SuperAPI AI 工具集

build-mcp-sdk-server

智能体与模型

查看项目

更新于 10-16 06:45

技能介绍

用途:使用官方 TypeScript SDK v2(main 分支)构建 MCP 服务器,目标包为 @modelcontextprotocol/server;若代码仍导入 @modelcontextprotocol/sdk,应先阅读 v1 到 v2 迁移文档。注意上游 README 将 v2 main 标记为 pre-alpha,v1.x 仍是生产推荐版本,故此处 v2 指引不代表生产稳定性。

主要能力与用法:涵盖项目脚手架与传输选择、注册工具/资源/提示词、用户输入收集(elicitation)、工具内调用 LLM(sampling)、长任务(实验性)以及部署(Claude Desktop stdio、生产 HTTP)。

安装:npm init -y;npm install @modelcontextprotocol/server zod;npm install -D typescript tsx @types/node。package.json 需设 "type": "module"。如用 Streamable HTTP,按需安装 @modelcontextprotocol/node、@modelcontextprotocol/express express 等适配器。最小 stdio 服务器使用 McpServer 与 StdioServerTransport,通过 server.registerTool 注册工具,命令 npx @modelcontextprotocol/inspector tsx src/index.ts 可即时测试。

关键实践:声明 outputSchema 时同时返回 content 与 structuredContent;工具回调中捕获异常,返回 isError: true 而非抛出;动态资源用 ResourceTemplate 并提供 list 回调。传输选择:stdio 适合单客户端进程派生;Streamable HTTP 无状态适合生产 API/无服务器,有状态适合会话;SSE 自 2025 年 3 月弃用。

限制:v2 为预发布,生产建议 v1.x;避免使用 v1 的 server.tool();Zod 字段应加 .describe();响应大小需受控;密钥经环境变量传入而非硬编码。其余细节以参考资料为准。