mcp-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Development
MCP开发
What is MCP?
什么是MCP?
The Model Context Protocol (MCP) is an open protocol that enables AI assistants to interact with external tools, data sources, and services in a standardized way.
Model Context Protocol(MCP)是一种开放协议,可让AI助手以标准化方式与外部工具、数据源和服务进行交互。
Core Concepts
核心概念
| Concept | Description |
|---|---|
| Tools | Functions the AI can call |
| Resources | Data the AI can read |
| Prompts | Pre-defined prompt templates |
| Transports | Communication methods (stdio, HTTP) |
| 概念 | 描述 |
|---|---|
| Tools | AI可调用的功能 |
| Resources | AI可读取的数据 |
| Prompts | 预定义的提示模板 |
| Transports | 通信方式(stdio、HTTP) |
MCP Server Structure
MCP服务器结构
typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "my-mcp-server",
version: "1.0.0",
}, {
capabilities: {
tools: {},
resources: {},
}
});
// Define tools
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "get_data",
description: "Fetch data from the API",
inputSchema: {
type: "object",
properties: {
id: { type: "string", description: "Item ID" }
},
required: ["id"]
}
}
]
}));
// Handle tool calls
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "get_data") {
const result = await fetchData(args.id);
return { content: [{ type: "text", text: JSON.stringify(result) }] };
}
throw new Error(`Unknown tool: ${name}`);
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "my-mcp-server",
version: "1.0.0",
}, {
capabilities: {
tools: {},
resources: {},
}
});
// Define tools
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "get_data",
description: "Fetch data from the API",
inputSchema: {
type: "object",
properties: {
id: { type: "string", description: "Item ID" }
},
required: ["id"]
}
}
]
}));
// Handle tool calls
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "get_data") {
const result = await fetchData(args.id);
return { content: [{ type: "text", text: JSON.stringify(result) }] };
}
throw new Error(`Unknown tool: ${name}`);
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);Tool Design Best Practices
工具设计最佳实践
Clear Descriptions
清晰的描述
typescript
{
name: "search_documents",
description: "Search documents by keyword. Returns matching documents with relevance scores. Use when the user asks to find or search for specific content.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query - can include multiple keywords"
},
limit: {
type: "integer",
description: "Maximum number of results (default: 10)",
default: 10
}
},
required: ["query"]
}
}typescript
{
name: "search_documents",
description: "Search documents by keyword. Returns matching documents with relevance scores. Use when the user asks to find or search for specific content.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query - can include multiple keywords"
},
limit: {
type: "integer",
description: "Maximum number of results (default: 10)",
default: 10
}
},
required: ["query"]
}
}Error Handling
错误处理
typescript
server.setRequestHandler("tools/call", async (request) => {
try {
const result = await executeTool(request.params);
return { content: [{ type: "text", text: result }] };
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${error.message}`
}],
isError: true
};
}
});typescript
server.setRequestHandler("tools/call", async (request) => {
try {
const result = await executeTool(request.params);
return { content: [{ type: "text", text: result }] };
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${error.message}`
}],
isError: true
};
}
});Resources
资源
typescript
server.setRequestHandler("resources/list", async () => ({
resources: [
{
uri: "file:///docs/readme.md",
name: "README",
description: "Project documentation",
mimeType: "text/markdown"
}
]
}));
server.setRequestHandler("resources/read", async (request) => {
const { uri } = request.params;
const content = await readResource(uri);
return {
contents: [{
uri,
mimeType: "text/markdown",
text: content
}]
};
});typescript
server.setRequestHandler("resources/list", async () => ({
resources: [
{
uri: "file:///docs/readme.md",
name: "README",
description: "Project documentation",
mimeType: "text/markdown"
}
]
}));
server.setRequestHandler("resources/read", async (request) => {
const { uri } = request.params;
const content = await readResource(uri);
return {
contents: [{
uri,
mimeType: "text/markdown",
text: content
}]
};
});Transport Options
传输选项
| Transport | Use Case |
|---|---|
| stdio | Local CLI tools |
| HTTP/SSE | Web services, remote servers |
| 传输方式 | 使用场景 |
|---|---|
| stdio | 本地CLI工具 |
| HTTP/SSE | Web服务、远程服务器 |
Security Considerations
安全注意事项
- Validate all input parameters
- Sanitize file paths
- Rate limit API calls
- Don't expose secrets
- Log all tool invocations
- Handle timeouts gracefully
- 验证所有输入参数
- 清理文件路径
- 对API调用进行速率限制
- 不要暴露机密信息
- 记录所有工具调用
- 优雅处理超时
Detailed References
详细参考资料
- MCP Patterns: See references/mcp-patterns.md
- AI/ML Integration: See references/ai-ml-integration.md
- MCP模式:查看 references/mcp-patterns.md
- AI/ML集成:查看 references/ai-ml-integration.md