Skip to content

MCP Server 与扩展生态

什么是 MCP(模型上下文协议)

MCP(Model Context Protocol,模型上下文协议) 是 Anthropic 于 2024 年底开源的标准协议,用于解决 AI 模型与外部工具、数据源之间的集成问题。

在 MCP 之前,每个 AI 工具都需要为每个外部服务单独开发集成,维护成本极高。MCP 定义了一套统一的通信规范,让任何 AI 应用都能通过相同的方式接入任意数据源或工具。

核心概念

┌─────────────────────────────────────────────────────┐
│                    MCP 架构                          │
│                                                     │
│  ┌─────────────┐      ┌────────────────────────┐   │
│  │  MCP 客户端  │◄────►│    MCP 服务器           │   │
│  │ (Claude Code│      │  ┌─────────────────┐   │   │
│  │  Cursor 等) │      │  │  Resources(资源)│   │   │
│  └─────────────┘      │  ├─────────────────┤   │   │
│                        │  │  Tools(工具)   │   │   │
│                        │  ├─────────────────┤   │   │
│                        │  │  Prompts(提示) │   │   │
│                        │  └─────────────────┘   │   │
│                        └────────────────────────┘   │
└─────────────────────────────────────────────────────┘

MCP 服务器提供三类能力:

类型说明示例
Resources暴露可读取的数据文件内容、数据库记录、API 响应
Tools提供可调用的函数写文件、执行查询、发送请求
Prompts预定义的提示模板代码审查模板、文档生成模板

MCP 的工作流程

1. AI 应用(客户端)启动时连接已配置的 MCP 服务器
2. 服务器声明自己能提供哪些 Tools 和 Resources
3. 用户发出请求,AI 判断是否需要调用外部工具
4. AI 通过 MCP 协议向服务器发送工具调用请求
5. 服务器执行操作并返回结果
6. AI 将结果整合到响应中呈现给用户

常用 MCP 服务器详解

1. Filesystem(文件系统)

最基础的 MCP 服务器,提供对本地文件系统的读写访问。

json
// 配置示例
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/projects",
        "/Users/username/documents"
      ]
    }
  }
}

提供的工具:

  • read_file:读取文件内容
  • write_file:写入文件
  • list_directory:列出目录
  • create_directory:创建目录
  • move_file:移动/重命名文件
  • search_files:按模式搜索文件

典型用法:

> 扫描 /projects/my-app/src 目录,找出所有超过 300 行的文件,
> 并给出重构建议

2. Database(数据库)

PostgreSQL

json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "postgresql://user:pass@localhost:5432/mydb"
      }
    }
  }
}

提供的工具:

  • query:执行 SQL 查询(只读)
  • list_tables:列出所有表
  • describe_table:查看表结构

典型用法:

> 分析 orders 表的数据分布,找出最近 30 天销售额最高的 10 个商品,
> 并解释查询的性能特征

SQLite

json
{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "/path/to/database.db"]
    }
  }
}

3. Web Search(网络搜索)

让 Claude 能够实时搜索互联网获取最新信息。

json
{
  "mcpServers": {
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "your-api-key"
      }
    }
  }
}

典型用法:

> 搜索 React 19 的最新特性,对比我们项目当前使用的 React 18 API,
> 评估升级的影响范围

4. Playwright(浏览器自动化)

通过 Playwright MCP 服务器,Claude 能够控制浏览器执行网页交互。

json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest"]
    }
  }
}

提供的工具:

  • browser_navigate:导航到 URL
  • browser_click:点击页面元素
  • browser_fill_form:填写表单
  • browser_take_screenshot:截图
  • browser_snapshot:获取页面 DOM 快照
  • browser_evaluate:执行 JavaScript

典型用法:

> 打开我们的登录页面 http://localhost:3000/login,
> 用测试账号登录,截图确认登录成功,
> 然后检查用户中心页面是否显示正确的用户信息

5. GitHub

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_your_token"
      }
    }
  }
}

提供的工具:

  • 创建/管理 Issues
  • 搜索代码仓库
  • 管理 Pull Requests
  • 读取仓库内容

6. Memory(持久记忆)

跨会话保存和检索信息:

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

在 Claude Code 中配置 MCP 服务器

配置文件位置

MCP 服务器在 Claude Code 的 settings.json 中配置:

