lang: zh slug: mcp-deep-dive-definitive-2026-guide title: ‘模型上下文协议 (MCP) 深入探讨’ description: ‘从头开始构建您的第一个 MCP 服务器。 通过 Python 和 TypeScript 实践示例来学习 Anthropic 的模型上下文协议。 使用 OpenAI、Google 和 Microsoft 采用的开放标准将 AI 代理连接到真实的 API、数据库和工具。’ tags: [“ai-tools”, “guide”, “mcp”, “model-context-protocol”, “open-source”, “reference”, “tutorial”] date: 2026-05-15 00:00:00+08:00 lastmod: 2026-05-15 00:00:00+08:00 tech_stack: [] application_domain: Llm Frameworks source_version: ’' licensing_model: Open Source license_type: MIT file_size: ’' file_md5: ’' download_url: ’' backup_url: ’' github_repo: ’' last_maintained: ‘2026-05-15’ draft: false aliases:
- /posts/mcp-deep-dive-definitive-2026-guide/
faqs:
- q: ‘What is the Model Context Protocol (MCP)?’ a: ‘MCP is an open standard, released by Anthropic in November 2024, that standardizes how AI models connect to external tools, APIs, and data sources. It runs on JSON-RPC 2.0 and acts like ‘‘USB-C for AI’’—a single port any model can use to plug into any tool. Since December 2025 it has been governed by the Linux Foundation’’s Agentic AI Foundation rather than Anthropic.’
- q: ‘What problem does MCP solve?’ a: ‘MCP solves the M×N integration problem, where connecting M LLM providers to N external tools previously required custom glue code for every pair. By having tool authors expose their tools once via an MCP server and LLM vendors implement one MCP client, the integration burden collapses from M×N to M+N.’
- q: ‘Which transport options does MCP support and when should I use each?’ a: ‘MCP supports stdio (fastest, zero network exposure, best for local development and desktop apps) and HTTP+SSE/Streamable HTTP (slightly higher latency but cross-machine and stream-capable, best for remote servers and production). The rule of thumb is to prototype with stdio and promote to HTTP/SSE for production.’
- q: ‘How many tools should a single MCP server expose?’ a: ‘Keep it under 10 tools per server. Too many tools degrade the LLM’’s selection accuracy and bloat the context window, since every tool definition is injected into the prompt. Split by functional domain—for example, one server for database operations and another for Slack operations.’
- q: ‘Is MCP a replacement for frameworks like LangChain, CrewAI, or the OpenAI Agents SDK?’ a: ‘No. MCP is a protocol—the plumbing for exposing tools—while LangChain chains calls, CrewAI orchestrates multi-agent workflows, and the OpenAI Agents SDK is a high-level agent builder. These frameworks increasingly consume MCP servers as their tool layer rather than competing with MCP.’
featureImage: /images/articles/mcpmodel-context-protocol-완벽-실전-가이드.png #
Headroom: Compress LLM Inputs by 60-95% • Persistent Memory for AI Coding Agents in 2026 {</* resource-info */>}
简介:为什么 MCP 是 2026 年开发者最明智的选择如果您仍在为每个 LLM 和每个工具编写自定义集成代码,那么您将在 2026 年完成 2025 年的工作。2024 年 11 月,Anthropic 悄然发布了模型上下文协议(MCP)。 六个月后,它已成为人工智能基础设施中采用最快的开放标准。 OpenAI、Google DeepMind 和微软都承诺提供原生支持。 社区构建了 10,000 多个 MCP 服务器。 官方 Python 和 JavaScript SDK 的每周下载量超过 2000 万。然后在 2025 年 12 月,Linux 基金会成立了Agentic AI 基金会来独立管理 MCP。 它不再是 Anthropic 的协议。 这是行业的协议。本指南不是高级概述。 您将编写一个真正的生产级 MCP 服务器,用于监视网站运行状况和 SSL 证书,然后将其连接到 Claude Desktop、Cursor 和 VS Code Copilot 代理模式。 最后,您将拥有一个可以为您自己的 API 进行扩展并立即部署的工作工具。—## 目录1. MCP 实际上是什么(以及它不是什么) #
- 架构:主机、客户端和服务器如何对话
- 5 分钟开发环境
- 动手:构建 SiteMonitor MCP 服务器
- 连接到 Claude 桌面、光标和 VS Code
- 升级:资源、提示和 HTTP/SSE 传输
- 安全和生产强化
- MCP 生态系统备忘单:立即尝试 15 台服务器
- 常见问题解答—## 1. MCP 实际上是什么(以及它不是什么)### M×N 问题在 MCP 之前,将法学硕士与外部工具集成是一场组合噩梦:- M LLM 提供商(OpenAI、Anthropic、Google、Meta、Mistral…)
- N 外部工具(GitHub、Postgres、Slack、Stripe、Salesforce…)
- 每双的定制胶水代码MCP 将其折叠为 M + N:- 工具作者通过 MCP(服务器)公开一次
- LLM 供应商实施一个 MCP 客户端
- 一切都协同工作将其视为 USB-C for AI:任何模型都可以用来插入任何数据源或工具的单一标准化端口。### MCP 不是什么| Misconception | Reality | |—————|———| | A new AI model | No—it’s a protocol, not a model | | A replacement for Function Calling | No—MCP standardizes how tools are exposed; Function Calling is how models invoke them. They stack together. | | Only for Claude | No—OpenAI, Google, Microsoft, Cursor, Zed, Sourcegraph all support it | | Anthropic-proprietary | No—governed by the Linux Foundation since Dec 2025 |### 谁支持 MCP(2026 年 5 月)| Platform | Support Level | Notes | |———-|—————|——-| | Claude Desktop / Claude Code | Native | Reference implementation | | ChatGPT | Full (Dev Mode) | Read/write, Plus/Pro tiers since Sept 2025 | | Google Gemini | Confirmed | DeepMind CEO announced roadmap | | Cursor / Windsurf / Zed | Supported | AI-native IDEs | | VS Code Copilot Agent Mode | Native | v1.99+ | | Sourcegraph Cody | Enterprise | Enterprise MCP adoption |—## 2. 架构:主机、客户端和服务器如何对话MCP 通过两种传输选项在 JSON-RPC 2.0 上运行。 四个概念涵盖了现实世界 90% 的用法。### 四个概念```` ┌──────────────────────────────────────────────────────┐ │ MCP 主机 │ │ ┌────────────┐ ┐────────────────────┐ │ │ │ 法学硕士 │◄────────►│ MCP 客户 │ │ │ │ (克劳德) │ │ (stdio / HTTP+SSE) │ │ │ └──────────────┘ └──────────┬──────────────┘ │ └────────────────────────────────────────┼──────────────┘ │ JSON-RPC 2.0 ┌────────────────────────────────────────┼──────────────┐ │ MCP 服务器 │ │ │ • 工具(可调用函数)│◄─────────────┘ │ • 资源(可读数据) │ │ • 提示(可重复使用的模板) │ └──────────────────────────────────────────────────────┘
**客户端**:主机内使用 MCP 的模块。
**服务器**:公开工具/资源/提示的独立进程。### 三个交互原语1. **工具**:AI 可以使用参数调用函数,接收结构化结果。
2. **资源**:AI 可以获取的只读数据(文件、数据库行、配置)。
3. **提示**:AI 可以调用的命名、参数化提示模板。### 交通选择| Transport | Best For | Trade-off |
|-----------|----------|-----------|
| **stdio** | Local dev, desktop apps | Fastest, zero network exposure, limited to single machine |
| **HTTP + SSE** | Remote servers, microservices | Slightly higher latency, cross-machine, supports streaming |
| **Streamable HTTP** | Production, serverless | Stateful fallback, long-running ops |**经验法则**:带有 stdio 的原型。 升级到 HTTP/SSE 以进行生产。---## 3. 5 分钟开发环境Python、TypeScript、C#/.NET、Java/Kotlin 和 Go(社区)都有官方 SDK。 我们将使用 **Python** 来提高速度,并使用 **TypeScript** 作为并行参考。### 安装 uv(快速 Python 包管理器)````
bas
h
卷曲-LsSf https://astral.sh/uv/install.sh | 嘘
````### 搭建项目支架````
bas
h
mkdir mcp-site-monitor && cd mcp-site-monitor
紫外线初始化
uv 添加“mcp[cli]”httpx
````目录布局:````
mcp-站点监控/
├── .env # 秘密(gitignored)
├── .gitignore
├── pyproject.toml
└── server.py # 主MCP服务器
````---## 4. 实践:构建 SiteMonitor MCP 服务器我们将公开两个工具:- `check_site_status` — HTTP 运行状况检查(带时间)
- `check_ssl_expiry` — SSL 证书的剩余天数### 完整的 Python 服务器 (`server.py`)````蟒蛇
导入异步
导入SSL
进口插座
从日期时间导入日期时间导入httpx
从 mcp.server.fastmcp 导入 FastMCPmcp = FastMCP("站点监控器")@mcp.tool()
异步bash
卷曲-LsSf https://astral.sh/uv/install.sh | 嘘
````:
"""检查网站是否在线并测量响应时间。参数:```
bas
h
mkdir mcp-site-monitor && cd mcp-site-monitor
紫外线初始化
uv 添加“mcp[cli]”httpx
```
t
失败前,默认 10。
”“”
尝试:
与 httpx.AsyncClient 异步(follow_redirects=Tr```
mcp-站点监控/
├── .env # 秘密(gitignored)
├── .gitignore
├── pyproject.toml
└── server.py # 主MCP服务器
```
ncio
.get_event_loop().time() - t0status = "✅ 在线" 如果 r.status_code < 400 否则 "⚠️ 降级"
返回(
f"{状态}\n"
f"• URL: {url}\n"
f"• 状态:{r.status_code}\n"
f"• 响应时间:{经过:.2f}s\n"
f"• 服务器: {r.headers.get('服务器', '未知')}\n"
````蟒蛇
导入异步
导入SSL
进口插座
从日期时间导入日期时间
导入httpx
从 mcp.server.fastmcp 导入 FastMCP
mcp = FastMCP("站点监控器")
@mcp.tool()
异步 def check_site_status(url: str, 超时: int = 10) -> str:
"""检查网站是否在线并测量响应时间。
参数:
url:要检查的完整 URL,例如 https://example.com
timeout:失败前等待的秒数,默认 10。
”“”
尝试:
与 httpx.AsyncClient(follow_redirects=True, timeout=timeout) 作为客户端异步:
t0 = asyncio.get_event_loop().time()
r = 等待 client.get(url)
经过 = asyncio.get_event_loop().time() - t0
status = "✅ 在线" 如果 r.status_code < 400 否则 "⚠️ 降级"
返回(
f"{状态}\n"
f"• URL: {url}\n"
f"• 状态:{r.status_code}\n"
f"• 响应时间:{经过:.2f}s\n"
f"• 服务器: {r.headers.get('服务器', '未知')}\n"
)
除了httpx.TimeoutException:
return f"❌ 超时: {url} 在 {timeout} 秒内没有响应"
除了异常 e:
return f"❌ 错误: {type(e).__name__}: {e}"
@mcp.tool()
异步 def check_ssl_expiry(主机名: str, 端口: int = 443) -> str:
"""检查域的 SSL 证书还剩多少天。
参数:
主机名:域名,例如 example.com
port:HTTPS端口,默认443。
”“”
尝试:
ctx = ssl.create_default_context()
使用 socket.create_connection((主机名, 端口), timeout=10) 作为袜子:
使用 ctx.wrap_socket(sock, server_hostname=hostname) 作为 ssock:
证书 = ssock.getpeercert()
expiry = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
天数 = (过期 - datetime.utcnow()).days
flag = "🟢 健康" 如果天数 > 30 else "🟡 即将过期" 如果天数 > 7 else "🔴 严重"
返回(
f"{标志}\n"
f"• 主机:{主机名}\n"
f"• 颁发者:{cert.get('颁发者', '未知')}\n"
f"• 过期:{expiry.strftime('%Y-%m-%d %H:%M UTC')}\n"
f"• 剩余天数:{天}\n"
)
除了异常 e:
return f"❌ SSL 检查失败: {type(e).__name__}: {e}"
如果 __name__ == "__main__":
mcp.run(传输=“stdio”)
``` 异步 ({ url, 超时 = 10 }) => {
// ... httpx 相当于 fetch/axios
返回 { 内容:[{ 类型:“文本”,文本:结果 }] };
}
);const 传输 = new StdioServerTransport();
等待服务器.connect(传输);
````---## 5. 连接到 Claude 桌面、光标和 VS Code### 克劳德桌面 (macOS)编辑:````
bas
h
〜/库/应用程序\支持/克劳德/claude_desktop_config.json
````添加:```
jso
n
{
“mcp服务器”:{
“站点监视器”:{
“命令”:“紫外线”,
“参数”:[
“跑”,
“--目录”,
“/绝对/路径/到/mcp-站点监视器”,
“服务器.py”
]
}
}
}
````重新启动克劳德桌面。 问:>“检查 https://github.com 是否已启动,并告诉我其 SSL 证书还剩多少天。”Claude 自动调用这两个工具并格式化结果。### 光标在项目根目录中创建 `.cursor/mcp.json`:```
jso
n
{
“mcp服务器”:{
“站点监视器”:{
“命令”:“紫外线”,
“参数”:[
“跑”,
“--目录”,
“/绝对/路径/到/mcp-站点监视器”,
“服务器.py”
]
}
}
}
Curso
r
的 AI Chat 发现并使用内联工具。### VS Code Copilot 代理模式在“settings.json”中:```
jso
n
{
“github.copilot.chat.mcpServers”:{
“站点监视器”:{
“命令”:“紫外线”,
“args”:[“运行”,“server.py”],
“cwd”:“/绝对/路径/到/mcp-site-monitor”
}
}
}
---## 6. 升级:资源、提示和 HTTP/SSE 传输### 公开资源(只读数据)蟒蛇
@mcp.resource(“config://app”)
def get_app_config() -> str:
“““返回当前应用程序配置。”””
导入 json
返回 json.dumps({“check_interval_sec”: 300, “alert_threshold_ms”: 2000})@mcp.resource(“log://最新”)
def get_latest_log() -> str:
“““返回最近的监控日志条目。”””
返回“[2026-05-15T08:00:00Z] github.com:23ms内200 OK”
### 暴露提示(可重用模板)蟒蛇
@mcp.prompt()
def debug_incident(url: str, status_code: int) -> str:
“““生成结构化事件调试提示。”””
return f"““网站 {url} 正在返回 HTTP {status_code}。调查:
- DNS解析健康状况 2.服务器进程状态 3.最近的应用程序日志(最近10分钟)
- CDN 仪表板的流量峰值模式
”“”
### 切换到 HTTP + SSE 进行生产蟒蛇 从 mcp.server.sse 导入 SseServerTransport 从 starlette.applications 导入 Starlette 从 starlette.routing 导入路线sse = SseServerTransport("/消息/")异步定义handle_sse(请求): 与 sse.connect_sse(request.scope, request.receive, request._send) 异步作为流: 等待 mcp.run(流[0], 流[1], mcp.create_initialization_options())应用程序 = Starlette(routes=[路线("/sse”, 端点=handle_sse)])
ASGI 主机(Railway、Fly.io、您自己的 VPS)并将远程客户端指向 SSE 端点。---## 7. 安全和生产强化将人工智能连接到外部系统既强大又危险。 Fo```打字稿
从“@modelcontextprotocol/sdk/server/mcp.js”导入{McpServer};
从“@modelcontextprotocol/sdk/server/stdio.js”导入{ StdioServerTransport };
从“zod”导入{z};
const server = new McpServer({ 名称: "SiteMonitor", 版本: "1.0.0" });
服务器.工具(
“检查站点状态”,
{
url: z.string().describe("要检查的完整 URL"),
超时: z.number().可选().describe("超时以秒为单位"),
},
异步({ url,超时= 10 })=> {
// ... httpx 相当于 fetch/axios
返回 { 内容:[{ 类型:“文本”,文本:结果 }] };
}
);
const 传输 = new StdioServerTransport();
等待服务器.connect(传输);
`` 防止 MITM 篡改工具调用。
7. **审核和监控** — 记录每个工具调用。 异常警报。**现实世界警告**:2025 年 7 月,Anthropic 的 MCP Inspector 中发现了一个严重的 RCE 漏洞(CVE-2025-49596、CVSS 9.4)。 针对人工智能开发工具的基于浏览器的攻击现已成为已知的威胁类别。 将 MCP 服务器视为安全关键基础设施。---## 8. MCP 生态系统备忘单:立即尝试的 15 台服务器| 服务器| 它有什么作用 | 最佳用例|
|--------|--------------|----------------|
| **文件系统** | 读/写本地文件 | 代码库分析、文档处理 |
| **github** | PR、问题、代码搜索 | 自动代码审查 |
| **postgres** / **sqlite** | SQL 查询 | 数据分析,内部BI |
| **sl```
bas
h
〜/库/应用程序\支持/克劳德/claude_desktop_config.json
``` **勇敢的探索** | 网络搜索| 实时事实核查 |
| **傀儡师** | ```
jso
n
{
“mcp服务器”:{
“站点监视器”:{
“命令”:“紫外线”,
“参数”:[
“跑”,
“--目录”,
“/绝对/路径/到/mcp-站点监视器”,
“服务器.py”
]
}
}
}
``管理|
| **获取** | 任意URL获取| 内容摘要|
| **顺序思维** | 思路链帮手| 复杂推理任务 |
| **剧作家** | E2E测试自动化| 测试生成|
| **redis** | 键值操作 | 缓存检查 |
| **码头工人** | 集装箱管理| DevOps 自动化 |
| **kubernetes** | K8s 资源操作 | 集群管理|完整目录: [Smithery.ai](https://smithery.ai) · [MCP.so](https:```
jso
n
{
“mcp服务器”:{
“站点监视器”:{
“命令”:“紫外线”,
“参数”:[
“跑”,
“--目录”,
“/绝对/路径/到/mcp-站点监视器”,
“服务器.py”
]
}
}
}
``代理工作流程。 OpenAI Agents SDK 是一个高级代理构建器。 这些框架越来越多地**使用** MCP 服务器作为其工具层。**问:我可以在云中/Kubernetes 上运行 MCP 服务器吗?**是的。 stdio 用于本地。 HTTP/SSE scales to containers, VPS, and serverless (with caveats around MCP's stateful desig```
jso
n
{
“github.copilot.chat.mcpServers”:{
“站点监视器”:{
“命令”:“紫外线”,
“args”:[“运行”,“server.py”],
“cwd”:“/绝对/路径/到/mcp-site-monitor”
}
}
}
```
io
n
accuracy and bloat the context window (every tool definition is injected into the prompt). Split by functional domain: one server for DB ops, another for Slack ops.**问:MCP 与 Google 的 A2A 协议有何关系?**MCP连接**AI → Tools**(代理到外部系统)```
pytho
n
@mcp.resource("config://app")
def get_app_config() -> str:
"""返回当前应用程序配置。"""
导入 json
返回 json.dumps({"check_interval_sec": 300, "alert_threshold_ms": 2000})
@mcp.resource("log://最新")
def get_latest_log() -> str:
"""返回最近的监控日志条目。"""
返回“[2026-05-15T08:00:00Z] github.com:23ms内200 OK”
```
e
technology. 它是 2026 年 AI 工具集成的**实时标准**。如果您今天不知道如何构建 MCP 服务器,那么您就错过了每个 AI 原生开发团队明天所期望的基本技能。您的后续步骤:1.复制上面的SiteMonitor代码并使用`uv`运行它
2. 将其连接到 Claude Desktop 并提出自然语言监控问题
3. 将团队最常用的内部 API 包装为 MCP 服务器
4.P```
pytho
n
@mcp.prompt()
def debug_incident(url: str, status_code: int) -> str:
"""生成结构化事件调试提示。"""
return f"""网站 {url} 正在返回 HTTP {status_code}。调查:
1. DNS解析健康状况
2.服务器进程状态
3.最近的应用程序日志(最近10分钟)
4. CDN 仪表板的流量峰值模式
”“”
```
y
市场](https://mcp.so)---## 🔌 跳过模式样板为每个工具手动编写 JSON Schema 是 MCP 开发中最乏味的部分。 使用 dibi8 的免费 **[MCP Tool Builder](/tools/mcp-tool-builder/)** — 粘贴 Python 或 TypeScript 函数签名并获取符合规范的工具定义 + 完整服务器样板(FastMCP / TypeScript SDK) + cURL 测试命令。 保存```
pytho
n
从 mcp.server.sse 导入 SseServerTransport
从 starlette.applications 导入 Starlette
从 starlette.routing 导入路线
sse = SseServerTransport("/消息/")
异步定义handle_sse(请求):
与 sse.connect_sse(request.scope, request.receive, request._send) 异步作为流:
等待 mcp.run(流[0], 流[1], mcp.create_initialization_options())
应用程序 = Starlette(routes=[路线("/sse", 端点=handle_sse)])
``来自中国大陆。 这与托管 dibi8.com 的 IDC 是同一个 IDC——在生产中经过了实际考验。*附属链接 - 它们不会花费您额外的费用,并且有助于保持 dibi8.com 的运行。**发布于 2026 年 5 月 15 日。基于 MCP 协议规范 2025-11-25(一周年发布)。*<!--自动引用-->
## 参考文献和来源- [MCP 规范](https://modelcontextprotocol.io)
- [MCP Python SDK (FastMCP)](https://github.com/modelcontextprotocol/python-sdk)
- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
- [MCP 参考服务器(文件系统、github、postgres、slack 等)](https://github.com/modelcontextprotocol/servers)
- [Smithery.ai(MCP 服务器注册表)](https://smithery.ai)
- [MCP.so(社区市场)](https://mcp.so)
- [uv(Python 包管理器)](https://github.com/astral-sh/uv)
💬 留言讨论