Post

MCP 完整开发指南:从概念到实现

MCP 完整开发指南:从概念到实现

MCP(Model Context Protocol,模型上下文协议)是连接 AI Agent 与外部世界的桥梁。本文带你系统了解 MCP 的核心概念、架构设计、以及如何开发一个 MCP 服务器。

目录

什么是 MCP

想象一个场景:你是一位 AI 助手,被关在一个只有文字的房间里。用户让你”查看一下 GitHub 上的 issue”,但你没有手去敲键盘,也没有浏览器访问网络。这就是大多数 LLM 的困境——它们很聪明,但无法直接与外部世界交互。

MCP 就是解决这个问题的标准化通信协议,它为 AI Agent 提供了一双”看得见、摸得着”的手和眼睛。

MCP 核心定位MCP Protocol LayerAI Agent(Cline/Cursor)AI Agent(Cline/Cursor)MCP ClientMCP ClientMCP ServerMCP ServerExternal Systems(GitHub/Slack/DB)External Systems(GitHub/Slack/DB)自然语言请求JSON-RPC 调用实际操作返回数据标准化响应上下文注入

MCP 的核心价值:

特性 说明
标准化 统一的 JSON-RPC 协议,所有工具遵循相同规范
可扩展 开发者可以创建任意类型的工具服务器
类型安全 使用 JSON Schema 定义输入输出格式
多语言 可用 Python、TypeScript、Rust 等实现

MCP 核心架构

MCP 采用客户端-服务器架构,通过标准输入输出(stdio)或网络进行通信。

MCP 完整架构图AI IDE (VS Code)MCP EcosystemExternal WorldCline ExtensionMCP HostMCP Server A(Firecrawl)MCP Server B(GitHub)MCP Server C(Custom)WebGitHub APIDatabaseMCP Host 负责:- 发现可用服务器- 管理进程生命周期- 路由工具调用- 格式化响应数据我需要搜索网络注入到上下文中tools/callsearch(query=...)JSON ResponseHTTP RequestSearch Results

核心组件详解

1. MCP 客户端(Host)

通常由 AI 编程工具(如 Cline、Cursor)实现,负责:

  • 发现和启动 MCP 服务器
  • 维护通信通道
  • 调用工具并处理响应
  • 将结果注入 LLM 上下文

2. MCP 服务器

开发者实现的部分,提供具体功能:

  • 声明可用的工具和资源
  • 处理工具调用请求
  • 执行实际操作(API 调用、文件操作等)
  • 返回标准化的结果

3. 通信协议

MCP 使用 JSON-RPC 2.0 作为基础协议,核心方法包括:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 工具调用请求
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "firecrawl_search",
    "arguments": {
      "query": "MCP 协议文档",
      "limit": 5
    }
  }
}

工具类型与实现

MCP 服务器可以提供多种类型的能力,每种类型有不同的实现方式。

1. Tools(工具)

最常用的类型,让 AI Agent 可以”做事情”。

Tool 生命周期AgentAgentMCPHostMCPHostMCPServerMCPServer搜索 MCP 相关信息查找可用工具tools/list 请求返回工具列表{tools: [{name: firecrawl_search,description: 搜索网页,inputSchema: {...}}]}注入工具描述决定调用 firecrawl_searchtools/call 执行实际 HTTP 搜索返回结果注入搜索结果上下文

2. Resources(资源)

提供可访问的数据源,AI Agent 可以读取这些资源获取上下文。

Resource 访问流程AgentAgentMCPHostMCPHostMCPServerMCPServer我需要了解项目配置resources/list资源列表{resources: [{uri: file:///project/package.json,name: 项目配置,description: npm 配置文件}]}可用资源列表请求读取 package.jsonresources/read文件内容注入文件内容

3. Prompts(提示模板)

预定义的提示词模板,帮助 AI Agent 更好地完成特定任务。

Prompt 使用流程AgentAgentMCPHostMCPHostMCPServerMCPServerprompts/list提示模板列表{prompts: [{name: code-review,description: 代码评审模板,arguments: [...]}]}使用 code-review 模板prompts/get填充后的提示注入完整提示词

开发一个 MCP 服务器

让我们以一个实际的例子,从零开始开发一个 MCP 服务器。

步骤 1:选择开发语言

MCP 官方提供了 SDK:

  • Pythonmcp
  • TypeScript@modelcontextprotocol/sdk

这里我们使用 Python 进行演示,它是开发 MCP 服务器最常用的语言。

步骤 2:初始化项目

1
2
3
mkdir my-mcp-server
cd my-mcp-server
pip install mcp

步骤 3:实现核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from mcp.server import Server
from mcp.types import Tool, TextContent
import logging

# 配置日志(使用 stderr,避免干扰 stdio 通信)
logging.basicConfig(
    level=logging.INFO,
    format='[%(levelname)s] %(message)s',
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

# 创建服务器实例
server = Server("my-mcp-server")

# 注册工具列表
@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="calculate_sum",
            description="计算两个数字的和",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {
                        "type": "number",
                        "description": "第一个数字"
                    },
                    "b": {
                        "type": "number",
                        "description": "第二个数字"
                    }
                },
                "required": ["a", "b"]
            }
        )
    ]

