从零封装MCP Server:让WorkBuddy 听懂你的工具

📅 2026/7/18 23:54:55
从零封装MCP Server:让WorkBuddy 听懂你的工具
从零封装 MCP Server让 WorkBuddy 听懂你的工具什么是 MCPMCPModel Context Protocol是 Anthropic 推出的开放协议让 AI 助手如 WorkBuddy可以安全地调用外部工具和API。它就像一个标准化的插件接口——你写好服务端AI 就能自动发现并调用你的工具。核心概念只有三个Server你写的服务端程序注册了多个工具Tool一个具体的功能比如「发帖到知乎」Transport通信方式通常是 stdio——标准输入输出第一步项目结构一个最小化的 MCP Server 只需要三个文件my-mcp-server/ ├── package.json # 依赖声明 ├── tsconfig.json # TS 编译配置 └── src/ └── index.ts # MCP Server 入口第二步package.json{name:my-mcp-server,version:1.0.0,type:module,scripts:{build:tsc,start:node dist/index.js},dependencies:{modelcontextprotocol/sdk:^1.0.4},devDependencies:{typescript:^5.7.2,types/node:^22.10.0}}第三步编写 Serverimport{Server}frommodelcontextprotocol/sdk/server/index.js;import{StdioServerTransport}frommodelcontextprotocol/sdk/server/stdio.js;import{CallToolRequestSchema,ListToolsRequestSchema}frommodelcontextprotocol/sdk/types.js;// 1. 创建 ServerconstservernewServer({name:my-mcp,version:1.0.0},{capabilities:{tools:{}}});// 2. 注册工具列表server.setRequestHandler(ListToolsRequestSchema,async()({tools:[{name:hello_world,description:打个招呼,inputSchema:{type:object,properties:{name:{type:string,description:你的名字}},required:[name]}}]}));// 3. 处理工具调用server.setRequestHandler(CallToolRequestSchema,async(req){const{name,arguments:args}req.params;if(namehello_world){return{content:[{type:text,text:你好${args.name}}]};}return{content:[{type:text,text:未知工具}],isError:true};});// 4. 启动consttransportnewStdioServerTransport();awaitserver.connect(transport);console.error(MCP Server started);第四步注册到 WorkBuddy编译后在~/.workbuddy/mcp.json中添加{mcpServers:{my-mcp:{command:node,args:[/path/to/my-mcp-server/dist/index.js],cwd:/path/to/my-mcp-server,disabled:false}}}重启 WorkBuddy去连接器面板点「信任」你的工具就生效了。进阶接入 Playwright 浏览器实际项目中你通常需要在 MCP Server 里集成浏览器自动化。以下是一个带 Playwright 的完整示例import{chromium}fromplaywright;// 在工具处理中启动浏览器server.setRequestHandler(CallToolRequestSchema,async(req){const{name,arguments:args}req.params;if(namescreenshot){constbrowserawaitchromium.launch({headless:true});constpageawaitbrowser.newPage();awaitpage.goto(args.url);constpathscreenshot-${Date.now()}.png;awaitpage.screenshot({path});awaitbrowser.close();return{content:[{type:text,text:截图已保存:${path}}]};}return{content:[{type:text,text:未知工具}],isError:true};});关键踩坑ESM 模式MCP SDK 只支持 ESMpackage.json 必须声明type: modulestdio 通信不要用 console.log 输出普通内容用 console.error 输出日志stdout 被 MCP 协议占用路径问题mcp.json 里的 command 和 args 要用绝对路径~/不会被展开端口冲突stdio 模式下不存在端口冲突问题最佳实践维度建议错误处理每个工具调用都要 try/catch返回友好的错误信息超时控制网络请求设置 30s 超时避免 WorkBuddy 卡死日志用 console.error 输出操作日志方便排查版本管理SemVer 严格管理工具定义变更时更新 schema测试用 echo ‘{“method”:“tools/list”}’总结从零到一封装一个 MCP Server 只需要 4 步创建项目 → 安装 SDK写 index.ts → 注册工具 处理调用配置 mcp.json → 让 WorkBuddy 识别去连接器面板点「信任」完整代码约 50 行半小时能跑通。真正花时间的是工具本身的业务逻辑