返回首页
🤖 AI / LLM

MCP 协议深度解析:LLM 工具调用的统一标准

Model Context Protocol(MCP)正在成为 LLM 工具调用的事实标准。本文深度解析其架构、价值和实战用法。

MCP · LLM · Claude · 协议
📰

今日技术简讯

📰 技术简讯 · 2026-06-15

今日聚合 6 条热门技术内容(周日)。

🤖 AI / LLM

1. MCP 协议深度解析

  • 链接https://modelcontextprotocol.io
  • 来源:Anthropic 官方
  • 摘要:Model Context Protocol 成为 LLM 工具调用事实标准,Claude / GPT / Gemini 全支持。

2. Ollama v0.6 发布

🎨 前端 / Web

3. Lit 4.0 发布

⚙️ 后端 / 架构

4. eBPF Summit 2026 总结

  • 链接https://ebpf.io/summit-2026
  • 来源:eBPF 基金会
  • 摘要:Cilium / Falco / Pixie 等项目成熟度大幅提升,eBPF 进入主流。

🚀 独立开发 / OPC

5. 《Indie Hacker 失败案例集》

6. Cloudflare D1 进入 GA


数据来源:HN / Reddit / 各厂博客 采集时间:2026-06-15 09:00 (UTC+8)

📝

今日深度文

MCP 协议深度解析:LLM 工具调用的统一标准

一句话结论:MCP 是 LLM 时代的"USB 接口"。它统一了 AI 与外部工具的通信方式,让"AI Agent + 工具"变成可组合的乐高积木。

背景

2024 年 11 月,Anthropic 开源了 Model Context Protocol(MCP)。

2026 年,MCP 已经成为 LLM 工具调用的事实标准:

  • Claude / GPT / Gemini 全部原生支持
  • 1000+ 开源 MCP Server(GitHub / Slack / Notion / Postgres)
  • 大厂都在接入(Microsoft / JetBrains / Sourcegraph)

核心架构

┌─────────────────┐
│   LLM (Claude)  │  ← MCP Client(嵌入在 IDE / 应用里)
└────────┬────────┘
         │ MCP Protocol (JSON-RPC)

┌─────────────────┐
│   MCP Server    │  ← 工具 / 资源 / 提示词
│  (e.g. GitHub)  │
└─────────────────┘

三大核心概念

1. Tools(工具)

// MCP Server 定义工具
server.setRequestHandler('tools/list', async () => ({
  tools: [{
    name: 'create_issue',
    description: '在 GitHub 仓库创建 issue',
    inputSchema: {
      type: 'object',
      properties: {
        repo: { type: 'string', description: '仓库名' },
        title: { type: 'string' },
        body: { type: 'string' },
      },
      required: ['repo', 'title'],
    },
  }],
}));

2. Resources(资源)

// 暴露数据(如文件、数据库记录)
server.setRequestHandler('resources/list', async () => ({
  resources: [{
    uri: 'file:///docs/api.md',
    name: 'API 文档',
    mimeType: 'text/markdown',
  }],
}));

3. Prompts(提示词模板)

// 预设的 prompt 模板
server.setRequestHandler('prompts/list', async () => ({
  prompts: [{
    name: 'code_review',
    description: '代码审查模板',
    arguments: [{
      name: 'language',
      description: '编程语言',
      required: true,
    }],
  }],
}));

实战:写一个 GitHub MCP Server

// mcp-server-github/index.ts
import { Server } from '@modelcontextprotocol/sdk/server';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio';
import { Octokit } from 'octokit';

const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });

const server = new Server({
  name: 'github-mcp',
  version: '1.0.0',
}, {
  capabilities: {
    tools: {},
    resources: {},
  },
});

// 工具 1:搜索仓库
server.setRequestHandler('tools/list', async () => ({
  tools: [
    {
      name: 'search_repos',
      description: '搜索 GitHub 仓库',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string' },
          limit: { type: 'number', default: 10 },
        },
        required: ['query'],
      },
    },
    {
      name: 'create_issue',
      description: '创建 issue',
      inputSchema: {
        type: 'object',
        properties: {
          repo: { type: 'string' },
          title: { type: 'string' },
          body: { type: 'string' },
        },
        required: ['repo', 'title'],
      },
    },
  ],
}));

