python-mcp-server-generator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGenerate Python MCP Server
生成Python MCP服务器
Create a complete Model Context Protocol (MCP) server in Python with the following specifications:
创建一个符合以下规范的完整Model Context Protocol (MCP) Python服务器:
Requirements
需求
- Project Structure: Create a new Python project with proper structure using uv
- Dependencies: Include mcp[cli] package with uv
- Transport Type: Choose between stdio (for local) or streamable-http (for remote)
- Tools: Create at least one useful tool with proper type hints
- Error Handling: Include comprehensive error handling and validation
- 项目结构:使用uv创建一个结构规范的新Python项目
- 依赖项:通过uv引入mcp[cli]包
- 传输类型:在stdio(本地使用)或streamable-http(远程使用)中选择其一
- 工具:创建至少一个带有正确类型提示的实用工具
- 错误处理:包含全面的错误处理与验证机制
Implementation Details
实现细节
Project Setup
项目搭建
- Initialize with
uv init project-name - Add MCP SDK:
uv add "mcp[cli]" - Create main server file (e.g., )
server.py - Add for Python projects
.gitignore - Configure for direct execution with
if __name__ == "__main__"
- 使用初始化项目
uv init project-name - 添加MCP SDK:
uv add "mcp[cli]" - 创建主服务器文件(例如:)
server.py - 添加Python项目专用的文件
.gitignore - 通过配置直接执行逻辑
if __name__ == "__main__"
Server Configuration
服务器配置
- Use class from
FastMCPmcp.server.fastmcp - Set server name and optional instructions
- Choose transport: stdio (default) or streamable-http
- For HTTP: optionally configure host, port, and stateless mode
- 从导入
mcp.server.fastmcp类FastMCP - 设置服务器名称及可选说明
- 选择传输方式:stdio(默认)或streamable-http
- 若使用HTTP:可选择性配置主机、端口和无状态模式
Tool Implementation
工具实现
- Use decorator on functions
@mcp.tool() - Always include type hints - they generate schemas automatically
- Write clear docstrings - they become tool descriptions
- Use Pydantic models or TypedDicts for structured outputs
- Support async operations for I/O-bound tasks
- Include proper error handling
- 在函数上使用装饰器
@mcp.tool() - 务必包含类型提示——它们会自动生成模式
- 编写清晰的文档字符串——它们将成为工具描述
- 使用Pydantic模型或TypedDicts实现结构化输出
- 为I/O密集型任务支持异步操作
- 包含完善的错误处理
Resource/Prompt Setup (Optional)
资源/提示配置(可选)
- Add resources with decorator
@mcp.resource() - Use URI templates for dynamic resources:
"resource://{param}" - Add prompts with decorator
@mcp.prompt() - Return strings or Message lists from prompts
- 使用装饰器添加资源
@mcp.resource() - 为动态资源使用URI模板:
"resource://{param}" - 使用装饰器添加提示
@mcp.prompt() - 从提示中返回字符串或Message列表
Code Quality
代码质量
- Use type hints for all function parameters and returns
- Write docstrings for tools, resources, and prompts
- Follow PEP 8 style guidelines
- Use async/await for asynchronous operations
- Implement context managers for resource cleanup
- Add inline comments for complex logic
- 为所有函数参数和返回值添加类型提示
- 为工具、资源和提示编写文档字符串
- 遵循PEP 8风格指南
- 使用async/await处理异步操作
- 为资源清理实现上下文管理器
- 为复杂逻辑添加行内注释
Example Tool Types to Consider
可考虑的工具类型示例
- Data processing and transformation
- File system operations (read, analyze, search)
- External API integrations
- Database queries
- Text analysis or generation (with sampling)
- System information retrieval
- Math or scientific calculations
- 数据处理与转换
- 文件系统操作(读取、分析、搜索)
- 外部API集成
- 数据库查询
- 文本分析或生成(带采样功能)
- 系统信息检索
- 数学或科学计算
Configuration Options
配置选项
-
For stdio Servers:
- Simple direct execution
- Test with
uv run mcp dev server.py - Install to Claude:
uv run mcp install server.py
-
For HTTP Servers:
- Port configuration via environment variables
- Stateless mode for scalability:
stateless_http=True - JSON response mode:
json_response=True - CORS configuration for browser clients
- Mounting to existing ASGI servers (Starlette/FastAPI)
-
针对stdio服务器:
- 简单直接的执行方式
- 使用进行测试
uv run mcp dev server.py - 安装到Claude:
uv run mcp install server.py
-
针对HTTP服务器:
- 通过环境变量配置端口
- 启用无状态模式以实现可扩展性:
stateless_http=True - JSON响应模式:
json_response=True - 为浏览器客户端配置CORS
- 挂载到现有ASGI服务器(Starlette/FastAPI)
Testing Guidance
测试指南
- Explain how to run the server:
- stdio: or
python server.pyuv run server.py - HTTP: then connect to
python server.pyhttp://localhost:PORT/mcp
- stdio:
- Test with MCP Inspector:
uv run mcp dev server.py - Install to Claude Desktop:
uv run mcp install server.py - Include example tool invocations
- Add troubleshooting tips
- 说明如何运行服务器:
- stdio:或
python server.pyuv run server.py - HTTP:执行后连接到
python server.pyhttp://localhost:PORT/mcp
- stdio:
- 使用MCP Inspector测试:
uv run mcp dev server.py - 安装到Claude桌面端:
uv run mcp install server.py - 包含工具调用示例
- 添加故障排除技巧
Additional Features to Consider
可考虑的附加功能
- Context usage for logging, progress, and notifications
- LLM sampling for AI-powered tools
- User input elicitation for interactive workflows
- Lifespan management for shared resources (databases, connections)
- Structured output with Pydantic models
- Icons for UI display
- Image handling with Image class
- Completion support for better UX
- 用于日志记录、进度跟踪和通知的上下文使用
- 用于AI驱动工具的LLM采样
- 用于交互式工作流的用户输入引导
- 共享资源(数据库、连接)的生命周期管理
- 使用Pydantic模型实现结构化输出
- 用于UI显示的图标
- 使用Image类处理图片
- 为提升UX的自动补全支持
Best Practices
最佳实践
- Use type hints everywhere - they're not optional
- Return structured data when possible
- Log to stderr (or use Context logging) to avoid stdout pollution
- Clean up resources properly
- Validate inputs early
- Provide clear error messages
- Test tools independently before LLM integration
Generate a complete, production-ready MCP server with type safety, proper error handling, and comprehensive documentation.
- 处处使用类型提示——这不是可选的
- 尽可能返回结构化数据
- 记录到stderr(或使用Context日志)以避免污染stdout
- 正确清理资源
- 尽早验证输入
- 提供清晰的错误消息
- 在与LLM集成前独立测试工具
生成一个具备类型安全、完善错误处理和全面文档的生产级MCP服务器。