模板uv mcp服务器
使用Python SDK构建MCP(模型上下文协议)服务器的可重用模板 uv 作为依赖管理器和运行时工具。
概述
快速开始
先决条件
- Python 3.11+
- 紫外线 安装
安装
- 克隆或使用此模板:
git clone https://github.com/ezemriv/template-uv-mcp-server.git
cd template-uv-mcp-server- 安装依赖项:
uv sync- 测试服务器:
uv run template-uv-mcp-server
# or
uv run python -m template_uv_mcp_server项目结构
template-uv-mcp-server/
├── .gitignore # Git ignore rules
├── .python-version # Python version specification (3.11)
├── LICENSE # License file
├── README.md # This file
├── PLAN.md # Implementation plan
├── pyproject.toml # Project configuration & dependencies
├── uv.lock # Lock file (generated by uv)
└── src/
└── template_uv_mcp_server/
├── __init__.py # Package initialization
├── __main__.py # Entry point for `python -m`
└── server.py # Main MCP server implementation核心文件
pyproject.toml
项目配置遵循PEP 621标准。定义:
- 项目元数据(名称、版本、描述)
- 依赖关系(支持CLI的mcp)
- 控制台脚本入口点
- 构建系统配置
src/template_uv_mcp_server/server.py
使用FastMCP实现主服务器。包括以下示例实现:
- 工具:
hello()-一个问候用户的简单工具 - 资源:
get_info()-提供模板信息的资源端点 - 提示:
greeting_prompt()-可重用的提示模板
src/template_uv_mcp_server/__init__.py
导出的包初始化 main 功能和版本。
src/template_uv_mcp_server/__main__.py
允许将服务器作为模块运行: python -m template_uv_mcp_server
用法
本地运行
# Using uv
uv run template-uv-mcp-server
# Or using Python directly
uv run python -m template_uv_mcp_server使用MCP开发工具进行测试
# Start the development server with MCP Inspector
uv run mcp dev src/template_uv_mcp_server/server.pyClaude桌面配置
选项1:使用 uv run (推荐)
编辑您的Claude Desktop配置文件并添加:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json 视窗: %APPDATA%\Claude\claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"template-server": {
"command": "/Users/youruser/.local/bin/uv",
"args": [
"--directory",
"/path/to/template-uv-mcp-server",
"run",
"template-uv-mcp-server"
]
}
}
}重要提示: 替换两条路径:
/Users/youruser/.local/bin/uv→ 通往您的完整路径uv二进制/path/to/template-uv-mcp-server→ 此项目的完整路径
找到你的 uv 路径:
which uv
# Example output: /Users/youruser/.local/bin/uv为什么是全程? Claude Desktop是一个GUI应用程序,它不继承shell的PATH环境变量。仅使用"command": "uv"将失败,因为Claude Desktop找不到二进制文件。始终使用返回的绝对路径which uv.
选项2:使用MCP CLI
uv run mcp install src/template_uv_mcp_server/server.py --name "Template Server"这将自动更新您的Claude Desktop配置。
定制
添加新工具
工具是用装饰的功能 @mcp.tool()他们应该:
- 清晰的文档字符串(用作Claude的工具描述)
- 参数和返回值的类型提示
- 可选的
Context高级功能参数
@mcp.tool()
def my_tool(param1: str, param2: int = 10) -> dict:
"""Description of what this tool does."""
return {"result": f"{param1} processed with {param2}"}添加新资源
资源是用以下元素装饰的数据端点 @mcp.resource()。他们可以使用动态资源的URI模板:
@mcp.resource("myapp://document/{id}")
def get_document(id: str) -> str:
"""Retrieve a document by ID."""
return f"Content of document {id}"添加新提示
提示是可重复使用的模板,装饰有 @mcp.prompt():
@mcp.prompt()
def code_review_prompt(code: str) -> str:
"""Generate a code review prompt."""
return f"Please review this code:\n\n{code}"添加依赖关系
# Add a regular dependency
uv add requests
# Add a dev dependency
uv add --dev pytest开发流程
初始设置
uv sync --dev运行测试
uv run pytest类型检查
uv run mypy src/代码检查
uv run ruff check src/代码格式化
uv run ruff format src/高级功能
使用上下文进行日志记录
from mcp.server.fastmcp import Context, FastMCP
@mcp.tool()
async def advanced_tool(param: str, ctx: Context) -> str:
"""Tool that uses logging context."""
await ctx.info(f"Processing parameter: {param}")
try:
result = do_something(param)
return result
except Exception as e:
await ctx.error(f"Error occurred: {e}")
raisePydantic结构化输出
from pydantic import BaseModel
class AnalysisResult(BaseModel):
status: str
score: float
details: str
@mcp.tool()
def analyze_data(data: str) -> AnalysisResult:
"""Analyze data and return structured result."""
return AnalysisResult(
status="success",
score=0.95,
details="Analysis complete"
)寿命管理
对于需要设置/拆卸的复杂服务器:
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[dict]:
# Setup phase
db = await Database.connect()
cache = {}
try:
yield {"db": db, "cache": cache}
finally:
# Cleanup phase
await db.disconnect()
mcp = FastMCP("My App", lifespan=app_lifespan)故障排除
Python版本问题
此模板需要Python 3.11+。检查您的版本:
python --version未找到紫外线
安装紫外线:
curl -LsSf https://astral.sh/uv/install.sh | sh运行时导入错误
确保安装了依赖项:
uv sync克劳德桌面找不到服务器
验证中的路径 claude_desktop_config.json 正确,服务器启动时没有错误:
uv run template-uv-mcp-server资源
许可证
此模板根据MIT许可证获得许可。有关详细信息,请参阅LICENSE文件。
贡献
欢迎投稿!请随时提交pull请求或打开bug和功能请求的问题。
