Skip to main content

构建 MCP Server

4.1 开发环境准备

TypeScript (推荐)

Python

4.2 TypeScript完整示例

一个提供天气查询工具的MCP Server:

多工具Server(含outputSchema和structuredContent)

协议版本 2025-11-25 支持 outputSchema 定义工具的结构化输出格式,并通过 structuredContent 返回结构化数据:

4.3 Python完整示例

4.4 暴露Resources

除了工具,Server还可以暴露数据资源:

4.5 Streamable HTTP Server

远程部署时使用Streamable HTTP传输:

4.6 测试和调试

MCP Inspector

官方提供的调试工具:
Inspector会启动一个Web界面,让你交互式地测试每个工具。你可以:
  • 查看Server暴露的所有工具、资源、提示词
  • 手动输入参数执行工具
  • 查看JSON-RPC请求和响应的原始数据
  • 验证inputSchema和outputSchema

在Claude Desktop中测试

编辑Claude Desktop配置文件: macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json
重启Claude Desktop,在对话中尝试使用你的工具。

4.7 常见错误

stdio Server绝对不能用 console.log。stdout是协议通道,任何非JSON-RPC的输出都会破坏通信。用 console.error 或写文件日志。

下一章: 商务MCP Server — 电商场景的MCP Server设计模式