mcp-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Server Development Guide
MCP 服务器开发指南
Overview
概述
To create high-quality MCP (Model Context Protocol) servers that enable LLMs to effectively interact with external services, use this skill. An MCP server provides tools that allow LLMs to access external services and APIs. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks using the tools provided.
若要创建能让LLM有效与外部服务交互的高质量MCP(Model Context Protocol)服务器,请使用本指南。MCP服务器提供工具,允许LLM访问外部服务和API。MCP服务器的质量衡量标准是,它能在多大程度上借助所提供的工具,让LLM完成实际任务。
Process
开发流程
🚀 High-Level Workflow
🚀 整体工作流
Creating a high-quality MCP server involves four main phases:
创建高质量MCP服务器包含四个主要阶段:
Phase 1: Deep Research and Planning
阶段1:深入研究与规划
1.1 Understand Agent-Centric Design Principles
1.1 理解以Agent为中心的设计原则
Before diving into implementation, understand how to design tools for AI agents by reviewing these principles:
Build for Workflows, Not Just API Endpoints:
- Don't simply wrap existing API endpoints - build thoughtful, high-impact workflow tools
- Consolidate related operations (e.g., that both checks availability and creates event)
schedule_event - Focus on tools that enable complete tasks, not just individual API calls
- Consider what workflows agents actually need to accomplish
Optimize for Limited Context:
- Agents have constrained context windows - make every token count
- Return high-signal information, not exhaustive data dumps
- Provide "concise" vs "detailed" response format options
- Default to human-readable identifiers over technical codes (names over IDs)
- Consider the agent's context budget as a scarce resource
Design Actionable Error Messages:
- Error messages should guide agents toward correct usage patterns
- Suggest specific next steps: "Try using filter='active_only' to reduce results"
- Make errors educational, not just diagnostic
- Help agents learn proper tool usage through clear feedback
Follow Natural Task Subdivisions:
- Tool names should reflect how humans think about tasks
- Group related tools with consistent prefixes for discoverability
- Design tools around natural workflows, not just API structure
Use Evaluation-Driven Development:
- Create realistic evaluation scenarios early
- Let agent feedback drive tool improvements
- Prototype quickly and iterate based on actual agent performance
在开始实现前,请先通过以下原则了解如何为AI Agent设计工具:
为工作流而非仅API端点构建:
- 不要简单封装现有API端点,要构建经过深思熟虑、高价值的工作流工具
- 整合相关操作(例如,可同时检查可用性并创建事件)
schedule_event - 专注于能完成完整任务的工具,而非仅单个API调用
- 考虑Agent实际需要完成哪些工作流
针对有限上下文进行优化:
- Agent的上下文窗口有限,要让每个token都发挥作用
- 返回高信息量的内容,而非详尽的数据转储
- 提供“简洁”与“详细”两种响应格式选项
- 默认使用人类可读的标识符而非技术代码(用名称而非ID)
- 将Agent的上下文预算视为稀缺资源
设计可操作的错误消息:
- 错误消息应引导Agent采用正确的使用方式
- 建议具体的下一步操作:“尝试使用filter='active_only'来减少结果数量”
- 让错误消息兼具教育性,而非仅用于诊断
- 通过清晰的反馈帮助Agent学习正确的工具使用方法
遵循自然任务细分:
- 工具名称应反映人类对任务的思考方式
- 使用一致的前缀对相关工具进行分组,便于发现
- 围绕自然工作流而非仅API结构设计工具
采用评估驱动的开发方式:
- 尽早创建真实的评估场景
- 根据Agent的反馈改进工具
- 快速原型开发,并基于Agent的实际性能迭代优化
1.3 Study MCP Protocol Documentation
1.3 学习MCP协议文档
Fetch the latest MCP protocol documentation:
Use WebFetch to load:
https://modelcontextprotocol.io/llms-full.txtThis comprehensive document contains the complete MCP specification and guidelines.
获取最新的MCP协议文档:
使用WebFetch加载:
https://modelcontextprotocol.io/llms-full.txt这份全面的文档包含完整的MCP规范与指南。
1.4 Study Framework Documentation
1.4 学习框架文档
Load and read the following reference files:
- MCP Best Practices: 📋 View Best Practices - Core guidelines for all MCP servers
For Python implementations, also load:
- Python SDK Documentation: Use WebFetch to load
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md - 🐍 Python Implementation Guide - Python-specific best practices and examples
For Node/TypeScript implementations, also load:
- TypeScript SDK Documentation: Use WebFetch to load
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md - ⚡ TypeScript Implementation Guide - Node/TypeScript-specific best practices and examples
加载并阅读以下参考文件:
- MCP最佳实践:📋 查看最佳实践 - 适用于所有MCP服务器的核心指南
若采用Python实现,还需加载:
- Python SDK文档:使用WebFetch加载
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md - 🐍 Python实现指南 - 针对Python的最佳实践与示例
若采用Node/TypeScript实现,还需加载:
- TypeScript SDK文档:使用WebFetch加载
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md - ⚡ TypeScript实现指南 - 针对Node/TypeScript的最佳实践与示例
1.5 Exhaustively Study API Documentation
1.5 全面研究API文档
To integrate a service, read through ALL available API documentation:
- Official API reference documentation
- Authentication and authorization requirements
- Rate limiting and pagination patterns
- Error responses and status codes
- Available endpoints and their parameters
- Data models and schemas
To gather comprehensive information, use web search and the WebFetch tool as needed.
要集成某一服务,请通读所有可用的API文档:
- 官方API参考文档
- 认证与授权要求
- 速率限制与分页模式
- 错误响应与状态码
- 可用端点及其参数
- 数据模型与架构
如需收集全面信息,可根据需要使用网页搜索和WebFetch工具。
1.6 Create a Comprehensive Implementation Plan
1.6 创建全面的实现计划
Based on your research, create a detailed plan that includes:
Tool Selection:
- List the most valuable endpoints/operations to implement
- Prioritize tools that enable the most common and important use cases
- Consider which tools work together to enable complex workflows
Shared Utilities and Helpers:
- Identify common API request patterns
- Plan pagination helpers
- Design filtering and formatting utilities
- Plan error handling strategies
Input/Output Design:
- Define input validation models (Pydantic for Python, Zod for TypeScript)
- Design consistent response formats (e.g., JSON or Markdown), and configurable levels of detail (e.g., Detailed or Concise)
- Plan for large-scale usage (thousands of users/resources)
- Implement character limits and truncation strategies (e.g., 25,000 tokens)
Error Handling Strategy:
- Plan graceful failure modes
- Design clear, actionable, LLM-friendly, natural language error messages which prompt further action
- Consider rate limiting and timeout scenarios
- Handle authentication and authorization errors
基于你的研究,制定详细计划,包含以下内容:
工具选择:
- 列出最有价值的端点/操作来实现
- 优先处理能支持最常见、最重要用例的工具
- 考虑哪些工具可协同工作以实现复杂工作流
共享工具与辅助函数:
- 识别通用API请求模式
- 规划分页辅助函数
- 设计过滤与格式化工具
- 规划错误处理策略
输入/输出设计:
- 定义输入验证模型(Python用Pydantic,TypeScript用Zod)
- 设计一致的响应格式(如JSON或Markdown),以及可配置的详细程度(如“详细”或“简洁”)
- 针对大规模使用场景进行规划(数千用户/资源)
- 实现字符限制与截断策略(如25000个token)
错误处理策略:
- 规划优雅的失败模式
- 设计清晰、可操作、适合LLM的自然语言错误消息,提示进一步操作
- 考虑速率限制与超时场景
- 处理认证与授权错误
Phase 2: Implementation
阶段2:实现开发
Now that you have a comprehensive plan, begin implementation following language-specific best practices.
制定完全面计划后,开始遵循语言特定的最佳实践进行实现。
2.1 Set Up Project Structure
2.1 搭建项目结构
For Python:
- Create a single file or organize into modules if complex (see 🐍 Python Guide)
.py - Use the MCP Python SDK for tool registration
- Define Pydantic models for input validation
For Node/TypeScript:
- Create proper project structure (see ⚡ TypeScript Guide)
- Set up and
package.jsontsconfig.json - Use MCP TypeScript SDK
- Define Zod schemas for input validation
针对Python:
- 若项目简单,创建单个文件;若复杂则按模块组织(参考🐍 Python指南)
.py - 使用MCP Python SDK进行工具注册
- 定义Pydantic模型用于输入验证
针对Node/TypeScript:
- 创建规范的项目结构(参考⚡ TypeScript指南)
- 配置和
package.jsontsconfig.json - 使用MCP TypeScript SDK
- 定义Zod schema用于输入验证
2.2 Implement Core Infrastructure First
2.2 先实现核心基础设施
To begin implementation, create shared utilities before implementing tools:
- API request helper functions
- Error handling utilities
- Response formatting functions (JSON and Markdown)
- Pagination helpers
- Authentication/token management
开始实现前,先创建共享工具,再实现具体工具:
- API请求辅助函数
- 错误处理工具
- 响应格式化函数(JSON和Markdown)
- 分页辅助函数
- 认证/令牌管理
2.3 Implement Tools Systematically
2.3 系统地实现工具
For each tool in the plan:
Define Input Schema:
- Use Pydantic (Python) or Zod (TypeScript) for validation
- Include proper constraints (min/max length, regex patterns, min/max values, ranges)
- Provide clear, descriptive field descriptions
- Include diverse examples in field descriptions
Write Comprehensive Docstrings/Descriptions:
- One-line summary of what the tool does
- Detailed explanation of purpose and functionality
- Explicit parameter types with examples
- Complete return type schema
- Usage examples (when to use, when not to use)
- Error handling documentation, which outlines how to proceed given specific errors
Implement Tool Logic:
- Use shared utilities to avoid code duplication
- Follow async/await patterns for all I/O
- Implement proper error handling
- Support multiple response formats (JSON and Markdown)
- Respect pagination parameters
- Check character limits and truncate appropriately
Add Tool Annotations:
- : true (for read-only operations)
readOnlyHint - : false (for non-destructive operations)
destructiveHint - : true (if repeated calls have same effect)
idempotentHint - : true (if interacting with external systems)
openWorldHint
针对计划中的每个工具:
定义输入Schema:
- 使用Pydantic(Python)或Zod(TypeScript)进行验证
- 包含适当的约束(最小/最大长度、正则表达式、最小/最大值、范围)
- 提供清晰、描述性的字段说明
- 在字段说明中包含多样的示例
编写全面的文档字符串/描述:
- 一行工具功能摘要
- 详细说明工具的用途与功能
- 明确参数类型并附带示例
- 完整的返回类型Schema
- 使用示例(何时使用、何时不使用)
- 错误处理文档,说明遇到特定错误时应如何处理
实现工具逻辑:
- 使用共享工具避免代码重复
- 所有I/O操作遵循async/await模式
- 实现适当的错误处理
- 支持多种响应格式(JSON和Markdown)
- 遵循分页参数要求
- 检查字符限制并进行适当截断
添加工具注解:
- : true(适用于只读操作)
readOnlyHint - : false(适用于非破坏性操作)
destructiveHint - : true(若重复调用效果相同)
idempotentHint - : true(若与外部系统交互)
openWorldHint
2.4 Follow Language-Specific Best Practices
2.4 遵循语言特定的最佳实践
At this point, load the appropriate language guide:
For Python: Load 🐍 Python Implementation Guide and ensure the following:
- Using MCP Python SDK with proper tool registration
- Pydantic v2 models with
model_config - Type hints throughout
- Async/await for all I/O operations
- Proper imports organization
- Module-level constants (CHARACTER_LIMIT, API_BASE_URL)
For Node/TypeScript: Load ⚡ TypeScript Implementation Guide and ensure the following:
- Using properly
server.registerTool - Zod schemas with
.strict() - TypeScript strict mode enabled
- No types - use proper types
any - Explicit Promise<T> return types
- Build process configured ()
npm run build
此时,请加载对应语言的指南:
针对Python:加载🐍 Python实现指南,并确保符合以下要求:
- 正确使用MCP Python SDK进行工具注册
- 使用带有的Pydantic v2模型
model_config - 全程使用类型提示
- 所有I/O操作使用async/await
- 合理组织导入
- 使用模块级常量(如CHARACTER_LIMIT、API_BASE_URL)
针对Node/TypeScript:加载⚡ TypeScript实现指南,并确保符合以下要求:
- 正确使用
server.registerTool - 使用带有的Zod schema
.strict() - 启用TypeScript严格模式
- 不使用类型,使用正确的类型定义
any - 明确Promise<T>返回类型
- 配置构建流程()
npm run build
Phase 3: Review and Refine
阶段3:审查与优化
After initial implementation:
完成初始实现后:
3.1 Code Quality Review
3.1 代码质量审查
To ensure quality, review the code for:
- DRY Principle: No duplicated code between tools
- Composability: Shared logic extracted into functions
- Consistency: Similar operations return similar formats
- Error Handling: All external calls have error handling
- Type Safety: Full type coverage (Python type hints, TypeScript types)
- Documentation: Every tool has comprehensive docstrings/descriptions
为确保质量,从以下方面审查代码:
- DRY原则:工具间无重复代码
- 可组合性:共享逻辑已提取为独立函数
- 一致性:相似操作返回相似格式
- 错误处理:所有外部调用均有错误处理
- 类型安全:完整的类型覆盖(Python类型提示、TypeScript类型)
- 文档:每个工具都有全面的文档字符串/描述
3.2 Test and Build
3.2 测试与构建
Important: MCP servers are long-running processes that wait for requests over stdio/stdin or sse/http. Running them directly in your main process (e.g., or ) will cause your process to hang indefinitely.
python server.pynode dist/index.jsSafe ways to test the server:
- Use the evaluation harness (see Phase 4) - recommended approach
- Run the server in tmux to keep it outside your main process
- Use a timeout when testing:
timeout 5s python server.py
For Python:
- Verify Python syntax:
python -m py_compile your_server.py - Check imports work correctly by reviewing the file
- To manually test: Run server in tmux, then test with evaluation harness in main process
- Or use the evaluation harness directly (it manages the server for stdio transport)
For Node/TypeScript:
- Run and ensure it completes without errors
npm run build - Verify dist/index.js is created
- To manually test: Run server in tmux, then test with evaluation harness in main process
- Or use the evaluation harness directly (it manages the server for stdio transport)
重要提示: MCP服务器是长期运行的进程,会通过stdio/stdin或sse/http等待请求。直接在主进程中运行(如或)会导致进程无限挂起。
python server.pynode dist/index.js安全的服务器测试方式:
- 使用评估工具包(见阶段4)- 推荐方式
- 在tmux中运行服务器,使其独立于主进程
- 测试时使用超时命令:
timeout 5s python server.py
针对Python:
- 验证Python语法:
python -m py_compile your_server.py - 通过查看文件确认导入是否正确
- 手动测试方法:在tmux中运行服务器,然后在主进程中使用评估工具包测试
- 或直接使用评估工具包(它会为stdio传输管理服务器)
针对Node/TypeScript:
- 运行并确保无错误完成
npm run build - 确认dist/index.js已生成
- 手动测试方法:在tmux中运行服务器,然后在主进程中使用评估工具包测试
- 或直接使用评估工具包(它会为stdio传输管理服务器)
3.3 Use Quality Checklist
3.3 使用质量检查清单
To verify implementation quality, load the appropriate checklist from the language-specific guide:
- Python: see "Quality Checklist" in 🐍 Python Guide
- Node/TypeScript: see "Quality Checklist" in ⚡ TypeScript Guide
为验证实现质量,请从对应语言的指南中加载检查清单:
- Python:查看🐍 Python指南中的“质量检查清单”
- Node/TypeScript:查看⚡ TypeScript指南中的“质量检查清单”
Phase 4: Create Evaluations
阶段4:创建评估用例
After implementing your MCP server, create comprehensive evaluations to test its effectiveness.
Load ✅ Evaluation Guide for complete evaluation guidelines.
实现MCP服务器后,请创建全面的评估用例来测试其有效性。
加载✅ 评估指南获取完整的评估准则。
4.1 Understand Evaluation Purpose
4.1 理解评估目的
Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
评估用于测试LLM能否有效使用你的MCP服务器,回答真实的复杂问题。
4.2 Create 10 Evaluation Questions
4.2 创建10个评估问题
To create effective evaluations, follow the process outlined in the evaluation guide:
- Tool Inspection: List available tools and understand their capabilities
- Content Exploration: Use READ-ONLY operations to explore available data
- Question Generation: Create 10 complex, realistic questions
- Answer Verification: Solve each question yourself to verify answers
要创建有效的评估用例,请遵循评估指南中概述的流程:
- 工具检查:列出可用工具并了解其功能
- 内容探索:使用只读操作探索可用数据
- 问题生成:创建10个复杂、真实的问题
- 答案验证:自行解决每个问题以验证答案正确性
4.3 Evaluation Requirements
4.3 评估要求
Each question must be:
- Independent: Not dependent on other questions
- Read-only: Only non-destructive operations required
- Complex: Requiring multiple tool calls and deep exploration
- Realistic: Based on real use cases humans would care about
- Verifiable: Single, clear answer that can be verified by string comparison
- Stable: Answer won't change over time
每个问题必须满足:
- 独立性:不依赖其他问题
- 只读性:仅需非破坏性操作
- 复杂性:需要多次调用工具并深入探索
- 真实性:基于人类实际关心的用例
- 可验证性:答案唯一、清晰,可通过字符串比对验证
- 稳定性:答案不会随时间变化
4.4 Output Format
4.4 输出格式
Create an XML file with this structure:
xml
<evaluation>
<qa_pair>
<question>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?</question>
<answer>3</answer>
</qa_pair>
<!-- More qa_pairs... -->
</evaluation>创建如下结构的XML文件:
xml
<evaluation>
<qa_pair>
<question>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?</question>
<answer>3</answer>
</qa_pair>
<!-- More qa_pairs... -->
</evaluation>Reference Files
参考文件
📚 Documentation Library
📚 文档库
Load these resources as needed during development:
开发过程中可按需加载以下资源:
Core MCP Documentation (Load First)
核心MCP文档(优先加载)
- MCP Protocol: Fetch from - Complete MCP specification
https://modelcontextprotocol.io/llms-full.txt - 📋 MCP Best Practices - Universal MCP guidelines including:
- Server and tool naming conventions
- Response format guidelines (JSON vs Markdown)
- Pagination best practices
- Character limits and truncation strategies
- Tool development guidelines
- Security and error handling standards
- MCP协议:从获取 - 完整的MCP规范
https://modelcontextprotocol.io/llms-full.txt - 📋 MCP最佳实践 - 通用MCP指南,包含:
- 服务器与工具命名规范
- 响应格式指南(JSON vs Markdown)
- 分页最佳实践
- 字符限制与截断策略
- 工具开发指南
- 安全与错误处理标准
SDK Documentation (Load During Phase 1/2)
SDK文档(阶段1/2加载)
- Python SDK: Fetch from
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md - TypeScript SDK: Fetch from
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md
- Python SDK:从获取
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md - TypeScript SDK:从获取
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md
Language-Specific Implementation Guides (Load During Phase 2)
语言特定实现指南(阶段2加载)
-
🐍 Python Implementation Guide - Complete Python/FastMCP guide with:
- Server initialization patterns
- Pydantic model examples
- Tool registration with
@mcp.tool - Complete working examples
- Quality checklist
-
⚡ TypeScript Implementation Guide - Complete TypeScript guide with:
- Project structure
- Zod schema patterns
- Tool registration with
server.registerTool - Complete working examples
- Quality checklist
-
🐍 Python实现指南 - 完整的Python/FastMCP指南,包含:
- 服务器初始化模式
- Pydantic模型示例
- 使用注册工具
@mcp.tool - 完整的工作示例
- 质量检查清单
-
⚡ TypeScript实现指南 - 完整的TypeScript指南,包含:
- 项目结构
- Zod schema模式
- 使用注册工具
server.registerTool - 完整的工作示例
- 质量检查清单
Evaluation Guide (Load During Phase 4)
评估指南(阶段4加载)
- ✅ Evaluation Guide - Complete evaluation creation guide with:
- Question creation guidelines
- Answer verification strategies
- XML format specifications
- Example questions and answers
- Running an evaluation with the provided scripts
- ✅ 评估指南 - 完整的评估用例创建指南,包含:
- 问题创建准则
- 答案验证策略
- XML格式规范
- 问题与答案示例
- 使用提供的脚本运行评估