mcp-builder

mcp-builder

使用 mcp-use 框架建置 Model Context Protocol (MCP) 伺服器。當建立 MCP 伺服器、定義工具/資源/提示詞、使用 mcp-use、初始化 MCP 專案、部署 MCP 伺服器,或使用者提及 MCP 開發、MCP 工具、MCP 資源或 MCP 提示詞時使用。

1星標
2分支
更新於 2026/1/31
SKILL.md
唯讀
名稱
mcp-builder
描述

使用 mcp-use 框架建置 Model Context Protocol (MCP) 伺服器。當建立 MCP 伺服器、定義工具/資源/提示詞、使用 mcp-use、初始化 MCP 專案、部署 MCP 伺服器,或使用者提及 MCP 開發、MCP 工具、MCP 資源或 MCP 提示詞時使用。

MCP Server Builder

使用 mcp-use 框架建置生產級別的 MCP 伺服器。此 Skill 提供建立 MCP 伺服器的快速入門說明與最佳實踐。

快速入門

永遠建議使用 npx create-mcp-use-app 初始化專案:

npx create-mcp-use-app my-mcp-server
cd my-mcp-server

根據需求選擇範本:

  • --template starter - 功能完整,包含所有 MCP 原語(工具、資源、提示詞)+ 範例 Widget
  • --template mcp-apps - 針對 ChatGPT Widget 最佳化,包含商品搜尋範例
  • --template blank - 極簡起點,適合自訂實作
# 範例:MCP Apps 範本
npx create-mcp-use-app my-server --template mcp-apps
cd my-server
yarn install

範本細節:

  • starter:最適合學習 - 包含所有 MCP 功能與 Widget
  • mcp-apps:最適合 ChatGPT 應用程式 - 包含商品輪播/折疊選單範例
  • blank:最適合專家 - 極簡模板

MCP Apps 結構

自動註冊 Widget

mcp-apps 與 starter 範本會自動探索並註冊 resources/ 資料夾中的 React Widget:

單一檔案 Widget 模式:

resources/
└── weather-display.tsx  # Widget 名稱會變成 "weather-display"

資料夾架構 Widget 模式:

resources/
└── product-search/      # Widget 名稱會變成 "product-search"
    ├── widget.tsx       # 入口點(必須使用此名稱!)
    ├── components/      # 子元件
    ├── hooks/           # 自訂 Hook
    ├── types.ts
    └── constants.ts

