MCP 协议实战:我用它让 Claude 直接操作我的数据库
MCP(Model Context Protocol)是 Anthropic 推出的开放协议,让 AI 模型可以直接连接外部工具和数据源。
我用 MCP 让 Claude 直接操作 PostgreSQL 数据库,效果超出预期。
什么是 MCP
MCP 是一个标准化协议,类似于 AI 世界的 USB-C:
- **统一接口**:所有工具用同一种方式连接
- **即插即用**:配置好就能用
- **安全可控**:权限可以精细控制
架构设计
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude │────▶│ MCP Client │────▶│ MCP Server │
│ Desktop │ │ (内置) │ │ (数据库) │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ PostgreSQL │
└─────────────┘安装配置
1. 安装 MCP Server
# 使用 npm 安装 PostgreSQL MCP Server
npm install -g @modelcontextprotocol/server-postgres2. 配置 Claude Desktop
编辑 ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://user:password@localhost:5432/mydb"
]
}
}
}3. 重启 Claude Desktop
重启后,Claude 会自动发现可用的 MCP 工具。
实战演示
查询数据
我:帮我查看用户表中注册时间在最近 7 天的用户数量。
Claude:
SELECT COUNT(*) as new_users
FROM users
WHERE created_at >= NOW() - INTERVAL '7 days';执行结果:new_users = 1,234
最近 7 天有 1,234 个新用户注册。
分析数据
我:分析一下用户的活跃度分布,按最后登录时间分组。
Claude:
SELECT
CASE
WHEN last_login >= NOW() - INTERVAL '1 day' THEN '今天'
WHEN last_login >= NOW() - INTERVAL '7 days' THEN '最近7天'
WHEN last_login >= NOW() - INTERVAL '30 days' THEN '最近30天'
ELSE '30天前'
END as activity_group,
COUNT(*) as user_count,
ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 2) as percentage
FROM users
GROUP BY activity_group
ORDER BY
CASE activity_group
WHEN '今天' THEN 1
WHEN '最近7天' THEN 2
WHEN '最近30天' THEN 3
ELSE 4
END;执行结果:
| 活跃度 | 用户数 | 占比 |
|--------|--------|------|
| 今天 | 5,678 | 12.3% |
| 最近7天 | 15,432 | 33.5% |
| 最近30天 | 18,765 | 40.7% |
| 30天前 | 6,234 | 13.5% |
修改数据
我:把所有测试用户的状态改为 inactive。
Claude:
在执行修改操作前,我需要确认:
1. 测试用户的判断标准是什么?(邮箱包含 test?用户名以 test_ 开头?)
2. 这个操作会影响多少条记录?
让我先查询一下:
SELECT COUNT(*)
FROM users
WHERE email LIKE '%test%' OR username LIKE 'test_%';结果:共有 45 个测试用户。
确认要将这 45 个用户的状态改为 inactive 吗?
我:确认。
Claude:
UPDATE users
SET status = 'inactive', updated_at = NOW()
WHERE email LIKE '%test%' OR username LIKE 'test_%';已更新 45 条记录。
高级用法
自定义 MCP Server
我写了一个自定义 MCP Server,让 Claude 可以调用内部 API:
// 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: "internal-api",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// 定义可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "get_user_orders",
description: "获取用户的所有订单",
inputSchema: {
type: "object",
properties: {
user_id: {
type: "string",
description: "用户 ID",
},
},
required: ["user_id"],
},
},
{
name: "send_notification",
description: "发送通知给用户",
inputSchema: {
type: "object",
properties: {
user_id: { type: "string" },
message: { type: "string" },
},
required: ["user_id", "message"],
},
},
],
};
});
// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case "get_user_orders": {
const response = await fetch(
`https://api.internal.com/users/${args.user_id}/orders`,
{ headers: { Authorization: `Bearer ${process.env.API_TOKEN}` } }
);
const orders = await response.json();
return {
content: [{ type: "text", text: JSON.stringify(orders, null, 2) }],
};
}
case "send_notification": {
await fetch("https://api.internal.com/notifications", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
body: JSON.stringify({
user_id: args.user_id,
message: args.message,
}),
});
return {
content: [{ type: "text", text: "通知已发送" }],
};
}
default:
throw new Error(`Unknown tool: ${name}`);
}
});
// 启动服务器
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main();多 MCP Server 组合
可以同时配置多个 MCP Server:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "..."]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "..."
}
},
"internal-api": {
"command": "node",
"args": ["./mcp-server.ts"],
"env": {
"API_TOKEN": "..."
}
}
}
}这样 Claude 可以同时访问数据库、文件系统、GitHub 和内部 API。
安全考虑
1. 权限控制
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "..."],
"permissions": {
"read": true,
"write": false
}
}
}
}2. 审计日志
所有 MCP 调用都会记录在 Claude Desktop 的日志中,可以追溯。
3. 网络隔离
MCP Server 运行在本地,不暴露到公网,安全性更高。
性能测试
| 操作 | 延迟 | 成功率 |
|------|------|--------|
| 简单查询 | 50ms | 100% |
| 复杂查询 | 200ms | 100% |
| 数据修改 | 100ms | 100% |
| 批量操作 | 500ms | 98% |
性能表现良好,延迟在可接受范围内。
使用场景
适合 MCP 的场景
1. 数据分析:让 AI 直接查询和分析数据
2. 运维操作:自动化日常运维任务
3. 开发辅助:直接操作开发环境
4. 内容管理:批量更新 CMS 内容
不适合 MCP 的场景
1. 生产环境直接操作:风险太高
2. 高频调用:MCP 不是为高并发设计的
3. 实时系统:延迟不可控
总结
MCP 是一个革命性的协议,让 AI 真正能够"动手"操作外部系统。
优势:
- 统一接口,易于集成
- 安全可控,权限精细
- 生态丰富,工具众多
局限:
- 目前只有 Claude Desktop 支持
- 不适合生产环境直接操作
- 需要一定的配置工作
推荐用法:开发环境 + 数据分析 + 自动化任务
实践时间:2026年7月
MCP Server 数量:15 个
自动化任务:200+ 个
#MCP #Claude #AI工具 #自动化
读者评论 2