Ian Chou's Blog

最小可行性 MCP Server (Code Walkthrough)

最小可行性 MCP Server (Code Walkthrough)

這段程式碼展示了如何使用 TypeScript/JavaScript 建立一個 最小可行性的 Model Context Protocol (MCP) Server

它的核心功能是:建立一個伺服器,透過標準輸入/輸出 (Stdio) 與 MCP Client(例如 Claude Desktop, Cursor, 或其他 AI 代理)溝通,並提供一個名為 add 的工具讓 AI 調用。

以下是詳細的逐段解釋:


1. 引入必要的模組

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import * as z from "zod";

2. 初始化伺服器實例

const server = new McpServer({ name: "minimal-mcp", version: "1.0.0" });

3. 註冊工具 (Register Tool)

這是整段程式碼的靈魂,定義了 AI 可以使用的「技能」。

server.registerTool(
  "add", // 工具名稱 (Name)
  {
    title: "Add", // 人類可讀的標題
    description: "Add two numbers", // 給 AI 看的描述 (Prompt),讓 AI 知道何時該用這個工具
    inputSchema: { a: z.number(), b: z.number() }, // 輸入參數定義
    outputSchema: { result: z.number() } // 輸出格式定義 (選填,但在高階應用中有助於型別安全)
  },
  // 工具的執行邏輯 (Handler)
  async ({ a, b }) => {
    const output = { result: a + b };
    return {
      content: [{ type: "text", text: JSON.stringify(output) }],
      structuredContent: output // 回傳結構化資料
    };
  }
);

4. 連接與啟動

const transport = new StdioServerTransport();
await server.connect(transport);

5. 記錄日誌 (Logging) 的關鍵細節

console.error("minimal-mcp running (stdio)");

總結

這段程式碼是一個標準的 Local MCP Server 樣板。當你將它配置在 Claude Desktop 或 Cursor 中時,流程如下:

  1. Client 啟動這個 script (透過 node script.jsbun run script.ts)。
  2. Client 透過 stdin 發送 "ListTools" 請求。
  3. Server 回傳 JSON,告訴 Client:「我有個 add 工具,需要 ab」。
  4. 使用者問 AI:「100 加 200 是多少?」
  5. AI 決定呼叫 add 工具,Client 發送 JSON-RPC Call。
  6. Server 計算 300 並回傳。
  7. AI 收到結果,回答使用者:「答案是 300」。