devAlice
← AI Agents

MCP 服务器 — 将外部工具连接到 Claude Code / Cursor

通过 Model Context Protocol 将文件系统、GitHub、数据库、Slack 暴露给 AI 代理。配置、调试、安全。

Model Context Protocol(MCP) 是向 AI 代理暴露外部工具和数据的标准协议。由 Anthropic 提出的开放规范,已被 Claude Code、Cursor、Continue.dev 等采用 — 它们共享同一接口。

一句话概括:「我想让 Claude 或 GPT 直接操作文件系统 / 数据库 / GitHub,而不需要每次编写自定义 API 包装器。」

本指南涵盖核心概念、常见服务器配置、调试和安全。

TL;DR

  1. MCP 是 JSON-RPC over stdio/SSE — 通过标准化 RPC 暴露工具
  2. 官方 server:filesystem、GitHub、Slack、Postgres、Puppeteer 等 — @modelcontextprotocol/server-*
  3. 单一客户端配置:Claude Code 使用 ~/.claude/settings.json,Cursor 使用其设置 UI — 相同的 JSON schema
  4. 安全首要原则:优先使用只读 server;可写 server 只对显式 allow-list 目录开放

前提条件

  • Node.js 20+(用于 npx
  • 一个兼容 MCP 的客户端 — Claude Code 或 Cursor
  • 要暴露服务的 API token(GitHub PAT、Slack 等)

1. 30 秒了解 MCP 概念

术语含义
HostAI 代理(Claude Code、Cursor)
Server暴露工具/资源的进程(文件系统、GitHub)
ClientHost 创建的用于与每个 server 通信的适配器
Transportstdio(本地子进程)或 SSE(HTTP 远程)
Toolserver 暴露的函数 — AI 可以调用它
Resourceserver 暴露的数据 — AI 可以读取它
Promptserver 提供的 prompt 模板

2. 在 Claude Code 中添加 MCP

2.1 配置文件

~/.claude/settings.json

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/me/projects",
        "/Users/me/notes"
      ]
    }
  }
}
  • 命令参数 = 要暴露的目录,作为 allow-list — 其他路径不可访问。
  • 使用绝对路径,~/ 不会自动展开。

2.2 重启 Claude Code

# 结束上一个会话后
claude

2.3 验证

在 Claude Code 中:

What tools are available?

如果 filesystem MCP 的 read_file、write_file、list_directory 显示出来,则配置成功。

3. 在 Cursor 中添加 MCP

Settings(⌘,)→ Features → MCP → Add Server。JSON:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
    }
  }
}

schema 相同。可与 Claude Code 共享配置 — 直接复制 ~/.claude/settings.json 中的 mcpServers 块即可。

4. 六个常用服务器

4.1 Filesystem

"filesystem": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
}

读 / 写 / 搜索文件。强制执行路径白名单。

4.2 GitHub

"github": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-github"],
  "env": {
    "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."
  }
}

Issues、PR、代码搜索。PAT 权限范围:最小必要(reporead:user)。

4.3 Slack

"slack": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-slack"],
  "env": {
    "SLACK_BOT_TOKEN": "xoxb-...",
    "SLACK_TEAM_ID": "T..."
  }
}

频道读取 / 发送。优先使用 bot token 而非 user token。

4.4 PostgreSQL(只读)

"postgres": {
  "command": "npx",
  "args": [
    "-y",
    "@modelcontextprotocol/server-postgres",
    "postgresql://readonly_user:pass@localhost/mydb"
  ]
}

务必以只读用户身份连接 — AI 可执行任意查询,因此权限分离至关重要。

4.5 Puppeteer

"puppeteer": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
}

真实浏览器自动化。截图、DOM 操作、JS 执行。

4.6 SQLite

"sqlite": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-sqlite", "/path/to/db.sqlite"]
}

非常适合本地 SQLite 分析。

5. 通过 1Password 管理密钥

不要在 JSON 中以明文写入 token。推荐使用 multi-os/password-manager 中的方案:

方案 A — chezmoi 模板

~/.claude/settings.json 纳入 chezmoi 管理,使用 {{ onepasswordRead "op://..." }}

