🚀 进阶教程

MCP (Model Context Protocol) 集成

MCP 是 Anthropic 推出的开放协议,允许 Claude Code 连接外部工具和服务。 通过 MCP,你可以扩展 Claude Code 的能力,让它访问数据库、调用 API、 操作文件系统等。

什么是 MCP Server?

MCP Server 是一个独立的程序,提供一组工具供 Claude Code 调用。 每个 Server 可以定义自己的工具和资源。

配置 MCP Server

MCP 配置
1
2
3
4
5
6
7
8
9
10
# Claude Code 会自动检测项目中的 .mcp/ 目录
# 或者你可以在 CLAUDE.md 中配置

# 示例:配置一个简单的文件系统 MCP
# .mcp/filesystem.json
{
  "name": "filesystem",
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
}

常用 MCP Servers

  • @modelcontextprotocol/server-filesystem - 文件系统操作
  • @modelcontextprotocol/server-postgres - PostgreSQL 数据库
  • @modelcontextprotocol/server-github - GitHub API
  • @modelcontextprotocol/server-slack - Slack 集成

自定义工具开发

你可以创建自己的 MCP Server 来扩展 Claude Code 的功能。

创建简单的 MCP Server

MCP Server 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// my-mcp-server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "my-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;
    // 实现你的逻辑
    return {
      content: [{ type: "text", text: `${city} 今天晴,25°C` }]
    };
  }
});

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

多文件编辑

Claude Code 能够理解项目结构,并执行跨多文件的编辑任务。

示例:重构整个模块

Claude Code 提示
1
2
3
4
5
6
7
将 src/auth 模块重构为使用 JWT 代替 session:

1. 更新 src/auth/index.ts 使用 JWT
2. 创建 src/auth/jwt.ts 处理 token 生成和验证
3. 更新所有使用 auth 的 API 路由
4. 更新前端代码适配新的认证方式
5. 添加必要的类型定义

Claude Code 会分析整个项目,找出所有需要修改的文件, 并按正确的顺序进行修改。

Git 工作流集成

代码审查

Claude Code 提示
1
2
3
4
5
6
7
8
审查当前分支相对于 main 分支的所有更改,
检查:
1. 潜在的 bug
2. 性能问题
3. 安全漏洞
4. 代码风格问题

提供改进建议。

生成提交信息

Claude Code 提示
1
2
根据当前的 git diff 生成一个清晰的提交信息,
使用 conventional commits 格式。

解决冲突

Claude Code 提示
1
2
帮助我解决当前的 git merge 冲突,
分析两边的更改并给出合并建议。

CLAUDE.md 配置

CLAUDE.md 是项目根目录下的配置文件,用于告诉 Claude Code 项目的上下文信息。

CLAUDE.md 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# CLAUDE.md

## 项目概述
这是一个 Next.js 14 项目,使用 TypeScript 和 Tailwind CSS。

## 代码风格
- 使用函数组件和 React Hooks
- 使用 const 定义常量
- 优先使用命名导出

## 禁止事项
- 不要修改 .env 文件
- 不要运行数据库迁移命令

## 常用命令
- npm run dev: 启动开发服务器
- npm run build: 构建生产版本
- npm test: 运行测试

## MCP 配置
@mcp/database.json
@mcp/github.json

高级命令行选项

高级参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 指定模型
claude --model claude-4-opus

# 设置最大思考时间
claude --thinking-budget 10000

# 跳过权限确认 (谨慎使用)
claude --permission-mode bypassPermissions

# 指定工作目录
claude --cd /path/to/project

# 使用特定配置文件
claude --config ./claude.config.json

# 启用详细日志
claude --verbose

🔧 MCP 实战教程

实战 1: 创建天气 MCP Server

从零开始创建一个完整的天气查询 MCP Server。

步骤 1: 创建项目结构

终端
1
2
3
mkdir weather-mcp-server && cd weather-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk axios

步骤 2: 创建 MCP Server

