MCP 是什么
Model Context Protocol(MCP)是 Anthropic 在 2024 年 11 月发布的开放标准协议,旨在解决一个核心问题: 如何让 AI 助手安全、标准化地访问外部工具与数据源,而不是为每个 AI 应用单独开发集成代码。
为什么 MCP 重要?在 MCP 之前,让 AI 访问数据库需要为每个 AI 工具单独写集成代码。有了 MCP,只需要写一次 MCP Server,所有支持 MCP 的 AI 工具都能使用它。这极大降低了 AI 集成的重复工作。
Cursor 中的 MCP
在 Cursor 中,MCP 工具只在 Agent 模式下可用。当你启动 Agent 模式后,AI 会自动看到所有已配置的 MCP 工具,并根据任务需要自主决定是否调用。 你不需要手动触发 MCP 工具调用——AI 会在合适的时机自动使用。
配置 MCP Server
在 Cursor 中配置 MCP Server 有两种方式:
- 全局配置(~/.cursor/mcp.json) 对所有项目生效,适合通用工具(如文件系统、Web 搜索)。
- 项目配置(.cursor/mcp.json) 只对当前项目生效,适合项目专属工具(如连接特定数据库、项目文档搜索)。推荐将此文件加入 .gitignore(包含敏感凭证时)或加入版本控制(团队共享配置时)。
// .cursor/mcp.json 配置格式示例
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxx..."
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres",
"postgresql://user:pass@localhost:5432/mydb"]
},
"puppeteer": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-puppeteer"]
}
}
}
常用官方 MCP Server
| Server | 功能 | 安装 | 典型用途 |
|---|---|---|---|
server-filesystem |
读写本地文件系统 | npx | 让 Agent 读取项目外文件、管理文档 |
server-github |
GitHub API | npx | 创建 PR、查询 Issue、搜索代码 |
server-postgres |
PostgreSQL 查询 | npx | 查询数据库 schema 和数据 |
server-puppeteer |
浏览器自动化 | npx | 截图、爬取网页、UI 测试 |
server-slack |
Slack API | npx | 发送消息、查询频道历史 |
server-memory |
知识图谱记忆 | npx | AI 跨会话记忆用户偏好 |
编写自定义 MCP Server
当官方 MCP Server 不满足需求时,可以用 Python SDK 快速编写自定义服务器:
# 安装 MCP Python SDK
# pip install mcp
from mcp.server import Server, StdioServerTransport
from mcp.types import Tool, TextContent
import json
import sqlite3
# 创建 MCP Server 实例
server = Server("my-product-db") # Server 名称(在 Cursor 中显示)
@server.list_tools()
async def list_tools():
"""声明此 Server 提供的工具列表"""
return [
Tool(
name="query_products",
description="查询产品数据库,根据条件筛选产品信息",
inputSchema={
"type": "object",
"properties": {
"category": {"type": "string", "description": "产品类别,如 electronics, clothing"},
"max_price": {"type": "number", "description": "最高价格(元)"},
"limit": {"type": "integer", "description": "返回条数,默认10", "default": 10}
},
"required": ["category"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
"""处理工具调用请求"""
if name == "query_products":
conn = sqlite3.connect("products.db")
cursor = conn.cursor()
query = "SELECT name, price, stock FROM products WHERE category = ?"
params = [arguments["category"]]
if "max_price" in arguments:
query += " AND price <= ?"
params.append(arguments["max_price"])
query += f" LIMIT {arguments.get('limit', 10)}"
cursor.execute(query, params)
rows = cursor.fetchall()
conn.close()
result = [f"产品名: {r[0]}, 价格: {r[1]}元, 库存: {r[2]}" for r in rows]
return [TextContent(type="text", text="\n".join(result) or "未找到产品")]
# 运行服务器(标准输入/输出传输)
if __name__ == "__main__":
import asyncio
from mcp.server.stdio import stdio_server
asyncio.run(stdio_server(server))
# 注册自定义 MCP Server(.cursor/mcp.json):
{
"mcpServers": {
"product-db": {
"command": "python3",
"args": ["/path/to/product_mcp_server.py"],
"cwd": "/path/to/project"
}
}
}
# 配置后,在 Cursor Agent 模式中,AI 可以自然语言调用:
# "查询电子产品类别中价格低于200元的产品"
# Agent 会自动调用 query_products 工具
MCP 安全注意事项
不要把敏感凭证写在 mcp.json 中并提交到 Git!
数据库密码、API Key 等应该通过环境变量传入:
# .cursor/mcp.json — 只引用环境变量名
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres",
"${DATABASE_URL}"] // 引用环境变量
}
}
}
在 shell 中设置:export DATABASE_URL="postgresql://..."
MCP 工具权限最小化:给 AI 的数据库账号只给 SELECT 权限,不给 INSERT/UPDATE/DELETE。给文件系统工具指定具体的允许目录,不给根目录访问权限。一旦 Agent 出现错误行为,有限的权限能大幅缩小损害范围。
本章小结
- MCP 是 AI 工具集成的标准协议,让 Cursor Agent 能访问任意外部工具与数据源
- 通过 .cursor/mcp.json 配置 MCP Server,项目级配置只对当前项目生效
- 官方提供了文件系统、GitHub、PostgreSQL、浏览器等常用 Server,可直接 npx 启动
- 用 Python MCP SDK 可以快速开发业务专属工具,连接内部数据库和 API
- 安全第一:凭证用环境变量,工具权限最小化,避免 Agent 意外操作生产数据