# 实现工具调用
@server.call_tool()
async def call_tool(name: str, arguments: dict):
    logger.info(f"收到工具调用: {name}, 参数: {arguments}")
  
    if name == "calculate_sum":
        a = arguments.get("a")
        b = arguments.get("b")
  
        # 输入验证
        if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
            return [
                TextContent(
                    type="text",
                    text="错误:a 和 b 必须是数字"
                )
            ]
  
        result = a + b
        return [
            TextContent(
                type="text",
                text=f"计算结果:{a} + {b} = {result}"
            )
        ]
  
    return [
        TextContent(
            type="text",
            text=f"错误:未知工具 {name}"
        )
    ]

# 启动服务器
if __name__ == "__main__":
    import asyncio
    from mcp.server.stdio import stdio_server
  
    async def main():
        logger.info("My MCP Server 已启动")
        async with stdio_server() as (read_stream, write_stream):
            await server.run(
                read_stream,
                write_stream,
                server.create_initialization_options()
            )
  
    asyncio.run(main())

步骤 4:运行测试

1
2
# 直接运行 Python 脚本
python server.py

配置与集成

开发完成后,需要在 AI 工具中配置 MCP 服务器。

Cline 配置

在 VS Code 设置中添加 MCP 服务器配置:

1
2
3
4
5
6
7
8
9
10
11
{
  "cline.mcpServers": {
    "my-mcp-server": {
      "command": "python",
      "args": ["C:/path/to/your/server/server.py"],
      "env": {
        "API_KEY": "your-api-key-here"
      }
    }
  }
}

验证集成

配置完成后,重启 VS Code,然后:

  1. 打开 Cline 聊天窗口
  2. 观察 MCP 服务器是否成功启动
  3. 尝试让 AI 使用你的工具:”计算 123 + 456 的和”
MCP 集成验证流程VS CodeVS CodeCline ExtensionCline ExtensionMCP Server ProcessMCP Server Process启动扩展读取 MCP 配置spawn 子进程启动服务器服务器就绪tools/list 请求返回工具列表在 UI 中显示可用工具MCP 集成成功!

最佳实践

1. 错误处理

1
2
3
4
5
6
7
8
9
10
# ❌ 不推荐:直接抛出未处理的错误
raise Exception("出错了")

# ✅ 推荐:友好的错误信息
return [
    TextContent(
        type="text",
        text=f"错误:无法连接 API,原因:{str(err)}"
    )
]

2. 输入验证

始终验证输入参数,不要信任传入的数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@server.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "calculate_sum":
        a = arguments.get("a")
        b = arguments.get("b")
    
        # 验证必填参数
        if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
            return [
                TextContent(
                    type="text",
                    text="错误:a 和 b 必须是数字"
                )
            ]
    
        # 继续处理...

3. 日志调试

使用 logging 输出到 stderr(不能用 print,会干扰 stdio):

1
2
3
4
5
import logging

logger = logging.getLogger(__name__)
logger.info(f"[DEBUG] 收到工具调用: {name}, 参数: {arguments}")
logger.error(f"[ERROR] API 请求失败: {str(err)}")

4. 安全考虑

  • API Key:通过环境变量传递,不要硬编码
  • 权限控制:只暴露必要的功能
  • 输入过滤:防止注入攻击
  • 速率限制:避免滥用外部 API

总结

MCP 是 AI Agent 能力扩展的关键技术,它通过标准化的协议让 AI 能够安全、可控地与外部世界交互。

学习阶段 建议行动
入门 先使用现有的 MCP 服务器(如 Firecrawl、GitHub)
进阶 开发简单的自定义服务器(如文件操作、内部 API)
精通 开发复杂的多工具服务器,集成多个外部系统

MCP 的生态正在快速发展,掌握这项技术将让你在 AI 辅助开发浪潮中占据先机。你可以从简单的工具开始,逐步构建自己的 AI 能力扩展生态。

This post is licensed under CC BY 4.0 by the author.

© . Some rights reserved.

Using the Chirpy theme for Jekyll.