方案 B — 包装脚本

# ~/bin/mcp-github.sh
#!/bin/bash
export GITHUB_PERSONAL_ACCESS_TOKEN="$(op item get GitHub --fields token --reveal)"
exec npx -y @modelcontextprotocol/server-github

settings.json:

"github": {
  "command": "/Users/me/bin/mcp-github.sh"
}

op CLI 通过 GUI 生物识别自动解锁 1Password — 无感体验。

6. 编写自定义 MCP 服务器

十分钟暴露你自己的工具。Node.js(my-server.js):

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: "my-tools", version: "0.1.0" },
  { capabilities: { tools: {} } }
);
 
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "echo",
      description: "Echo back input",
      inputSchema: {
        type: "object",
        properties: { msg: { type: "string" } },
        required: ["msg"],
      },
    },
  ],
}));
 
server.setRequestHandler(CallToolRequestSchema, async (req) => {
  if (req.params.name === "echo") {
    return { content: [{ type: "text", text: req.params.arguments.msg }] };
  }
  throw new Error(`Unknown tool: ${req.params.name}`);
});
 
await server.connect(new StdioServerTransport());
"my-tools": {
  "command": "node",
  "args": ["/Users/me/code/my-server.js"]
}

参见 MCP SDK 官方示例

7. 调试

工具未显示

  • 完全重启客户端(Claude Code/Cursor)
  • 验证 npx 可运行 — which npx / Node 20+
  • 服务器日志 — Claude Code 下检查系统日志或 stderr

MCP Inspector

官方调试工具:

npx @modelcontextprotocol/inspector npx -y @modelcontextprotocol/server-filesystem /tmp

浏览器 UI,可直接发送 RPC 调用 — 可视化工具定义和响应。

响应慢

  • 首次调用:npx -y 下载包 — 一次慢,缓存后快
  • 永久安装:npm i -g @modelcontextprotocol/server-filesystem,然后 command: "mcp-server-filesystem"

8. 安全

仅允许 allow-list 文件夹

filesystem server,始终传入显式路径参数。省略路径参数,整个 home 目录都会暴露。

使用只读数据库用户

Postgres/SQLite 创建独立的只读用户。AI 不应有权执行 DROP TABLE

最小权限范围

GitHub PAT:repo + read:user,不要授予 admin:org

避免密钥泄露

不要将 settings.json 提交到 git。如果必须纳入版本管理,使用 chezmoi/secret 集成(§5)。

不要信任来源不明的 MCP server

坚持使用官方 @modelcontextprotocol/* 或可审计的开源包。不要将 token 交给任意 npm 包。

验证

  1. 编辑 settings.json 后重启 Claude Code → 询问「show available tools」→ 新服务器工具出现
  2. 「Show me files in the root」(使用 filesystem 服务器)
  3. 「Summarize the latest 5 PRs」(GitHub 服务器)
  4. 用 MCP Inspector 验证工具定义
  5. 尝试访问白名单外的路径 → 被拒绝

故障排查

npx -y 找不到包

  • @modelcontextprotocol/server-XXX 的包名拼写错误很常见。检查官方列表
  • 在企业 npm 仓库中,在 npmrc 中设置回退到公共仓库

Windows 路径问题

在 JSON 中转义 \ 或使用 /

"args": ["-y", "@modelcontextprotocol/server-filesystem", "C:/Users/me/projects"]

Claude Code 无法识别

  • 验证 ~/.claude/settings.json 语法 — jq . ~/.claude/settings.json
  • 与其他 settings.json 位置混淆(~/.claude.json、项目中的 .claude/settings.json

响应中部分工具缺失

listTools 处理器不确定性可能导致重启时结果不同。让 listTools 处理器确定性返回。

Token 被意外提交

立即轮换(GitHub → Personal access tokens → 撤销 + 重新颁发)。用 git filter-repo 清除 git 历史。

参考资料

更新日志

  • 2026-05-12:初稿。概念 + 客户端配置 + 6 个服务器 + 密钥管理 + 自定义服务器 + 调试 + 安全 + 五个故障排查案例。