mcp-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP Server Development Guide

MCP Server 开发指南

Build high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services.

构建高质量的MCP(Model Context Protocol)服务器,使LLM能够与外部服务进行交互。

Core Design Principles

核心设计原则

Build for Workflows, Not Just APIs

为工作流而非单纯API构建

PrincipleWhy
Consolidate operationsSingle tool for complete tasks
Return high-signal dataAgents have limited context
Provide format options"concise" vs "detailed" modes
Use human-readable IDsNot technical codes
Make errors actionableGuide toward correct usage
Key concept: Don't just wrap API endpoints. Design tools that enable complete workflows agents actually need.

原则原因
整合操作单个工具完成完整任务
返回高信号数据Agent的上下文有限
提供格式选项"简洁"与"详细"模式
使用人类可读ID而非技术编码
提供可操作的错误信息引导正确使用方式
核心概念:不要仅仅封装API端点。要设计能支持Agent实际所需完整工作流的工具。

Development Phases

开发阶段

Phase 1: Research

第一阶段:调研

StepAction
Study MCP ProtocolRead
modelcontextprotocol.io/llms-full.txt
Study SDK docsPython or TypeScript SDK README
Study target APIRead ALL available documentation
Create implementation planBefore writing code
步骤操作
学习MCP协议阅读
modelcontextprotocol.io/llms-full.txt
学习SDK文档Python或TypeScript SDK的README
研究目标API阅读所有可用文档
创建实现计划编写代码前完成

Phase 2: Design

第二阶段:设计

DecisionOptions
LanguagePython (FastMCP) or TypeScript
Tool granularityAtomic vs workflow-oriented
Response formatJSON, Markdown, or both
Error handlingWhat errors can occur, how to recover
决策项选项
开发语言Python(FastMCP)或TypeScript
工具粒度原子化 vs 面向工作流
响应格式JSON、Markdown或两者兼具
错误处理可能出现的错误及恢复方式

Phase 3: Implementation

第三阶段:实现

ComponentPurpose
Input validationPydantic (Python) or Zod (TypeScript)
Tool descriptionsClear, with examples
Error messagesInclude suggested next steps
Response formattingConsistent across tools
组件用途
输入验证使用Pydantic(Python)或Zod(TypeScript)
工具描述清晰且附带示例
错误信息包含建议的下一步操作
响应格式化所有工具保持一致

Phase 4: Testing

第四阶段:测试

Critical: MCP servers are long-running processes. Never run directly in main process.
ApproachHow
Evaluation harnessRecommended
tmux sessionRun server separately
Timeout wrapper
timeout 5s python server.py
MCP InspectorOfficial debugging tool

重点提示:MCP服务器是长期运行的进程。切勿直接在主进程中运行。
方法操作方式
评估工具集推荐使用
tmux会话单独运行服务器
超时包装器
timeout 5s python server.py
MCP Inspector官方调试工具

Tool Annotations

工具注解

AnnotationMeaningDefault
readOnlyHintDoesn't modify statefalse
destructiveHintCan cause damagetrue
idempotentHintRepeated calls safefalse
openWorldHintInteracts externallytrue
Key concept: Annotations help the LLM decide when and how safely to use tools.

注解含义默认值
readOnlyHint不修改状态false
destructiveHint可能造成损坏true
idempotentHint重复调用安全false
openWorldHint与外部交互true
核心概念:注解帮助LLM判断何时以及如何安全使用工具。

Input Design

输入设计

Validation Patterns

验证模式

PatternUse Case
Required fieldsCore parameters
Optional with defaultsConvenience parameters
EnumsLimited valid values
Min/max constraintsNumeric bounds
Pattern matchingFormat validation (email, URL)
模式使用场景
必填字段核心参数
带默认值的可选字段便捷参数
枚举类型有限的有效值
最小/最大值约束数值范围
模式匹配格式验证(邮箱、URL)

Parameter Naming

参数命名

GoodBadWhy
user_email
e
Self-documenting
limit
max_results_to_return
Concise but clear
include_archived
ia
Descriptive boolean

良好示例不良示例原因
user_email
e
自文档化
limit
max_results_to_return
简洁且清晰
include_archived
ia
描述性布尔值

Response Design

响应设计

Format Options

格式选项

FormatUse Case
JSONProgrammatic use, structured data
MarkdownHuman readability, reports
HybridJSON in markdown code blocks
格式使用场景
JSON程序化使用、结构化数据
Markdown人类可读性、报告
混合格式Markdown代码块中的JSON

Response Guidelines

响应指南

GuidelineWhy
~25,000 token limitContext constraints
Truncate with indicatorDon't silently cut
Support pagination
limit
and
offset
params
Include metadataTotal count, has_more

指南原因
~25,000 tokens限制上下文约束
截断时添加标识不要静默截断
支持分页
limit
offset
参数
包含元数据总数、是否还有更多数据

Error Handling

错误处理

Error Message Structure

错误消息结构

ElementPurpose
What failedClear description
Why it failedRoot cause if known
How to fixSuggested next action
ExampleCorrect usage
Key concept: Error messages should guide the agent toward correct usage, not just diagnose problems.

元素用途
失败内容清晰描述
失败原因已知的根本原因
修复方式建议的下一步操作
示例正确用法
核心概念:错误消息应引导Agent正确使用,而非仅仅诊断问题。

Quality Checklist

质量检查表

Code Quality

代码质量

CheckDescription
No duplicated codeExtract shared logic
Consistent formatsSimilar ops return similar structure
Full error handlingAll external calls wrapped
Type coverageAll inputs/outputs typed
Comprehensive docstringsEvery tool documented
检查项描述
无重复代码提取共享逻辑
格式一致类似操作返回相似结构
完整错误处理所有外部调用均被包装
类型覆盖所有输入/输出均已类型化
全面的文档字符串每个工具都有文档

Tool Quality

工具质量

CheckDescription
Clear descriptionsModel knows when to use
Good examplesIn docstring
Sensible defaultsReduce required params
Consistent namingGroup related with prefixes

检查项描述
清晰的描述模型知晓何时使用
优质示例包含在文档字符串中
合理的默认值减少所需参数
一致的命名使用前缀分组相关工具

Best Practices

最佳实践

PracticeWhy
One tool = one purposeClear mental model
Comprehensive descriptionsLLM selection accuracy
Include examples in docstringsShow expected usage
Return actionable errorsEnable self-correction
Test with actual LLMReal-world validation
Version your serverTrack compatibility
实践原因
一个工具对应一个用途清晰的心智模型
全面的描述提升LLM选择准确性
在文档字符串中包含示例展示预期用法
返回可操作的错误支持自我修正
使用实际LLM测试真实场景验证
为服务器版本化跟踪兼容性

Resources

资源