自動執行的流程:

  1. 伺服器在啟動時掃描 resources/ 資料夾
  2. 尋找 .tsx 檔案或資料夾中的 widget.tsx
  3. 從每個元件中擷取 widgetMetadata
  4. 註冊為 MCP 工具(例如 weather-display)
  5. 註冊為 MCP 資源(例如 ui://widget/weather-display.html)
  6. 使用 Vite 打包 Widget bundle

無需手動註冊! 只需匯出 widgetMetadata 與預設元件即可。

定義工具 (Tools)

工具是 AI 模型可以呼叫的可執行函式:

import { MCPServer, text, object } from "mcp-use/server";
import { z } from "zod";

const server = new MCPServer({
  name: "my-server",
  version: "1.0.0",
  description: "My MCP server"
});

// 簡單工具
server.tool(
  {
    name: "greet-user",
    description: "Greet a user by name",
    schema: z.object({
      name: z.string().describe("The user's name"),
      formal: z.boolean().optional().describe("Use formal greeting")
    })
  },
  async ({ name, formal }) => {
    const greeting = formal ? `Good day, ${name}` : `Hey ${name}!`;
    return text(greeting);
  }
);

關鍵要點:

  • 使用 Zod 進行 Schema 驗證
  • 為所有參數加上 .describe()
  • 回傳適當的回應類型(text, object, widget)

定義資源 (Resources)

資源用來暴露用戶端可以讀取的資料:

import { object, text, markdown } from "mcp-use/server";

// 靜態資源
server.resource(
  {
    uri: "config://settings",
    name: "Application Settings",
    description: "Current configuration",
    mimeType: "application/json"
  },
  async () => {
    return object({
      theme: "dark",
      version: "1.0.0"
    });
  }
);

// 動態資源
server.resource(
  {
    uri: "stats://current",
    name: "Current Stats",
    description: "Real-time statistics",
    mimeType: "application/json"
  },
  async () => {
    const stats = await getStats();
    return object(stats);
  }
);

// Markdown 資源
server.resource(
  {
    uri: "docs://guide",
    name: "User Guide",
    description: "Documentation",
    mimeType: "text/markdown"
  },
  async () => {
    return markdown("# Guide\n\nWelcome!");
  }
);

可用的回應 Helper:

  • text(string) - 純文字
  • object(data) - JSON 物件
  • markdown(string) - Markdown 內容
  • html(string) - HTML 內容
  • image(buffer, mimeType) - 二進位圖片
  • audio(buffer, mimeType) - 音訊檔案
  • binary(buffer, mimeType) - 二進位資料
  • mix(...contents) - 組合多種內容類型

進階回應範例:

// 音訊回應
import { audio } from 'mcp-use/server';

// 來自 Base64 資料
return audio(base64Data, "audio/wav");

// 來自檔案路徑 (非同步)
return await audio("/path/to/audio.mp3");

// 二進位資料 (PDF 等)
import { binary } from 'mcp-use/server';
return binary(pdfBuffer, "application/pdf");

// 混合多種內容類型
import { mix, text, object, resource } from 'mcp-use/server';
return mix(
  text("Analysis complete:"),
  object({ score: 95, status: "pass" }),
  resource("report://analysis-123", text("Full report..."))
);

定義提示詞 (Prompts)

提示詞是用於 AI 互動的可重用範本:

server.prompt(
  {
    name: "code-review",
    description: "Generate a code review template",
    schema: z.object({
      language: z.string().describe("Programming language"),
      focusArea: z.string().optional().describe("Specific focus area")
    })
  },
  async ({ language, focusArea }) => {
    const focus = focusArea ? ` with focus on ${focusArea}` : "";
    return {
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `Please review this ${language} code${focus}.`
          }
        }
      ]
    };
  }
);

本地端測試

開發模式(熱重載):

yarn dev

生產模式:

yarn build
yarn start

Inspector UI:
造訪 http://localhost:3000/inspector 以測試工具、檢視資源與嘗試提示詞。

Tunneling 隧道連線(部署前與 ChatGPT 一起測試):

選項 1 - 自動隧道:

mcp-use start --port 3000 --tunnel

選項 2 - 獨立隧道:

yarn start  # 終端機 1
npx @mcp-use/tunnel 3000  # 終端機 2

您將獲得公開 URL,如 https://happy-cat.local.mcp-use.run/mcp

隧道細節:

  • 24 小時後過期
  • 閒置 1 小時後自動關閉
  • 速率限制:每小時建立 10 個,每個 IP 最多 5 個作用中

瞭解更多:https://mcp-use.com/docs/tunneling

部署

部署至 mcp-use Cloud(推薦):

# 若尚未登入,請先登入
npx mcp-use login

# 部署
yarn deploy

如果遇到身分驗證錯誤:

npx mcp-use login
yarn deploy

