跳到主要内容

MCP 服务器构建

收藏0

从零写一个 MCP 服务器:怎么定义工具、选传输方式、处理错误与认证,附 Python 与 Node 两套服务器写法、评估方法和最佳实践。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-14下载 0 次

SKILL.md

10.9 KB查看排版效果
1---
2name: mcp-builder
3description: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
4license: Complete terms in LICENSE.txt
5---
6
7# MCP Server Development Guide
8
9## Overview
10
11Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.
12
13---
14
15# Process
16
17## 🚀 High-Level Workflow
18
19Creating a high-quality MCP server involves four main phases:
20
21### Phase 1: Deep Research and Planning
22
23#### 1.1 Understand Modern MCP Design
24
25**API Coverage vs. Workflow Tools:**
26Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.
27
28**Tool Naming and Discoverability:**
29Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming.
30
31**Context Management:**
32Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.
33
34**Actionable Error Messages:**
35Error messages should guide agents toward solutions with specific suggestions and next steps.
36
37#### 1.2 Study MCP Protocol Documentation
38
39**Navigate the MCP specification:**
40
41Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`
42
43Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).
44
45Key pages to review:
46- Specification overview and architecture
47- Transport mechanisms (streamable HTTP, stdio)
48- Tool, resource, and prompt definitions
49
50#### 1.3 Study Framework Documentation
51
52**Recommended stack:**
53- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)
54- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.
55
56**Load framework documentation:**
57
58- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines
59
60**For TypeScript (recommended):**
61
62The TypeScript SDK has two major versions. Pick one before writing code:
63- **v2** (`@modelcontextprotocol/server`): the current stable release. Use it for new servers.
64- **v1** (`@modelcontextprotocol/sdk`): receives bug and security fixes only. Use it only when the project's `package.json` already depends on `@modelcontextprotocol/sdk`, or migrate that project with `npx @modelcontextprotocol/codemod@latest v1-to-v2 .`
65
66If the project already uses v1, tell the user once, in a sentence or two, that v2 (`@modelcontextprotocol/server`) is the current stable release, that v1 receives only bug and security fixes, and that `npx @modelcontextprotocol/codemod@latest v1-to-v2 .` migrates the project. Then continue with v1 unless the user asks to migrate.
67
68Don't mix the two in one project: v1 code samples (imports from `@modelcontextprotocol/sdk/...`) don't apply to v2.
69
70- **TypeScript SDK (v2)**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`; the full docs index is `https://ts.sdk.modelcontextprotocol.io/v2/llms.txt`
71- [⚡ TypeScript Guide (v2)](./reference/node_mcp_server_v2.md) - TypeScript patterns and examples
72- For v1 projects only: `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.md` and the [TypeScript Guide (v1)](./reference/node_mcp_server.md)
73
74**For Python:**
75- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
76- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples
77
78#### 1.4 Plan Your Implementation
79
80**Understand the API:**
81Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
82
83**Tool Selection:**
84Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.
85
86---
87
88### Phase 2: Implementation
89
90#### 2.1 Set Up Project Structure
91
92See language-specific guides for project setup:
93- [⚡ TypeScript Guide (v2)](./reference/node_mcp_server_v2.md) - Project structure, package.json, tsconfig.json ([v1](./reference/node_mcp_server.md) for existing v1 projects)
94- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies
95
96#### 2.2 Implement Core Infrastructure
97
98Create shared utilities:
99- API client with authentication
100- Error handling helpers
101- Response formatting (JSON/Markdown)
102- Pagination support
103
104#### 2.3 Implement Tools
105
106For each tool:
107
108**Input Schema:**
109- Use Zod (TypeScript) or Pydantic (Python)
110- Include constraints and clear descriptions
111- Add examples in field descriptions
112
113**Output Schema:**
114- Define `outputSchema` where possible for structured data
115- Use `structuredContent` in tool responses (TypeScript SDK feature)
116- Helps clients understand and process tool outputs
117
118**Tool Description:**
119- Concise summary of functionality
120- Parameter descriptions
121- Return type schema
122
123**Implementation:**
124- Async/await for I/O operations
125- Proper error handling with actionable messages
126- Support pagination where applicable
127- Return both text content and structured data when using modern SDKs
128
129**Annotations:**
130- `readOnlyHint`: true/false
131- `destructiveHint`: true/false
132- `idempotentHint`: true/false
133- `openWorldHint`: true/false
134
135---
136
137### Phase 3: Review and Test
138
139#### 3.1 Code Quality
140
141Review for:
142- No duplicated code (DRY principle)
143- Consistent error handling
144- Full type coverage
145- Clear tool descriptions
146
147#### 3.2 Build and Test
148
149**TypeScript:**
150- Run `npm run build` to verify compilation
151- v2 projects: run the self-check script from the [v2 guide](./reference/node_mcp_server_v2.md#verify-your-server) against the built server
152- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`
153
154**Python:**
155- Verify syntax: `python -m py_compile your_server.py`
156- Test with MCP Inspector
157
158See language-specific guides for detailed testing approaches and quality checklists.
159
160---
161
162### Phase 4: Create Evaluations
163
164After implementing your MCP server, create comprehensive evaluations to test its effectiveness.
165
166**Load [✅ Evaluation Guide](./reference/evaluation.md) for complete evaluation guidelines.**
167
168#### 4.1 Understand Evaluation Purpose
169
170Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
171
172#### 4.2 Create 10 Evaluation Questions
173
174To create effective evaluations, follow the process outlined in the evaluation guide:
175
1761. **Tool Inspection**: List available tools and understand their capabilities
1772. **Content Exploration**: Use READ-ONLY operations to explore available data
1783. **Question Generation**: Create 10 complex, realistic questions
1794. **Answer Verification**: Solve each question yourself to verify answers
180
181#### 4.3 Evaluation Requirements
182
183Ensure each question is:
184- **Independent**: Not dependent on other questions
185- **Read-only**: Only non-destructive operations required
186- **Complex**: Requiring multiple tool calls and deep exploration
187- **Realistic**: Based on real use cases humans would care about
188- **Verifiable**: Single, clear answer that can be verified by string comparison
189- **Stable**: Answer won't change over time
190
191#### 4.4 Output Format
192
193Create an XML file with this structure:
194
195```xml
196<evaluation>
197 <qa_pair>
198 <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>
199 <answer>3</answer>
200 </qa_pair>
201<!-- More qa_pairs... -->
202</evaluation>
203```
204
205---
206
207# Reference Files
208
209## 📚 Documentation Library
210
211Load these resources as needed during development:
212
213### Core MCP Documentation (Load First)
214- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix
215- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including:
216 - Server and tool naming conventions
217 - Response format guidelines (JSON vs Markdown)
218 - Pagination best practices
219 - Transport selection (streamable HTTP vs stdio)
220 - Security and error handling standards
221
222### SDK Documentation (Load During Phase 1/2)
223- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
224- **TypeScript SDK (v2)**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`; full docs index at `https://ts.sdk.modelcontextprotocol.io/v2/llms.txt`
225- **TypeScript SDK (v1, existing v1 projects only)**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.md`
226
227### Language-Specific Implementation Guides (Load During Phase 2)
228- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Complete Python/FastMCP guide with:
229 - Server initialization patterns
230 - Pydantic model examples
231 - Tool registration with `@mcp.tool`
232 - Complete working examples
233 - Quality checklist
234
235- [⚡ TypeScript Implementation Guide (SDK v2)](./reference/node_mcp_server_v2.md) - Complete TypeScript guide for `@modelcontextprotocol/server` with:
236 - Project setup and the server factory
237 - Tool design: Zod 4 schemas, output formats, pagination, errors
238 - A complete example serving stdio and Streamable HTTP, plus bearer auth
239 - Resources, prompts, and notifications
240 - A self-check script to verify the built server
241 - Links to SDK examples for advanced features
242 - A v1 → v2 translation table, migration steps, and a quality checklist
243
244- [⚡ TypeScript Implementation Guide (SDK v1)](./reference/node_mcp_server.md) - The equivalent guide for existing `@modelcontextprotocol/sdk` projects
245
246### Evaluation Guide (Load During Phase 4)
247- [✅ Evaluation Guide](./reference/evaluation.md) - Complete evaluation creation guide with:
248 - Question creation guidelines
249 - Answer verification strategies
250 - XML format specifications
251 - Example questions and answers
252 - Running an evaluation with the provided scripts

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。