MCP 实战:AI Agent 连接万物的标准协议完整指南 2026
MCP(Model Context Protocol)是 2026 年 AI Agent 连接万物的标准。本文从 0 到 MCP 服务器实战,含 4 个真实项目 + 生态 + 与 Function Calling 区别。
今日技术简讯
📰 技术简讯 · 2026-08-08
今日聚合 6 条热门技术内容(中文素材优先)。
🤖 AI / LLM
1. Anthropic 推出 MCP 1.0 GA
- 链接:https://modelcontextprotocol.io/blog/1-0
- 来源:Anthropic
- 摘要:MCP 1.0 正式 GA,AI Agent 连接外部工具 / 数据 / API 的统一标准。
2. OpenAI 推出 MCP 兼容
- 链接:https://openai.com/blog/mcp-support
- 来源:OpenAI
- 摘要:OpenAI 推出 MCP 完整兼容,GPT-5 / o3 可调用 MCP 服务器。
3. Google 推出 MCP 集成
- 链接:https://ai.google.dev/gemini-api/docs/mcp
- 来源:Google
- 摘要:Google Gemini 推出 MCP 集成,统一协议接入 1000+ 工具。
🎨 前端 / Web
4. Cloudflare 推出 MCP Hosting
- 链接:https://blog.cloudflare.com/mcp-hosting
- 来源:Cloudflare
- 摘要:Cloudflare 推出 MCP Hosting,边缘部署 MCP 服务器,全球 < 50ms 响应。
⚙️ 后端 / 架构
5. Microsoft 推出 MCP for Enterprise
- 链接:https://learn.microsoft.com/mcp-enterprise
- 来源:Microsoft
- 摘要:Microsoft 推出 MCP Enterprise 版,企业 SSO + 审计 + 合规。
🚀 独立开发 / OPC
6. 即刻"MCP 实战"专题
- 链接:https://m.okjike.com/mcp-2026
- 来源:即刻
- 摘要:即刻 200+ 独立开发者分享 MCP 实战,自建 MCP 服务器 + Claude Desktop / Cursor 集成。
数据来源:掘金 / InfoQ 中文 / 即刻 / 少数派 / HN 采集日期:2026-08-08 (UTC+8)
今日深度文
MCP 实战:AI Agent 连接万物的标准协议完整指南 2026
一句话结论:MCP = AI Agent 的 USB-C 接口。一个协议,所有 AI 模型 / 所有工具 / 所有数据互通。本文从 0 到 MCP 服务器实战。
背景
2026 年 AI Agent 接入工具的痛点:
传统方式(每个 AI 各搞一套):
- Claude Tool Use
- OpenAI Function Calling
- Google Function Calling
- LangChain Tools
- LlamaIndex Tools
→ 每个都要重新适配,浪费时间
MCP 出现,彻底解决:
MCP(Model Context Protocol):
- 一个协议(JSON-RPC 2.0)
- 所有 AI 支持(Claude / GPT / Gemini)
- 所有工具互通(数据库 / API / 文件)
- 一次开发,到处运行
为什么 MCP 是 2026 年 AI 关键:
- 标准化:Anthropic 牵头,OpenAI / Google 都支持
- 生态爆发:1000+ MCP 服务器
- 开发效率:一次开发,到处运行
- 安全可控:本地运行 + 权限隔离
- 开源开放:协议完全开源
6 大核心优势
1. 一次开发,多 AI 支持
// ✅ 写一次 MCP 服务器,Claude / GPT / Gemini 都能用
// 不需要为每个 AI 写适配
2. JSON-RPC 2.0 协议
// 请求
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": { "city": "Beijing" }
}
}
// 响应
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{ "type": "text", "text": "Beijing 25°C" }]
}
}
3. 三大核心能力
MCP 服务器提供 3 类能力:
1. Tools(工具):执行操作(数据库查询 / API 调用)
2. Resources(资源):读取数据(文件 / 文档)
3. Prompts(提示):预定义 Prompt 模板
4. 传输方式多样
支持传输:
- stdio(标准输入输出,本地)
- HTTP + SSE(远程)
- WebSocket(双向)
5. 安全沙箱
// 用户授权每个工具
await client.request({
method: "tools/call",
params: {
name: "send_email",
arguments: { to: "...", subject: "...", body: "..." },
},
});
// 服务器响应
{
result: {
content: [{ type: "text", text: "已发送邮件" }],
isError: false,
},
}
6. 完整生态
MCP 生态:
- 官方服务器(Anthropic)
- 社区服务器(1000+)
- 客户端(Claude Desktop / Cursor / Cline)
- 工具库(Postgres / Slack / GitHub / ...)
MCP vs Function Calling
| 维度 | Function Calling | MCP |
|---|---|---|
| 标准化 | ❌ 每家不同 | ✅ 统一协议 |
| 跨平台 | ❌ 锁定厂商 | ✅ 多 AI 支持 |
| 开发成本 | 高(N 个 AI × N 个工具) | 低(1 个 MCP) |
| 生态 | 各自 | 共享 |
| 传输 | HTTP | stdio / HTTP / WS |
| 状态 | 无 | 有(Resources) |
| 适用 | 简单调用 | 复杂工具 |
4 个实战项目
项目 1:简单 MCP 服务器(Python)
# mcp_server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("weather-server")
@mcp.tool()
async def get_weather(city: str) -> str:
"""获取指定城市的天气"""
# 实际调用天气 API
weather = await fetch_weather(city)
return f"{city} 当前天气:{weather['temp']}°C,{weather['desc']}"
@mcp.resource("config://app")
def get_config() -> str:
"""应用配置"""
return "应用版本 1.0.0"
@mcp.prompt()
def weather_prompt(city: str) -> str:
"""天气查询 Prompt"""
return f"请告诉我 {city} 的天气"
if __name__ == "__main__":
mcp.run() # stdio 传输
# 配置 Claude Desktop
# ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["/path/to/mcp_server.py"]
}
}
}
项目 2:TypeScript MCP 服务器(推荐)
// mcp-server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
const server = new Server(
{
name: "postgres-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// 列出所有工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "query_database",
description: "查询 PostgreSQL 数据库",
inputSchema: {
type: "object",
properties: {
sql: {
type: "string",
description: "SQL 查询语句",
},
},
required: ["sql"],
},
},
],
};
});
// 调用工具
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "query_database") {
const sql = request.params.arguments?.sql as string;
// 安全检查
if (!isSafeSQL(sql)) {
return {
content: [{ type: "text", text: "危险 SQL 被拒绝" }],
isError: true,
};
}
// 执行查询
const result = await db.query(sql);
return {
content: [
{
type: "text",
text: JSON.stringify(result.rows, null, 2),
},
],
};
}
throw new Error("Tool not found");
});
function isSafeSQL(sql: string): boolean {
// 只允许 SELECT
return /^\s*SELECT/i.test(sql);
}
const transport = new StdioServerTransport();
await server.connect(transport);
# 配置 Cursor
# ~/.cursor/mcp.json
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["tsx", "/path/to/mcp-server.ts"],
"env": {
"DATABASE_URL": "postgresql://..."
}
}
}
}
项目 3:远程 MCP 服务器(HTTP + SSE)
// mcp-http-server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import express from "express";
const server = new Server(
{ name: "remote-server", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
const app = express();
app.get("/sse", async (req, res) => {
const transport = new SSEServerTransport("/messages", res);
await server.connect(transport);
});
app.post("/messages", async (req, res) => {
// 处理消息
});
app.listen(3000);
// 客户端连接
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
const transport = new SSEClientTransport(new URL("https://mcp.example.com/sse"));
const client = new Client({ name: "my-client", version: "1.0.0" }, { capabilities: {} });
await client.connect(transport);
// 调用远程工具
const result = await client.request({
method: "tools/call",
params: {
name: "remote_tool",
arguments: {},
},
});
项目 4:Cloudflare MCP Hosting
// wrangler.toml
name = "mcp-server"
main = "src/index.ts"
compatibility_date = "2026-08-01"
[vars]
API_KEY = "xxx"
// src/index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (request.headers.get("Upgrade") === "websocket") {
// WebSocket 升级
return handleWebSocket(request, env);
}
return new Response("MCP Server", { status: 200 });
},
};
// 部署到 Cloudflare
// $ wrangler deploy
# 全球 < 50ms 响应(边缘节点)
5 大常见 MCP 服务器
1. Postgres MCP
# 安装
$ npm install -g @modelcontextprotocol/server-postgres
# 配置
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://..."]
}
}
}
2. Filesystem MCP
# 本地文件访问
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/.../Documents"]
}
}
}
3. GitHub MCP
# GitHub 操作
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_TOKEN": "..." }
}
}
}
4. Slack MCP
# Slack 消息
{
"mcpServers": {
"slack": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"env": { "SLACK_TOKEN": "..." }
}
}
}
5. Puppeteer MCP
# 浏览器自动化
{
"mcpServers": {
"puppeteer": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-puppeteer"]
}
}
}
5 个常见坑
坑 1:协议不匹配
❌ 用 Function Calling 的代码冒充 MCP
✅ 严格遵守 JSON-RPC 2.0 + MCP 规范
坑 2:权限过大
// ❌ 不限制 SQL 类型
await db.query(sql); // DROP TABLE 也能跑
// ✅ 只允许 SELECT
if (!/^SELECT/i.test(sql)) throw new Error('Only SELECT allowed');
坑 3:无错误处理
// ❌ 不处理错误
return { content: [{ text: result }] };
// ✅ 捕获并返回
try {
return { content: [{ text: result }] };
} catch (error) {
return {
content: [{ type: 'text', text: error.message }],
isError: true,
};
}
坑 4:阻塞过长
// ❌ 同步长操作
await longRunningTask();
// ✅ 异步 + 超时
await Promise.race([
longRunningTask(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('timeout')), 30000)
),
]);
坑 5:日志泄露
// ❌ 日志输出到 stderr(污染 JSON-RPC)
console.log('debug');
// ✅ 用专门日志(不污染协议)
import pino from 'pino';
const logger = pino({ level: 'info' });
logger.info('debug');
与之前内容的关系
7/11 LangGraph → AI Agent
7/12 AutoGen → Multi-Agent
7/13 CrewAI → Multi-Agent
7/14 一人公司 AI Agent
7/15 RAG → 数据源
8/1 LLM 工程化 → Prompt / 评估
8/8 MCP 协议 → 工具标准 ← 今天
→ "Agent → 框架 → 工具"完整生态
7 天落地路径
Day 1:理解 MCP 概念
阅读 https://modelcontextprotocol.io
Day 2:安装 Claude Desktop
# 下载 + 配置 MCP
Day 3:使用官方 MCP 服务器
# filesystem / github / postgres
Day 4:第一个自定义 MCP
# Python: get_weather
Day 5:TypeScript MCP
# 关联 Cursor
Day 6:远程 MCP + Cloudflare
# 边缘部署
Day 7:发布到 Marketplace
# 分享给社区
我的看法
MCP 是 2026 年 AI Agent 的"USB-C 接口":
- 标准化:一次开发,到处运行
- 生态爆发:1000+ 服务器
- 多 AI 支持:Claude / GPT / Gemini
- 安全可控:本地 + 权限隔离
- 开源开放:完全开源
对独立开发者的建议:
- 学习 MCP:AI Agent 的未来
- 开发 MCP 服务器:垂直领域机会
- 发布到 Marketplace:变现渠道
- 结合现有项目:数据库 / 文件 / API
- 关注协议演进:早期参与者红利
参考
- MCP 官方
- MCP Python SDK
- MCP TypeScript SDK
- Claude Desktop
- MCP Servers
- LangGraph(7/11)
- AutoGen(7/12)
- CrewAI(7/13)
- 一人公司 AI Agent(7/14)
- LLMOps(8/1)
本文基于 MCP 1.0 GA,2026 年 8 月最新实战。
�� 同主题文章
RAG 检索质量工程实战 2026:从"能答"到"答得准"的完整优化链路
搭出一个能跑通的 RAG Demo 只需一个下午,但让它在你自己的数据上稳定"答得准"却要难得多:切分颗粒度、召回率、重排序、查询改写、上下文组装、引用与拒答,每一环都在决定最终答案的质量。2026 年的共识是,RAG 的瓶颈早已不在模型,而在检索质量工程。本文把整条链路拆开讲透:从可测量的流水线设计,到切片策略、混合检索、重排序、多路召回、上下文去噪与防幻觉,再到离线评测与在线反馈闭环,最后给出一份可照做的落地清单。
LLM 应用成本工程实战 2026:小模型价格战时代,把 API 账单压成零头
2026 年 10 月,旗舰模型输入价降到每百万 token 两美元、缓存读取低至一折,小模型价格再砍到上一代十分之一,模型能力快速商品化。成本不再是月底才看一眼的账单,而是写进架构里的一等决策:同样的功能,合理的路由、缓存与降级设计能让单次调用成本相差几十倍。本文系统实战 LLM 成本工程:看懂 token 定价结构、建立成本地图、三级模型路由与级联升级、Prompt 缓存断点设计、语义缓存、输入输出双端压缩、批处理异步化、降级链与预算熔断,以及独立开发者按 ROI 排序的落地清单。
AI 应用评估体系完整实战 2026:Evals 驱动的 LLM 质量保障
传统软件改一行代码,单元测试会告诉你有没有改坏东西;AI 应用改一个提示词或换一个模型,输出却可能在你完全没注意的角落悄悄变差——因为没有确定性的测试能断言「这段话写得对不对」。Evals(评估)就是 AI 应用的测试体系:用精心构造的数据集与可复现的打分方法,衡量模型输出的质量,并在每次变更后捕捉回归。本文完整实战 AI 评估体系:为什么传统测试不够用、评估数据集怎么建、自动打分与人评的分工、LLM-as-a-Judge 的用法与偏差、RAG 与 Agent 的专项评估、把 Evals 接入 CI、以及生产环境的在线评估闭环。