部署完成後:

  • 提供公開 URL(例如 https://your-server.mcp-use.com/mcp)
  • 自動縮放與監控
  • 已啟用 HTTPS
  • 零停機時間部署

最佳實踐

工具設計:

  • ✅ 一個工具 = 一個專注的功能
  • ✅ 具描述性的名稱與說明
  • ✅ 在所有 Zod 欄位上使用 .describe()
  • ✅ 優雅地處理錯誤
  • ✅ 回傳有幫助的錯誤訊息

資源設計:

  • ✅ 使用清晰的 URI Schema (config://, docs://, stats://)
  • ✅ 選擇適當的 MIME 類型
  • ✅ 使用回應 Helper 撰寫更乾淨的程式碼
  • ✅ 需要時將資源設計為動態

提示詞設計:

  • ✅ 保持提示詞可重用
  • ✅ 使用系統訊息提供上下文
  • ✅ 使用 Zod Schema 進行參數化
  • ✅ 包含清晰的指示

測試:

  • ✅ 先使用 Inspector UI 測試
  • ✅ 部署前使用隧道與真實用戶端進行測試
  • ✅ 驗證所有工具、資源與提示詞是否依預期運作

部署:

  • ✅ 先在本地端以及透過隧道進行測試
  • ✅ 如果部署失敗,執行 npx mcp-use login
  • ✅ 對您的伺服器進行語意化版本控管
  • ✅ 記錄破壞性變更 (breaking changes)

Widget 支援

自動註冊 Widget

使用 mcp-apps 或 starter 範本時,resources/ 資料夾中的 Widget 會自動註冊:

// resources/weather-display.tsx
import { useWidget, McpUseProvider, type WidgetMetadata } from 'mcp-use/react';
import { z } from 'zod';

const propSchema = z.object({
  city: z.string(),
  temperature: z.number()
});

// 必須:匯出 widget metadata
export const widgetMetadata: WidgetMetadata = {
  description: "Display weather information",
  props: propSchema, // 請使用 'props',而非 'schema'!
};

// 必須:匯出預設元件
export default function WeatherDisplay() {
  const { props, isPending } = useWidget<z.infer<typeof propSchema>>();
  
  // 務必處理載入狀態
  if (isPending) return <div>Loading...</div>;
  
  return (
    <McpUseProvider autoSize>
      <div>
        <h2>{props.city}</h2>
        <p>{props.temperature}°C</p>
      </div>
    </McpUseProvider>
  );
}

Widget 自動可用為:

  • MCP 工具:weather-display
  • MCP 資源:ui://widget/weather-display.html

內容安全性政策 (CSP)

控制 Widget 可以存取的外部資源:

export const widgetMetadata: WidgetMetadata = {
  description: "Weather widget",
  props: z.object({ city: z.string() }),
  metadata: {
    csp: {
      // 要呼叫的 API
      connectDomains: ["https://api.weather.com"],
      // 要載入的靜態資產
      resourceDomains: ["https://cdn.weather.com"],
      // 要嵌入的 iframe
      frameDomains: ["https://embed.weather.com"],
      // 指令碼指示
      scriptDirectives: ["'unsafe-inline'"],
    },
  },
};

或者在伺服器層級設定:

server.uiResource({
  type: "mcpApps",
  name: "my-widget",
  htmlTemplate: `...`,
  metadata: {
    csp: {
      connectDomains: ["https://api.example.com"],
      resourceDomains: ["https://cdn.example.com"],
    },
  },
});

雙協定 Widget 支援

mcp-use 支援 MCP Apps 標準 (SEP-1865),且具備自動雙協定支援:

import { MCPServer } from 'mcp-use/server';

const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  baseUrl: process.env.MCP_URL || 'http://localhost:3000', // Widget 必需設定
});

// 註冊雙協定 Widget
server.uiResource({
  type: "mcpApps", // 同時支援 MCP Apps 用戶端與 ChatGPT
  name: "weather-display",
  htmlTemplate: `<!DOCTYPE html>...`,
  metadata: {
    csp: { connectDomains: ["https://api.weather.com"] },
    prefersBorder: true,
    autoResize: true,
  },
});