// 工具调用处理
server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'search_repos') {
    const { query, limit } = request.params.arguments;
    const result = await octokit.search.repos({ q: query, per_page: limit });
    return {
      content: [{
        type: 'text',
        text: JSON.stringify(result.data.items, null, 2),
      }],
    };
  }
  
  if (request.params.name === 'create_issue') {
    const { repo, title, body } = request.params.arguments;
    const [owner, name] = repo.split('/');
    const issue = await octokit.rest.issues.create({
      owner,
      repo: name,
      title,
      body,
    });
    return {
      content: [{
        type: 'text',
        text: `Created issue #${issue.data.number}: ${issue.data.html_url}`,
      }],
    };
  }
});

// 启动
const transport = new StdioServerTransport();
await server.connect(transport);

在 Claude Desktop 中使用

// ~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "github": {
      "command": "node",
      "args": ["/path/to/github-mcp/index.js"],
      "env": {
        "GITHUB_TOKEN": "ghp_xxx"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://..."
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
    }
  }
}

实战对话

用户:帮我在我的 awesome-repo 仓库搜索所有 React 相关 issue,按状态分组

Claude 理解需求 → 调用 search_issues 工具 → 用 create_issue 工具的 schema 类似的方式过滤 → 返回结构化结果

5 个核心优势

1. 可组合

LLM + GitHub MCP + Notion MCP + Slack MCP = 全功能 AI 助理
不需要每个应用单独接入

2. 可复用

写一次 GitHub MCP Server,所有 LLM 客户端都能用
(Claude Desktop / Cursor / Continue.dev / 自研应用)

3. 可标准化

类似 USB / Bluetooth,统一了"AI 工具调用"的接口
未来类似"USB 设备"市场会兴起

4. 可安全控制

// MCP Server 可以加权限校验
if (!hasPermission(user, 'create_issue')) {
  throw new Error('Permission denied');
}

// 可以审计
logToolCall(user, tool, args);

5. 跨模型

不是 Anthropic 专属
GPT-5 / Gemini / Llama 都支持

5 个常见坑

坑 1:超时设置太短

// ❌ 默认 30s
const result = await fetchData();

// ✅ 长操作设置更长超时
const result = await fetchData({ timeout: 60000 });

坑 2:返回数据过大

// ❌ 返回 10MB JSON
return { content: JSON.stringify(hugeData) };

// ✅ 摘要 + 链接
return {
  content: `Found ${hugeData.length} items. First 10: ... [full data at file://...]`,
};

坑 3:错误信息不友好

// ❌ 抛 raw error
throw new Error('ECONNREFUSED');

// ✅ 返回结构化错误
return {
  isError: true,
  content: [{
    type: 'text',
    text: '无法连接数据库,请检查 DATABASE_URL 环境变量',
  }],
};

坑 4:忽略权限模型

// ❌ 任何人都能调用工具
const result = await deleteAllData();

// ✅ 加入权限检查
if (!hasPermission(user, 'delete')) {
  return { error: 'Permission denied' };
}

坑 5:没考虑 token 消耗

每个工具调用都消耗 LLM tokens
工具 description 要精炼
inputSchema 要最小化
返回数据要精简

我的看法

MCP 是 2026 年最重要的 AI 基础设施之一:

  1. 统一标准:让 LLM 工具调用从"各自为政"变成"统一接口"
  2. 生态飞轮:1000+ Server → 更多应用集成 → 更多 Server
  3. AI 时代的 USB:未来每个软件都会考虑"如何被 LLM 调用"

未来值得关注:

  • MCP Marketplace:类似 Apple App Store
  • 企业 MCP:私有 MCP Server(访问内部数据)
  • MCP + Agent:复杂多步骤任务编排
  • MCP 安全沙箱:防止恶意 Server

参考


本文示例基于 MCP 2026-06 版本,TypeScript SDK 最新版。

📚 同主题文章

🤖 AI / LLM 分类更多

🏷️ 本文标签

查看全部 99 篇文章 →