将 FastMCP 集成到 Cursor IDE 中
将 FastMCP 集成到 Cursor IDE
Cursor IDE 对模型上下文协议(Model Context Protocol,简称 MCP)服务器提供了出色的支持,让您能够将 FastMCP 服务器无缝集成到您的开发工作流程中。本指南将引导您完成 FastMCP 服务器与 Cursor 的设置和使用。
Cursor 中的 MCP 是什么?
模型上下文协议(MCP)是一种将 Cursor 连接到外部工具和数据源的协议。您无需反复解释您的项目结构,而是可以直接与您的工具集成。
Cursor 支持用任何能够输出到 stdout
或提供 HTTP 端点的语言编写的 MCP 服务器——这使得 FastMCP(Python)成为完美的选择!
为什么将 FastMCP 与 Cursor 结合使用?
FastMCP 的简洁性和强大功能使其成为 Cursor 集成的理想选择:
- 快速开发:以最少的样板代码构建 MCP 服务器
- 丰富工具:创建具有类型安全的复杂工具
- 资源访问:为您的 AI 助手提供上下文数据
- 轻松部署:针对不同用例提供多种传输选项
传输方式
Cursor 支持 MCP 服务器的三种传输方式:
传输方式 | 执行方式 | 部署方式 | 用户数量 | 输入 | 认证方式 |
---|---|---|---|---|---|
stdio |
本地 | Cursor 管理 | 单个用户 | Shell 命令 | 手动 |
SSE |
本地/远程 | 部署为服务器 | 多个用户 | SSE 端点 URL | OAuth |
Streamable HTTP |
本地/远程 | 部署为服务器 | 多个用户 | HTTP 端点 URL | OAuth |
对于 FastMCP 服务器,我们将重点关注 stdio
方法,以便进行本地开发和测试。
使用 Cursor 设置 FastMCP
步骤 1:创建您的 FastMCP 服务器
首先,让我们创建一个提供开发工具的简单 FastMCP 服务器:
# cursor_dev_tools.py
import asyncio
import subprocess
from pathlib import Path
from fastmcp import FastMCP
# 创建 MCP 服务器
mcp = FastMCP("Cursor Development Tools")
@mcp.tool()
def get_project_structure(max_depth: int = 2) -> str:
"""获取当前项目结构,可指定最大深度。"""
try:
result = subprocess.run(
["find", ".", "-type", "f", "-name", "*.py", "-o", "-name", "*.js", "-o", "-name", "*.ts", "-o", "-name", "*.json"],
capture_output=True,
text=True,
cwd="."
)
files = result.stdout.strip().split('\n')
# 按目录组织
structure = {}
for file in files:
if file:
parts = Path(file).parts
current = structure
for part in parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
current[parts[-1]] = "file"
return f"Project Structure:\n{_format_structure(structure)}"
except Exception as e:
return f"Error getting project structure: {str(e)}"
def _format_structure(structure, indent=0):
"""将结构字典格式化为树形结构。"""
result = []
for key, value in structure.items():
prefix = " " * indent + "├── "
if isinstance(value, dict):
result.append(f"{prefix}{key}/")
result.append(_format_structure(value, indent + 1))
else:
result.append(f"{prefix}{key}")
return "\n".join(result)
@mcp.tool()
def run_command(command: str, working_dir: str = ".") -> str:
"""在指定目录执行 shell 命令。"""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=working_dir,
timeout=30
)
output = []
if result.stdout:
output.append(f"STDOUT:\n{result.stdout}")
if result.stderr:
output.append(f"STDERR:\n{result.stderr}")
output.append(f"Return code: {result.returncode}")
return "\n\n".join(output)
except subprocess.TimeoutExpired:
return "Command timed out after 30 seconds"
except Exception as e:
return f"Error executing command: {str(e)}"
@mcp.tool()
def search_code(pattern: str, file_extension: str = "py") -> str:
"""在项目文件中搜索代码模式。"""
try:
result = subprocess.run(
["grep", "-r", "--include", f"*.{file_extension}", pattern, "."],
capture_output=True,
text=True
)
if result.returncode == 0:
return f"Found matches for '{pattern}':\n\n{result.stdout}"
else:
return f"No matches found for pattern '{pattern}' in *.{file_extension} files"
except Exception as e:
return f"Error searching code: {str(e)}"
@mcp.resource("file://project-docs")
async def get_project_docs():
"""提供项目文档和 README 文件。"""
docs = []
# 查找常见的文档文件
doc_files = ["README.md", "README.rst", "docs/README.md", "CONTRIBUTING.md"]
for doc_file in doc_files:
path = Path(doc_file)
if path.exists():
try:
content = path.read_text()
docs.append(f"=== {doc_file} ===\n{content}\n")
except Exception as e:
docs.append(f"=== {doc_file} ===\nError reading file: {str(e)}\n")
if not docs:
docs.append("No documentation files found in project root.")
return "\n".join(docs)
if __name__ == "__main__":
mcp.run()
步骤 2:在 Cursor 中配置 MCP
您有两种配置选项:
选项 A:项目特定配置
在您的项目根目录下创建 .cursor/mcp.json
:
{
"mcpServers": {
"fastmcp-dev-tools": {
"command": "python",
"args": ["cursor_dev_tools.py"],
"env": {}
}
}
}
选项 B:全局配置
在您的主目录中创建 ~/.cursor/mcp.json
以便全局访问:
{
"mcpServers": {
"fastmcp-dev-tools": {
"command": "python",
"args": ["/path/to/your/cursor_dev_tools.py"],
"env": {}
}
}
}
步骤 3:使用环境变量
对于需要 API 密钥或配置的服务器:
{
"mcpServers": {
"fastmcp-api-server": {
"command": "python",
"args": ["api_server.py"],
"env": {
"API_KEY": "your-api-key-here",
"DEBUG": "true"
}
}
}
}
在 Cursor 中使用 MCP 工具
自动使用工具
Cursor Composer Agent 会在相关时自动使用“可用工具”下列出的 MCP 工具。您的 FastMCP 工具将显示在聊天界面中。
手动调用工具
您也可以按名称请求特定工具:
- “使用 get_project_structure
工具显示项目布局”
- “运行 search_code
工具查找所有异步函数”
- “执行 run_command
来安装依赖”
工具批准和自动运行
默认情况下,Cursor 在使用 MCP 工具前会征求您的批准。您可以选择:
- 手动批准:点击工具名称旁边的箭头以查看参数并批准
- 自动运行模式:启用“Yolo 模式”以自动执行工具,无需批准
适用于 Cursor 的 FastMCP 高级功能
返回图像
FastMCP 服务器可以返回图像,Cursor 会在聊天中显示:
import base64
from fastmcp import FastMCP
mcp = FastMCP("Image Generator")
@mcp.tool()
def generate_diagram() -> dict:
"""生成简单图表并以图像形式返回。"""
# 创建或生成您的图像
with open("diagram.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode()
return {
"content": [
{
"type": "image",
"data": image_data,
"mimeType": "image/png"
}
]
}
复杂资源提供者
使用 FastMCP 的资源系统来提供丰富的上下文数据:
@mcp.resource("file://git-status")
async def get_git_status():
"""提供当前 git 仓库状态。"""
try:
# 获取 git 状态
status_result = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True,
text=True
)
# 获取最近的提交
log_result = subprocess.run(
["git", "log", "--oneline", "-10"],
capture_output=True,
text=True
)
return f"Git Status:\n{status_result.stdout}\n\nRecent Commits:\n{log_result.stdout}"
except Exception as e:
return f"Error getting git status: {str(e)}"
调试与故障排除
查看 MCP 日志
要在 Cursor 中调试 MCP 服务器问题:
- 打开输出面板(Mac 上按
⌘⇧U
,Windows/Linux 上按Ctrl+Shift+U
) - 从下拉菜单中选择“MCP Logs”(MCP 日志)
- 检查连接错误、认证问题或服务器崩溃
常见问题
服务器未启动
- 检查 Python 和您的脚本是否在正确的路径中
- 验证 mcp.json
配置语法
- 确保所有依赖项已安装
工具未显示 - 更改配置后重启 Cursor - 检查 MCP 日志是否有错误消息 - 验证您的 FastMCP 服务器是否可以从命令行正确运行
权限错误 - 确保 Python 脚本具有执行权限 - 检查 Cursor 是否有权访问指定的目录
测试您的服务器
独立测试您的 FastMCP 服务器:
# 直接运行您的服务器
python cursor_dev_tools.py
# 使用 MCP 客户端工具测试
npx @modelcontextprotocol/inspector cursor_dev_tools.py
安全最佳实践
将 FastMCP 服务器与 Cursor 结合使用时:
- 验证来源:仅使用来自受信开发者的 MCP 服务器
- 审查代码:在安装前审查服务器代码,特别是对于敏感项目
- 限制权限:使用具有最低所需权限的受限 API 密钥
- 环境变量:将密钥存储在环境变量中,切勿硬编码
- 本地开发:使用
stdio
传输进行敏感的开发工作
实际应用示例
开发工作流集成
# 增强型开发工具服务器
from fastmcp import FastMCP
import subprocess
import json
mcp = FastMCP("Advanced Dev Tools")
@mcp.tool()
def run_tests(test_pattern: str = "") -> str:
"""运行项目测试,可选择模式过滤。"""
cmd = ["python", "-m", "pytest"]
if test_pattern:
cmd.extend(["-k", test_pattern])
result = subprocess.run(cmd, capture_output=True, text=True)
return f"Test Results:\n{result.stdout}\n{result.stderr}"
@mcp.tool()
def format_code() -> str:
"""使用 black 格式化 Python 代码。"""
result = subprocess.run(
["black", ".", "--check", "--diff"],
capture_output=True,
text=True
)
if result.returncode == 0:
return "Code is already formatted correctly"
else:
return f"Code formatting suggestions:\n{result.stdout}"
@mcp.tool()
def check_dependencies() -> str:
"""检查过期的包依赖项。"""
result = subprocess.run(
["pip", "list", "--outdated", "--format", "json"],
capture_output=True,
text=True
)
try:
outdated = json.loads(result.stdout)
if outdated:
output = "Outdated packages:\n"
for pkg in outdated:
output += f"- {pkg['name']}: {pkg['version']} -> {pkg['latest_version']}\n"
return output
else:
return "All packages are up to date!"
except:
return "Error checking dependencies"
API 集成工具
@mcp.tool()
def fetch_api_docs(api_url: str) -> str:
"""从 OpenAPI/Swagger 端点获取 API 文档。"""
import requests
try:
response = requests.get(f"{api_url}/openapi.json", timeout=10)
if response.status_code == 200:
api_spec = response.json()
return f"API Documentation for {api_url}:\n{json.dumps(api_spec, indent=2)}"
else:
return f"Failed to fetch API docs: HTTP {response.status_code}"
except Exception as e:
return f"Error fetching API docs: {str(e)}"
后续步骤
既然您已将 FastMCP 集成到 Cursor 中:
- 探索可用工具:查看 MCP 工具目录以获取预构建的服务器
- 构建自定义工具:为您的开发工作流创建特定领域的工具
- 分享您的服务器:考虑为社区发布有用的 FastMCP 服务器
- 生产部署:为团队协作切换到 SSE 或 HTTP 传输
FastMCP 的易开发性与 Cursor 强大的 MCP 集成相结合,创造了无缝的 AI 辅助开发体验。开始构建能理解您特定代码库和工作流的工具吧!
故障排除常见问题
问:我的 FastMCP 服务器没有出现在 Cursor 的工具列表中
答:检查您的 mcp.json
语法是否正确,并重启 Cursor。使用 python your_server.py
验证服务器是否可以独立运行。
问:工具被调用但返回错误 答:检查 Cursor 输出面板中的 MCP 日志。常见问题包括缺少依赖项或工作目录不正确。
问:如何暂时禁用服务器?
答:前往设置(⌘⇧J
)→ 功能 → 模型上下文协议,在不删除配置的情况下关闭服务器。
问:我可以在远程 Cursor 安装中使用 FastMCP 吗? 答:对于远程开发,请考虑使用 SSE 或 HTTP 传输部署您的 FastMCP 服务器,而不是 stdio。
通过 FastMCP 和 Cursor,您现在拥有了一个强大的平台,可以创建理解您特定需求和代码库的 AI 辅助开发工具!