基于游标规则的Python MCP服务器开发
Python MCP服务器的全面开发框架,具有强制增量开发实践
  
🌟 这是什么
此存储库展示了 生产就绪开发框架 用于使用以下命令构建Python MCP(模型上下文协议)服务器 光标规则.该系统执行 增量开发实践 并为构建可靠、安全和可维护的MCP服务器提供了全面的指导方针。
🚀 主要特点
🎯 强制增量开发
- 永不 一次创建多个未经测试的文件
- 强制性TODO.md和TASKS.md管理
- 分步开发工作流程
- 内置优质闸门
🔧 综合工具
- 紫外线的 现代Python依赖管理的集成
- 类型检查 与mypy
- 代码格式化 黑色和isort
- 测试 使用pytest和pytest异步
- 预提交挂钩 质量保证
🛡️ 安全第一
- 文件路径验证和目录遍历保护
- SQL注入预防
- 输入净化和验证
- 全面的错误处理
📋 智能规则系统
- 自动附加规则 基于文件位置
- 手册规则 用于部署和故障排除
- 始终有效的规则 全球标准
- 情境感知开发指南
📁 存储库结构
python-mcp-development-framework/
├── .cursor/
│ └── rules/
│ ├── python_mcp_servers.mdc # Main development rules
│ ├── global-standards.mdc # Global standards
│ ├── file-server-rules.mdc # File server specific rules
│ ├── database-server-rules.mdc # Database server specific rules
│ ├── deployment-guide.mdc # Deployment procedures
│ └── troubleshooting.mdc # Troubleshooting guide
├── examples/
│ ├── file-server/ # File server examples
│ └── db-server/ # Database server examples
├── docs/ # Additional documentation
└── README.md # This file🎯 发展理念
增量方法
该框架围绕 严格的增量开发方法:
- 📋 计划优先 -使用特定任务更新TODO.md
- 🔨 实施一件事 -一次构建一个组件
- 🧪 立即测试 -在继续之前编写并运行测试
- ✅ 验证 -确保当前步骤完全正常工作
- 📝 文件 -更新进度和注释
为什么这很重要
- 减少bug 及早发现问题
- 提高代码质量 通过集中发展
- 增强可维护性 进展明显
- 提高可靠性 通过全面测试
- 加速调试 具有较小的变更集
🛠️ 规则系统是如何工作的
自动附加规则
规则会根据您的文件位置自动应用:
# Working in file server? File server rules auto-apply
servers/file-server/main.py → file-server-rules.mdc
# Working in database server? Database rules auto-apply
servers/db-server/main.py → database-server-rules.mdc手册规则
需要时在Cursor聊天中调用特定规则:
@deployment-guide # Get deployment procedures
@troubleshooting # Get debugging help始终有效的规则
核心开发标准适用于所有地方:
- 类型提示是必需的
- 需要错误处理
- 必须编写测试
- 文件已强制执行
🚀 快速开始
1.复制规则
# Copy the .cursor directory to your project
cp -r .cursor /path/to/your/mcp-project/2.初始化您的项目
# Initialize with UV
uv init your-mcp-project
cd your-mcp-project
# Add dependencies
uv add mcp fastapi uvicorn pydantic aiofiles
uv add --dev pytest pytest-asyncio black isort mypy ruff3.创建任务文件
# Create required task management files
touch TODO.md TASKS.md4.开始开发
这些规则将自动引导您完成:
- 首先创建最小实现
- 立即编写测试
- 遵循安全最佳实践
- 维护适当的文件
📊 例子
文件服务器示例
# examples/file-server/main.py
from typing import Dict, Any
import aiofiles
import logging
logger = logging.getLogger(__name__)
async def read_file_tool(request: Dict[str, Any]) -> Dict[str, Any]:
"""Handle file read requests with security validation"""
try:
file_path = request.get("file_path")
if not file_path:
raise ValueError("file_path is required")
# Security: Validate file path
safe_path = validate_file_path(file_path)
# Read file asynchronously
async with aiofiles.open(safe_path, 'r') as f:
content = await f.read()
return {
"status": "success",
"data": {"content": content, "path": str(safe_path)}
}
except Exception as e:
logger.error(f"File read error: {e}")
return {"status": "error", "error": str(e)}数据库服务器示例
# examples/db-server/main.py
from typing import Dict, Any
import aiosqlite
import logging
logger = logging.getLogger(__name__)
async def query_database_tool(request: Dict[str, Any]) -> Dict[str, Any]:
"""Handle database queries with SQL injection prevention"""
try:
table = request.get("table")
if not table:
raise ValueError("table is required")
# Security: Validate table name
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', table):
raise ValueError("Invalid table name")
# Execute query safely
async with aiosqlite.connect("database.db") as conn:
async with conn.execute(f"SELECT * FROM {table} LIMIT 100") as cursor:
rows = await cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
return {
"status": "success",
"data": {"rows": rows, "columns": columns}
}
except Exception as e:
logger.error(f"Database query error: {e}")
return {"status": "error", "error": str(e)}📚 文档
核心规则
操作指南
🎯 益处
对于开发者
- 更快的发展 有明确的指导方针
- 更少的bug 通过增量方法
- 更好的代码质量 有强制执行的标准
- 更容易调试 综合测井
对于团队
- 一致的代码风格 跨项目
- 缩短入职时间 对于新开发人员
- 更好的协作 有明确的做法
- 提高了可维护性 代码库
对于项目
- 更高的可靠性 通过全面测试
- 更好的安全性 具有内置保护功能
- 更容易部署 附有详细指南
- 更快的故障排除 有全面的文件
🔄 开发工作流程示例
# TODO.md
## Current Sprint: File Server Basic Operations
- [ ] Implement file read functionality
- [ ] Add file write functionality
- [ ] Implement directory listing
- [ ] Add file metadata retrieval
## Next Sprint
- [ ] Add file streaming for large files
- [ ] Implement file caching# TASKS.md
## Task: Implement File Read Functionality
**Status**: In Progress
**Priority**: High
### Subtasks:
1. [x] Create basic file read function
2. [x] Add path validation
3. [x] Write unit tests
4. [ ] Add error handling
5. [ ] Add logging
### Acceptance Criteria:
- [ ] Function can read text files
- [ ] Path validation prevents directory traversal
- [ ] All tests pass
- [ ] Proper error handling implemented
- [ ] Logging is comprehensive🤝 贡献
此演示展示了MCP服务器开发的最佳实践。请随意:
- 使用这些规则 在你自己的项目中
- 调整系统 根据您的特定需求
- 分享改进 通过问题和讨论
- 提供示例 适用于不同的用例
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🙏 致谢
- 为 光标AI IDE
- 设计用于 MCP(模型上下文协议)
- 由...驱动 紫外线的 用于Python包管理
______________________________________________________________________
记住成功发展的关键不是速度,而是一致性和质量。该框架通过有纪律的增量开发实践帮助您实现这两个目标。
🚀 准备好转变您的MCP服务器开发了吗?复制 .cursor 将目录添加到您的项目中,并开始更好、更快、更可靠地构建!
