Skip to content

MCP (Model Context Protocol) 本地服务接入实战 ​

什么是 MCP? ​

Model Context Protocol (MCP) 是一个开放标准协议,旨在为 AI 客户端(如 Claude Desktop、Claude Code、Cursor、支持 MCP 的智能终端)与外部数据源、本地工具及 API 服务之间建立通用的双向通信管道。

过去,每个 AI 产品都有自己的插件规范(如 OpenAI Plugins、ChatGPT Actions、各类编辑器专属插件),开发者需要为不同平台重复封装适配器。MCP 的出现使开发者只需开发一次 MCP Server,任何支持 MCP 的客户端均可直接接入。

text
┌─────────────────┐       ┌─────────────────┐
│  Claude Code    │       │     Cursor      │
└────────┬────────┘       └────────┬────────┘
         │ (JSON-RPC)              │ (JSON-RPC)
         └───────────┬─────────────┘
                     ▼
        ┌─────────────────────────┐
        │       MCP Server        │
        │  (Resources, Tools...)  │
        └────────────┬────────────┘
                     ▼
        ┌─────────────────────────┐
        │  本地数据库 / API / 系统 │
        └─────────────────────────┘

核心概念:Resources、Prompts 与 Tools ​

MCP 抽象了三大核心能力:

  1. Resources(资源):向模型提供上下文数据(如只读文件、数据库记录、API 日志)。
  2. Prompts(提示模板):预定义的对话模板和角色指引。
  3. Tools(工具函数):具有输入 Schema 的可调用动作,能够执行命令、查询或修改外部系统。

快速实战:用 TypeScript 搭建一个 Git 状态 MCP Server ​

1. 初始化项目与安装依赖 ​

bash
mkdir mcp-git-server
cd mcp-git-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node tsx

2. 编写 MCP Server (index.ts) ​

typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { execSync } from "child_process";
import { z } from "zod";

const server = new Server(
  {
    name: "git-helper-mcp",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 声明可用工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "get_git_status",
        description: "获取指定本地仓库的当前 git 状态摘要(含变更文件和未追踪项)",
        inputSchema: {
          type: "object",
          properties: {
            repoPath: {
              type: "string",
              description: "本地 Git 仓库绝对路径",
            },
          },
          required: ["repoPath"],
        },
      },
    ],
  };
});

// 处理具体工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "get_git_status") {
    const { repoPath } = request.params.arguments as { repoPath: string };
    try {
      const statusOutput = execSync("git status --short", {
        cwd: repoPath,
        encoding: "utf-8",
      });
      return {
        content: [
          {
            type: "text",
            text: statusOutput || "Working tree clean, nothing to commit.",
          },
        ],
      };
    } catch (err: any) {
      return {
        isError: true,
        content: [{ type: "text", text: `Git execution error: ${err.message}` }],
      };
    }
  }
  throw new Error(`Tool not found: ${request.params.name}`);
});

// 使用标准输入输出 (stdio) 与 AI 客户端通信
const transport = new StdioServerTransport();
await server.connect(transport);

3. 在客户端配置接入 ​

在客户端的 MCP 配置文件中(例如 claude_desktop_config.json 或 AI 工具的 MCP 设置):

json
{
  "mcpServers": {
    "git-helper": {
      "command": "node",
      "args": ["--loader", "tsx", "/Users/mac/projects/mcp-git-server/index.ts"]
    }
  }
}

调试与安全治理 ​

  1. Stdio 模式禁止污染 console.log: MCP 使用标准输入输出传输严格的 JSON-RPC 消息。如果在 Server 代码中写了 console.log("debug"),会导致 JSON-RPC 解析失败崩掉。 调试信息务必输出至 console.error(...)(stderr)或文件日志。
  2. 入参必须使用 Schema (如 Zod) 严格校验: 防御命令注入风险(如包含特殊字符的路径)。
  3. 权限边界明确: 对于只读工具,避免执行任何变更操作。对高危操作(如删除、推送代码)在协议层声明需要确认。

总结 ​

MCP 正在成为大模型与外部环境交互的基石协议。通过标准化接口,我们可以快速把日常用的脚本、内网 API 和数据库打包成 MCP 服务,让各类 AI 编程助手直接成为团队的业务专家。

基于 VitePress 构建 | 记录真实开发与 AI 协作过程