~/.claude/settings.json         ← 全局配置(所有项目可用)
.claude/settings.json           ← 项目级配置(随项目共享)
.claude/settings.local.json     ← 本地配置(不提交 Git)

完整配置示例

json
// ~/.claude/settings.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/projects"
      ]
    },
    "postgres-dev": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "postgresql://localhost:5432/myapp_dev"
      }
    },
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "BSA..."
      }
    },
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest"]
    }
  }
}

验证 MCP 服务器连接

bash
# 启动 Claude Code 时会自动连接配置的 MCP 服务器
claude

# 查看已连接的 MCP 服务器
> /mcp

# 在对话中测试
> 使用文件系统工具列出当前目录的内容

构建自定义 MCP 服务器

当现有 MCP 服务器不满足需求时,可以构建自己的服务器。

使用 TypeScript SDK

bash
npm install @modelcontextprotocol/sdk
typescript
// my-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: "my-custom-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 声明可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "get_weather",
        description: "获取指定城市的当前天气",
        inputSchema: {
          type: "object",
          properties: {
            city: {
              type: "string",
              description: "城市名称",
            },
          },
          required: ["city"],
        },
      },
    ],
  };
});

// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "get_weather") {
    const { city } = request.params.arguments as { city: string };
    
    // 实现天气查询逻辑
    const weather = await fetchWeather(city);
    
    return {
      content: [
        {
          type: "text",
          text: `${city} 当前天气:${weather.description},${weather.temperature}°C`,
        },
      ],
    };
  }
  
  throw new Error(`未知工具:${request.params.name}`);
});

// 启动服务器(通过标准输入输出通信)
const transport = new StdioServerTransport();
await server.connect(transport);

使用 Python SDK

bash
pip install mcp
python
# my_mcp_server.py
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent, CallToolResult
import mcp.types as types

app = Server("my-python-server")

@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="query_database",
            description="查询内部数据库并返回结果",
            inputSchema={
                "type": "object",
                "properties": {
                    "sql": {
                        "type": "string",
                        "description": "SQL 查询语句(只读)"
                    }
                },
                "required": ["sql"]
            }
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> CallToolResult:
    if name == "query_database":
        sql = arguments["sql"]
        # 执行查询逻辑
        results = await execute_query(sql)
        return CallToolResult(
            content=[TextContent(type="text", text=str(results))]
        )

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream, app.create_initialization_options())

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

在 Claude Code 中注册自定义服务器

json
// ~/.claude/settings.json
{
  "mcpServers": {
    "my-weather-server": {
      "command": "node",
      "args": ["/path/to/my-mcp-server.js"]
    },
    "my-python-server": {
      "command": "python",
      "args": ["/path/to/my_mcp_server.py"]
    }
  }
}

安全注意事项

在使用 MCP 服务器时,需要注意以下安全原则:

最小权限原则

json
// 只授权必要的目录访问权限
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/projects/my-app"  // 不要授权整个根目录
      ]
    }
  }
}

敏感信息管理

bash
# 在 settings.local.json 中配置包含密钥的服务器(不提交 Git)
# .claude/settings.local.json
{
  "mcpServers": {
    "production-db": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "postgresql://prod-server/prod-db"
      }
    }
  }
}

数据库只读访问

sql
-- 为 MCP 服务器创建专用只读用户
CREATE USER mcp_readonly WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE myapp TO mcp_readonly;
GRANT USAGE ON SCHEMA public TO mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;

扩展生态展望

MCP 协议自发布以来,生态发展迅速:

官方服务器(Anthropic 维护)

  • @modelcontextprotocol/server-filesystem
  • @modelcontextprotocol/server-postgres
  • @modelcontextprotocol/server-sqlite
  • @modelcontextprotocol/server-brave-search
  • @modelcontextprotocol/server-github
  • @modelcontextprotocol/server-memory
  • @modelcontextprotocol/server-slack
  • @modelcontextprotocol/server-google-maps

社区服务器(精选)

服务器功能
mcp-server-kubernetesKubernetes 集群管理
mcp-server-awsAWS 服务操作
mcp-server-jiraJira 项目管理
mcp-server-notionNotion 文档操作
mcp-server-stripeStripe 支付 API
mcp-server-linearLinear 任务管理

发现更多 MCP 服务器

MCP 的开放生态正在快速成长,越来越多的 SaaS 服务商开始提供官方 MCP 服务器,意味着 AI 能直接操作的工具范围将持续扩大。