index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import axios from "axios";

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

// 定义工具
server.setRequestHandler("tools/list", async () => {
  return {
    tools: [
      {
        name: "get_weather",
        description: "获取指定城市的天气信息",
        inputSchema: {
          type: "object",
          properties: {
            city: { 
              type: "string", 
              description: "城市名称(如 Beijing, Shanghai)" 
            }
          },
          required: ["city"]
        }
      },
      {
        name: "get_forecast",
        description: "获取城市未来几天的天气预报",
        inputSchema: {
          type: "object",
          properties: {
            city: { type: "string", description: "城市名称" },
            days: { type: "number", description: "预报天数(1-7)" }
          },
          required: ["city"]
        }
      }
    ]
  };
});

// 处理工具调用
server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;
  
  if (name === "get_weather") {
    const response = await axios.get(
      `https://wttr.in/${args.city}?format=j1`
    );
    const current = response.data.current_condition[0];
    return {
      content: [{
        type: "text",
        text: `🌤️ ${args.city} 天气:\n` +
              `温度: ${current.temp_C}°C\n` +
              `天气: ${current.weatherDesc[0].value}\n` +
              `湿度: ${current.humidity}%\n` +
              `风速: ${current.windspeedKmph} km/h`
      }]
    };
  }
  
  if (name === "get_forecast") {
    const response = await axios.get(
      `https://wttr.in/${args.city}?format=j1`
    );
    const days = args.days || 3;
    const forecast = response.data.weather.slice(0, days);
    
    const text = forecast.map(day => 
      `📅 ${day.date}: ${day.avgtempC}°C, ${day.hourly[4].weatherDesc[0].value}`
    ).join("\n");
    
    return { content: [{ type: "text", text }] };
  }
  
  throw new Error(`Unknown tool: ${name}`);
});

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

步骤 3: 配置到 Claude Code

.mcp/weather.json
1
2
3
4
5
6
// .mcp/weather.json
{
  "name": "weather",
  "command": "node",
  "args": ["/path/to/weather-mcp-server/dist/index.js"]
}

步骤 4: 测试

测试输出
1
2
3
4
5
6
7
8
9
# 在 Claude Code 中
今天北京天气怎么样?

# Claude 会自动调用 weather MCP Server
🌤️ Beijing 天气:
温度: 22°C
天气: Partly cloudy
湿度: 45%
风速: 12 km/h

实战 2: PostgreSQL 数据库连接

使用官方 PostgreSQL MCP Server 连接数据库。

安装
1
2
# 安装官方 MCP Server
npm install -g @modelcontextprotocol/server-postgres
.mcp/database.json
1
2
3
4
5
6
7
8
9
10
// .mcp/database.json
{
  "name": "postgres",
  "command": "npx",
  "args": [
    "-y",
    "@modelcontextprotocol/server-postgres",
    "postgresql://user:password@localhost:5432/mydb"
  ]
}
使用示例
1
2
3
4
5
# 在 Claude Code 中使用
查询 users 表中最近注册的 10 个用户

# Claude 会生成并执行 SQL
SELECT * FROM users ORDER BY created_at DESC LIMIT 10;

实战 3: GitHub 集成

配置 GitHub MCP Server 进行代码仓库操作。

.mcp/github.json
1
2
3
4
5
6
7
8
9
// .mcp/github.json
{
  "name": "github",
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-github"],
  "env": {
    "GITHUB_TOKEN": "ghp_your_token_here"
  }
}
使用示例
1
2
3
4
5
6
# 在 Claude Code 中使用
列出我的仓库中最近的 PR

创建一个新 issue,标题是 "修复登录 bug"

查看 owner/repo 仓库的最新 release

🎯 最佳实践

  • 在开始大型任务前,让 Claude Code 先制定计划
  • 使用 Git 分支来隔离 Claude Code 的实验性修改
  • 为复杂任务提供清晰的步骤和预期结果
  • 定期检查 Claude Code 的修改,确保符合预期