MCP (Model Context Protocol)
Claude Code 支持 MCP 协议,可以连接外部工具和数据源。
什么是 MCP?
Model Context Protocol 允许你为 AI 模型提供自定义上下文和工具能力。
基本配置
在配置文件中添加 MCP 服务器:
json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/files"]
}
}
}常用 MCP 服务器
| 服务器 | 说明 |
|---|---|
server-filesystem | 文件系统访问 |
server-github | GitHub 集成 |
server-postgres | PostgreSQL 数据库 |
server-slack | Slack 消息 |
配置示例
文件系统访问
json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "D:/projects"]
}
}
}GitHub 集成
json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your-github-token"
}
}
}
}数据库连接
json
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:password@localhost:5432/dbname"
}
}
}
}自定义 MCP 服务器
你可以创建自己的 MCP 服务器来扩展 Claude Code 的能力。详细文档请参考 MCP 官方文档。
创建自定义服务器
typescript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const server = new Server({
name: 'my-custom-server',
version: '1.0.0',
});
// 注册工具
server.setRequestHandler('tools/list', async () => {
return {
tools: [
{
name: 'my_tool',
description: '我的自定义工具',
inputSchema: {
type: 'object',
properties: {
input: { type: 'string' }
}
}
}
]
};
});
// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);