iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
生成式 AI

MCP Server 全攻略:讓 AI 動態調用工具的工作流革命系列 第 11

[11] Mcp Server Tool 註冊的三種方式

  • 分享至 

  • xImage
  •  

我發現官方網站上的範例其實有點過時, 舉註冊 tool 的方式為例, 可以看到在官方 github readme 已經說建議用 registerTool 來做:

// Using registerTool (recommended)
server.registerTool("my_tool", {
  title: "My Tool",              // This title takes precedence
  annotations: {
    title: "Annotation Title"    // This is ignored if title is set
  }
}, handler);

// Using tool with annotations (older API)
server.tool("my_tool", "description", {
  title: "Annotation Title"      // This is used as title
}, handler);

我們用註冊 create_journal 為例比較三者寫法:

官方網站 (不建議):

server.tool(
  'create_journal',
  'Create a new journal',
  {
    content: z.string(),
    date: z.string(),
  },
  async ({ content, date }) => {
    journals.push({ content, date });
    return { success: true };
  },
);

官方 github readme:

ref: https://github.com/JHIH-LEI/simple-journal-mcp/blob/main/src/index.ts

server.registerTool(
  'create_journal',
  {
      description: 'Create a new journal',
      inputSchema: {
        content: z.string(),
        date: z.string(),
      },
  },
  async ({ content, date }) => {
    journals.push({ content, date });
    return { success: true };
  },
);

開源範例

這裡用 server.setRequestHandler 來攔截特定 request schema(如 ListToolsRequestSchema),並回傳工具清單。
後面還需要自己定義每一個工具對應的 handler 是什麼, 會藉由攔截 CallToolRequestSchema 做。

server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
            {
                name: 'create_journal',
                description: 'Create a new journal entry',
                inputSchema: {
                    type: 'object',
                    properties: {
                        content: {
                            type: 'string',
                            description: 'Content of the journal entry',
                        },
                        date: {
                            type: 'string',
                            description: 'Date in YYYY-MM-DD format',
                        },
                    },
                    required: ['content', 'date'],
                },
            },
          ]
        }
      }

後來我把 server.tool 的寫法都暫且改成跟開源專案看到的一致, 如果想看完整的原始碼可至:

https://github.com/JHIH-LEI/simple-journal-mcp/blob/main/src/index.ts


上一篇
[10] Claude Desktop 運行 STDIO Mcp Server
下一篇
[12] MCP Server 授權方式解析:STDIO 與 HTTP 比較
系列文
MCP Server 全攻略:讓 AI 動態調用工具的工作流革命12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言