自動發生的處理:

  • MCP Apps 用戶端 (Claude, Goose) 接收到:text/html;profile=mcp-app 帶有 _meta.ui.*
  • ChatGPT 接收到:text/html+skybridge 帶有 _meta.openai/*
  • 同一套 Widget 程式碼隨處皆可執行!

自訂 OpenAI Metadata

需要 ChatGPT 專屬功能?結合兩個 metadata 欄位:

server.uiResource({
  type: "mcpApps",
  name: "my-widget",
  htmlTemplate: `...`,
  // 統一的 metadata (雙協定)
  metadata: {
    csp: { connectDomains: ["https://api.example.com"] },
    prefersBorder: true,
  },
  // ChatGPT 專屬的覆寫設定
  appsSdkMetadata: {
    "openai/widgetDescription": "ChatGPT-specific description",
    "openai/customFeature": "some-value", // 任何自訂的 OpenAI metadata
  },
});

專案結構

my-mcp-server/
├── resources/           # React Widget (apps-sdk)
│   └── widget.tsx
├── public/             # 靜態資產
├── index.ts            # 伺服器入口點
├── package.json
├── tsconfig.json
└── README.md

常見模式

帶有雙協定 Widget 的工具:

import { MCPServer, widget, text } from 'mcp-use/server';
import { z } from 'zod';

const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  baseUrl: process.env.MCP_URL || 'http://localhost:3000',
});

server.tool(
  {
    name: "show-data",
    description: "Display data with visualization",
    schema: z.object({
      query: z.string()
    }),
    widget: {
      name: "data-display", // 必須存在於 resources/ 中
      invoking: "Loading...",
      invoked: "Data loaded"
    }
  },
  async ({ query }) => {
    const data = await fetchData(query);
    return widget({
      props: { data },
      output: text(`Found ${data.length} results`)
    });
  }
);

資源範本(參數化):

server.resourceTemplate(
  {
    uriTemplate: "user://{userId}/profile",
    name: "User Profile",
    description: "Get user by ID",
    mimeType: "application/json"
  },
  async ({ userId }) => {
    const user = await fetchUser(userId);
    return object(user);
  }
);

錯誤處理:

server.tool(
  {
    name: "divide",
    schema: z.object({
      a: z.number(),
      b: z.number()
    })
  },
  async ({ a, b }) => {
    if (b === 0) {
      return text("Error: Cannot divide by zero");
    }
    return text(`Result: ${a / b}`);
  }
);

詳細範例

若要取得完整範例與進階模式,請連線至提供以下功能的 mcp-use MCP 伺服器:

  • 所有原語的完整範例資源
  • 完整可執行的伺服器範例
  • 詳細文件
  • 互動式 Widget 展示

瞭解更多

快速參考

指令:

  • npx create-mcp-use-app my-server - 快速初始化
  • yarn dev - 開發模式
  • yarn build - 建置為生產版本
  • yarn start - 執行生產伺服器
  • mcp-use start --tunnel - 啟動並建立隧道
  • npx mcp-use login - 進行身分驗證
  • yarn deploy - 部署至雲端

回應 Helper:

  • text(str), object(data), markdown(str), html(str)
  • image(buf, mime), audio(buf, mime), binary(buf, mime)
  • mix(...) - 組合多種內容類型
  • widget({ props, output }) - 回傳附帶資料的 Widget

伺服器方法:

  • server.tool() - 定義可執行工具
  • server.resource() - 定義靜態/動態資源
  • server.resourceTemplate() - 定義參數化資源
  • server.prompt() - 定義提示詞範本
  • server.uiResource() - 定義 Widget 資源
  • server.listen() - 啟動伺服器

Widget Metadata 欄位:

  • description - Widget 說明
  • props - Widget props 的 Zod schema
  • metadata - 統一設定 (雙協定)
  • metadata.csp - 內容安全性政策 (Content Security Policy)
  • appsSdkMetadata - ChatGPT 專屬覆寫設定

可用的範本:

  • starter - 功能完整(工具、資源、提示詞、Widget)
  • mcp-apps - ChatGPT 最佳化,包含商品範例
  • blank - 極簡起點模板