做什么
在 Python 中用 FastMCP 构建 MCP 服务器. 定义工具/ 资源/ 提示, 构建服务器, 本地测试, 部署到 FastMCP Cloud 或 Docker
技能库 智客分类:运维与云 mcp-builder
在Python中用FastMCP来构建MCP服务器. 定义工具/资源/提示,构建服务器,在本地测试,部署到FastMCP Cloud或Docker. 每当用户提及建立 MCP 服务器,向 LLMs, FastMCP 显示工具, 建立 Claude 集成, 或排除 FastMCP 模块级服务器出错, 存储, 寿命, 中间软件, OAuth, 或部署错误时使用 .
官方网址:skills.sh
先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。
在 Python 中用 FastMCP 构建 MCP 服务器. 定义工具/ 资源/ 提示, 构建服务器, 本地测试, 部署到 FastMCP Cloud 或 Docker
用户曾经提到建立 MCP 服务器, 向 LLMS 、 FastMCP 、 建立 Claude 集成, 或 排除 FastMCP 模块级服务器、 存储、 寿命、 中间软件、 OAuth 或 部署错误
按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:MCP Builder、Workflow、Step 1: Define What to Expose、Step 2: Scaffold the Server、MUST be at module level for FastMCP Cloud、Step 3: Add Companion CLI Scripts (Optional)。 其中含规范建议的小节:分步指令。
文件分析:除 SKILL.md 外,正文引用了 assets/SCRIPTS-TEMPLATE.md、assets/script-template.ts、references/integration-patterns.md、assets/basic-server.py、assets/self-contained-server.py、assets/tools-examples.py,属于带资源的技能包,这些文件按需再读。
Build MCP servers in Python with FastMCP. Define tools / resources / prompts, build the server, test locally, deploy to FastMCP Cloud or Docker. Use whenever the user mentions building an MCP server, exposing tools to LLMs, FastMCP, building a Claude integration, or troubleshooting FastMCP module-level server, storage, lifespan, middleware, OAuth, or deployment errors.
MCP BuilderWorkflowStep 1: Define What to ExposeStep 2: Scaffold the ServerMUST be at module level for FastMCP CloudStep 3: Add Companion CLI Scripts (Optional)Step 4: Test LocallyOpens inspector at http://localhost:5173Hot reload, detailed logging, tool/resource inspectionStep 5: Pre-Deploy ChecklistStep 6: DeployVisit https://fastmcp.cloud, connect repo, add env vars, deploy
兼容:claude-code-only
来源分类:skills.sh agent-skill
namemcp-builderdescriptioncompatibilityassets/SCRIPTS-TEMPLATE.mdassets/script-template.tsreferences/integration-patterns.mdassets/basic-server.pyassets/self-contained-server.pyassets/tools-examples.pyassets/resources-examples.pyassets/prompts-examples.pyassets/client-example.py以下路径提取自原文;文件是否齐全请以来源仓库中的完整目录为准。
具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗
先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。
该技能引用了附属文件,请从来源获取完整目录;仅复制 SKILL.md 可能缺少依赖。
复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。
把 Agent Skill「mcp-builder」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-90ea36df50b8c469-Mcp-Builder.html 请存为 .cursor/skills/mcp-builder/SKILL.md 或 .claude/skills/mcp-builder/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。 该技能还带 scripts/、references/、assets/ 等文件,请从 https://github.com/jezweb/claude-skills 取完整目录,不要只建一个 SKILL.md。
需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。
npx skills add 'https://github.com/jezweb/claude-skills' --list
npx skills add 'https://github.com/jezweb/claude-skills' --skill 'mcp-builder'
CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。
Build a working MCP server from a description of the tools you need. Produces a deployable Python server using FastMCP.
Ask what the server needs to provide:
A brief like "MCP server for querying our customer database" is enough.
pip install fastmcp
Create the server file. The server instance MUST be at module level:
from fastmcp import FastMCP
# MUST be at module level for FastMCP Cloud
mcp = FastMCP("My Server")
@mcp.tool()
async def search_customers(query: str) -> str:
"""Search customers by name or email."""
# Implementation here
return f"Found customers matching: {query}"
@mcp.resource("customers://{customer_id}")
async def get_customer(customer_id: str) -> str:
"""Get customer details by ID."""
return f"Customer {customer_id} details"
if __name__ == "__main__":
mcp.run()
For Claude Code terminal use, add scripts alongside the MCP server:
my-mcp-server/
├── src/index.ts # MCP server (for Claude.ai)
├── scripts/
│ ├── search.ts # CLI version of search tool
│ └── _shared.ts # Shared auth/config
├── SCRIPTS.md # Documents available scripts
└── package.json
CLI scripts provide file I/O, batch processing, and richer output that MCP can't.
See assets/SCRIPTS-TEMPLATE.md and assets/script-template.ts for TypeScript templates.
Quick test -- run directly:
python server.py
Dev mode with inspector UI (recommended):
fastmcp dev server.py
# Opens inspector at http://localhost:5173
# Hot reload, detailed logging, tool/resource inspection
HTTP mode for remote clients:
python server.py --transport http --port 8000
Automated test script using FastMCP Client:
import asyncio
from fastmcp import Client
async def test_server(server_path):
async with Client(server_path) as client:
# List everything
tools = await client.list_tools()
resources = await client.list_resources()
prompts = await client.list_prompts()
print(f"Tools: {[t.name for t in tools]}")
print(f"Resources: {[r.uri for r in resources]}")
print(f"Prompts: {[p.name for p in prompts]}")
# Call first tool
if tools:
result = await client.call_tool(tools[0].name, {})
print(f"Tool result: {result}")
# Read first resource
if resources:
data = await client.read_resource(resources[0].uri)
print(f"Resource data: {data}")
asyncio.run(test_server("server.py"))
Run these checks before deploying. All required checks must pass.
Required (will cause deploy failure):
python3 -m py_compile server.pygrep -q "^mcp = FastMCP\|^server = FastMCP\|^app = FastMCP" server.py
requirements.txt exists with PyPI packages only (no git+, -e, .whl, .tar.gz)api_key = "..." patterns excluding os.getenv/os.environ)Advisory (warnings):
fastmcp listed in requirements.txt.gitignore includes .envtimeout 5 fastmcp inspect server.pyFastMCP Cloud (simplest):
git add . && git commit -m "Ready for deployment"
git push -u origin main
# Visit https://fastmcp.cloud, connect repo, add env vars, deploy
# URL: https://your-project.fastmcp.app/mcp
Cloud requirements:
mcp, server, or apprequirements.txtDocker (self-hosted):
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "server.py", "--transport", "http", "--port", "8000"]
Cloudflare Workers (edge):
Build it in TypeScript with Cloudflare's agents SDK (McpAgent); Cloudflare's remote MCP server docs carry the current template.
FastMCP Cloud requires the server instance at module level:
# CORRECT
mcp = FastMCP("My Server")
@mcp.tool()
def my_tool(): ...
# WRONG -- Cloud can't find the server
def create_server():
mcp = FastMCP("My Server")
return mcp
# FIX for factory pattern -- export at module level
def create_server() -> FastMCP:
mcp = FastMCP("server")
return mcp
mcp = create_server()
FastMCP uses type annotations to generate tool schemas:
@mcp.tool()
async def search(
query: str, # Required parameter
limit: int = 10, # Optional with default
tags: list[str] = [] # Complex types supported
) -> str:
"""Docstring becomes the tool description."""
...
Return errors as strings, don't raise exceptions:
@mcp.tool()
async def get_data(id: str) -> str:
try:
result = await fetch_data(id)
return json.dumps(result)
except NotFoundError:
return f"Error: No data found for ID {id}"
import os
from fastmcp import FastMCP
mcp = FastMCP("production-server")
API_KEY = os.getenv("API_KEY")
@mcp.tool()
async def production_tool(data: str) -> dict:
if not API_KEY:
return {"error": "API_KEY not configured"}
return {"status": "success", "data": data}
if __name__ == "__main__":
mcp.run()
These are the errors you will hit. Fix them before deploying.
| Error | Cause | Fix |
|-------|-------|-----|
| RuntimeError: No server object found at module level | Server inside a function | Export mcp = FastMCP(...) at module level |
| RuntimeError: no running event loop | Missing async/await | Use async def for async operations |
| TypeError: missing required argument 'context' | Context not type-hinted | Add context: Context with type hint |
| ValueError: Invalid resource URI | Missing URI scheme | Use data://, file://, info://, api:// |
| Resource template parameter mismatch | Name mismatch | user://{user_id} needs def get_user(user_id: str) |
| Pydantic validation error | Wrong type hints | Ensure hints match actual data types |
| Transport mismatch | Client/server protocol differ | Match both to stdio or both to http |
| Import errors with editable package | Package not installed | pip install -e . or add to PYTHONPATH |
| DeprecationWarning: mcp.settings | Old API | Use os.getenv() instead |
| Port already in use | Stale process | lsof -ti:8000 \| xargs kill -9 |
| Schema generation failure | Non-JSON types | Use JSON-compatible types (no NumPy arrays) |
| JSON serialization error | datetime/bytes in response | Convert to .isoformat() or string |
| Circular import | Factory in __init__.py | Use direct imports, avoid factory pattern |
| Python 3.12+ datetime warning | datetime.utcnow() deprecated | Use datetime.now(timezone.utc) |
| Import-time execution | Async resource at module level | Use lazy init pattern |
Keep all utilities in one file to avoid circular imports:
from fastmcp import FastMCP
import os
mcp = FastMCP("my-server")
# Config
class Config:
API_KEY = os.getenv("API_KEY", "")
BASE_URL = os.getenv("BASE_URL", "https://api.example.com")
# Helpers
def format_success(data): return {"status": "success", "data": data}
def format_error(msg): return {"status": "error", "message": msg}
@mcp.tool()
async def my_tool(query: str) -> dict:
if not Config.API_KEY:
return format_error("API_KEY not configured")
return format_success({"query": query})
Don't create async resources at module level. Initialise on first use:
_db = None
async def get_db():
global _db
if _db is None:
_db = await create_connection(Config.DB_URL)
return _db
@mcp.resource("health://status")
async def health_check() -> dict:
return {
"status": "healthy",
"version": "1.0.0",
"checks": {
"api": "connected",
"database": "connected"
}
}
import httpx
_client = None
def get_client() -> httpx.AsyncClient:
global _client
if _client is None:
_client = httpx.AsyncClient(
base_url=Config.BASE_URL,
headers={"Authorization": f"Bearer {Config.API_KEY}"},
limits=httpx.Limits(max_connections=20, max_keepalive_connections=5),
timeout=30.0
)
return _client
async def retry_with_backoff(func, max_retries=3, initial_delay=1.0):
for attempt in range(max_retries):
try:
return await func()
except Exception as e:
if attempt == max_retries - 1:
raise
delay = initial_delay * (2 ** attempt)
await asyncio.sleep(delay)
from fastmcp import Context
@mcp.tool()
async def tool_with_context(param: str, context: Context) -> dict:
# Context parameter MUST have type hint
pass
@mcp.tool()
async def long_task(items: list[str], context: Context) -> str:
for i, item in enumerate(items):
await context.report_progress(i + 1, len(items), f"Processing {item}")
await process(item)
return "Done"
@mcp.tool()
async def summarise(text: str, context: Context) -> str:
result = await context.request_sampling(
messages=[{"role": "user", "content": f"Summarise: {text}"}],
max_tokens=200
)
return result
fastmcp dev server.py # Dev mode with inspector UI
fastmcp run server.py # Run (stdio)
fastmcp run server.py --transport http --port 8000 # Run (HTTP)
fastmcp inspect server.py # Inspect without running
fastmcp install server.py # Install to Claude Desktop
fastmcp deploy server.py --name my-server # Deploy to Cloud
Environment variables: FASTMCP_LOG_LEVEL (DEBUG/INFO/WARNING/ERROR), FASTMCP_ENV (development/staging/production).
For specific integration approaches, see references/integration-patterns.md:
httpx.AsyncClient with reusable clientFastMCP.from_openapi(spec, client, route_maps=[...])FastMCP.from_fastapi(app)assets/basic-server.py -- Minimal FastMCP server templateassets/self-contained-server.py -- Server with storage and middlewareassets/tools-examples.py -- Tool patterns and type annotationsassets/resources-examples.py -- Resource URI patternsassets/prompts-examples.py -- Prompt template patternsassets/client-example.py -- MCP client usageassets/SCRIPTS-TEMPLATE.md -- CLI companion docs templateassets/script-template.ts -- TypeScript CLI script template运维与云
用于容器管理,图像操作,调试的基本道克命令和工作流程.
运维与云
从开放的代理技能生态系统中发现并安装技能. 使用时:(1)用户问"我如何做X",X可能拥有现有技能,(2)用户说"为X找到技能"或"是否为X有技能",(3)用户问"你能否做X",X是专门能力,(4)用户想扩展代理能力,(5)用户想搜索工具,模板,或工作流程,(6)用户提到他们希望…
运维与云
构建,部署,评价,优化,微调,管理微软创始代理,模型,资源最终结束. 用法:铸造、azd ai代理、azd 提供/部署、托管代理脚手架/开发/运行/部署/拖放、即时代理创建、创建代理、更新代理、添加代理工具、援引代理、代理.yaml、评估代理、批量活化、连续活化、持续监测、代理C…
运维与云
执行已有.azure/部署计划.md和基础设施文件的ALREADY-PREPARED应用程序的Azure部署。 当用户向 CREATE 请求新应用程序时, 请不要使用此技能 。 这种技能运行了 azd上行, azd 部署, trarraform 应用, 和 az 部署命令带有内置…