mcp-creator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Creator — FastMCP v3
MCP 创建器 — FastMCP v3
Build production-ready MCP servers with FastMCP v3 (3.0.0rc2). This skill guides through research, scaffolding, implementation, testing, and deployment. All output follows this repo's conventions: directory, config, workspace member, imperative voice, kebab-case naming.
mcp/<name>/fastmcp.jsonuvTarget: FastMCP v3 rc2 — Provider/Transform architecture, 14 built-in middleware, OAuth 2.1, server composition, component versioning, structured output, background tasks, elicitation, sampling.
Input: — the service, API, or capability to wrap as an MCP server.
$ARGUMENTS使用FastMCP v3(3.0.0rc2)构建生产可用的MCP服务器。本指南将指导你完成调研、脚手架搭建、功能实现、测试和部署的全流程。所有输出需遵循本仓库的约定:目录结构、配置文件、工作区成员、命令式语气、短横线分隔命名法(kebab-case)。
mcp/<name>/fastmcp.jsonuv目标版本: FastMCP v3 rc2 — 采用Provider/Transform架构、内置14种中间件、支持OAuth 2.1、服务器组合、组件版本控制、结构化输出、后台任务、启发式交互、采样功能。
输入: — 要封装为MCP服务器的服务、API或功能。
$ARGUMENTSDispatch
任务分发
Route to the appropriate mode:
$ARGUMENTS| $ARGUMENTS pattern | Mode | Start at |
|---|---|---|
| Service/API name (e.g., "GitHub", "Stripe") | New server | Phase 1 |
Path to existing server (e.g., | Extend | Phase 3 |
| OpenAPI spec URL or file path | Convert OpenAPI | Phase 2 (scaffold) then load |
| FastAPI app to convert | Convert FastAPI | Phase 2 (scaffold) then load |
| Error message or "debug" + description | Debug | Load |
| "learn" or conceptual question | Learn | Load relevant reference file, explain |
| Empty | Gallery / help overview | Show available modes and example invocations |
根据的匹配模式路由到对应工作模式:
$ARGUMENTS| $ARGUMENTS 模式 | 模式 | 起始阶段 |
|---|---|---|
| 服务/API名称(例如:"GitHub", "Stripe") | 新建服务器 | 阶段1 |
现有服务器路径(例如: | 扩展服务器 | 阶段3 |
| OpenAPI规范URL或文件路径 | 转换OpenAPI | 阶段2(脚手架),然后参考 |
| 待转换的FastAPI应用 | 转换FastAPI | 阶段2(脚手架),然后参考 |
| 错误信息或包含"debug"的描述 | 调试 | 加载 |
| "learn"或概念性问题 | 学习 | 加载相关参考文档并进行解释 |
| 空输入 | 示例库/帮助概览 | 展示可用模式及调用示例 |
Consult Live Documentation
查阅实时文档
Before implementation, fetch current FastMCP v3 docs. Bundled references capture rc2 — live docs may be newer.
- Context7 — for "fastmcp", then
resolve-library-idfor the topic.query-docs - WebFetch — — comprehensive LLM-optimized docs.
https://gofastmcp.com/llms-full.txt - WebSearch fallback — for specific topics.
site:gofastmcp.com <topic>
If live docs contradict bundled references, live docs win. Always fetch live docs first — API details shift between rc2 and stable.
在开始实现前,请获取最新的FastMCP v3文档。内置参考文档基于rc2版本,而实时文档可能更新。
- Context7 — 调用获取"fastmcp"的库ID,再通过
resolve-library-id查询相关主题。query-docs - WebFetch — 访问— 这是为LLM优化的完整文档。
https://gofastmcp.com/llms-full.txt - WebSearch 备选方案 — 搜索获取特定主题内容。
site:gofastmcp.com <topic>
如果实时文档与内置参考文档冲突,以实时文档为准。请始终优先获取实时文档 — rc2到稳定版之间API细节可能会有变动。
Phase 1: Research & Plan
阶段1:调研与规划
Goal: Understand the target service and design the MCP server's tool/resource/prompt inventory.
Load: (naming, descriptions, parameter design, 8 tool patterns)
references/tool-design.md目标: 了解目标服务并设计MCP服务器的工具/资源/提示词清单。
参考文档: (命名规则、描述规范、参数设计、8种工具模式)
references/tool-design.md1.1 Understand the Target
1.1 了解目标服务
- Read any documentation, SDK, or API reference for the target service.
- Identify the core operations users need (CRUD, search, status, config).
- Note authentication requirements (API keys, OAuth, tokens).
- Check for existing MCP servers for this service — avoid duplicating work.
- 阅读目标服务的任何文档、SDK或API参考。
- 识别用户所需的核心操作(CRUD、搜索、状态查询、配置)。
- 记录认证要求(API密钥、OAuth、令牌)。
- 检查是否已存在针对该服务的MCP服务器 — 避免重复工作。
1.2 Architecture Checklist
1.2 架构检查清单
Answer before proceeding:
- Auth needed? (API key → env var, OAuth → HTTP transport, none → stdio)
- Transport? (stdio for local, Streamable HTTP for remote/multi-client)
- Background tasks? (long-running operations → , requires
task=True)fastmcp[tasks] - OpenAPI spec available? (→ or
OpenAPIProvider)FastMCP.from_openapi() - Multiple domains? (→ composed servers with + namespaces)
mount()
在进入下一阶段前,请确认以下事项:
- 是否需要认证?(API密钥→环境变量,OAuth→HTTP传输,无认证→stdio)
- 选择哪种传输方式?(本地使用stdio,远程/多客户端使用Streamable HTTP)
- 是否需要后台任务?(长时间运行的操作→设置,需安装
task=True)fastmcp[tasks] - 是否有可用的OpenAPI规范?(→使用或
OpenAPIProvider)FastMCP.from_openapi() - 是否涉及多个业务域?(→使用+命名空间实现服务器组合)
mount()
1.3 Design Tool Inventory
1.3 设计工具清单
Plan 5-15 tools per server. For each tool, define:
| Field | Requirement |
|---|---|
| Name | |
| Description | 3-5 sentences: WHAT, WHEN to use, WHEN NOT, WHAT it returns |
| Parameters | Each with type, description, constraints via |
| Annotations | |
| Error cases | What |
每个服务器规划5-15个工具。针对每个工具,需定义:
| 字段 | 要求 |
|---|---|
| 名称 | 使用 |
| 描述 | 3-5句话:说明功能、适用场景、不适用场景、返回结果 |
| 参数 | 每个参数需使用 |
| 注解 | 包含 |
| 错误场景 | 定义预期失败时需抛出的 |
1.4 Design Resources and Prompts
1.4 设计资源与提示词
- Resources for static/slow-changing data (config, schemas, status). URI-addressed.
- Prompts for reusable message templates that guide LLM behavior.
- See §6-7 for URI patterns and prompt design.
references/fastmcp-v3-api.md
- 资源(Resources):用于静态/慢变更数据(配置、 schema、状态),通过URI访问。
- 提示词(Prompts):用于指导LLM行为的可复用消息模板。
- 参考第6-7节了解URI模式和提示词设计规范。
references/fastmcp-v3-api.md
1.5 Plan Architecture
1.5 规划架构
Decide on composition strategy:
- Single server — Most cases. One instance with all tools.
FastMCP - Composed servers — Large APIs. Domain servers mounted via with namespaces.
mount() - Provider-based — Dynamic tool registration. or custom
FileSystemProvider.Provider - OpenAPI conversion — Auto-generate tools from OpenAPI spec. or
OpenAPIProvider.FastMCP.from_openapi()
See for patterns.
references/server-composition.md确定服务器组合策略:
- 单服务器:大多数场景适用。一个实例包含所有工具。
FastMCP - 组合服务器:适用于大型API。将业务域服务器通过挂载并添加命名空间。
mount() - 基于Provider:动态注册工具。使用或自定义
FileSystemProvider。Provider - OpenAPI转换:从OpenAPI规范自动生成工具。使用或
OpenAPIProvider。FastMCP.from_openapi()
参考了解具体模式。
references/server-composition.md1.6 Deliverable
1.6 交付物
Produce a tool/resource/prompt inventory table before proceeding:
markdown
| Component | Type | Name | Description (brief) |
|-----------|------|------|---------------------|
| Tool | tool | search_issues | Search GitHub issues by query |
| Resource | resource | config://settings | Current server configuration |
| Prompt | prompt | summarize_pr | Summarize a pull request for review |进入下一阶段前,需产出工具/资源/提示词清单表:
markdown
| 组件 | 类型 | 名称 | 简要描述 |
|-----------|------|------|---------------------|
| 工具 | tool | search_issues | 按查询条件搜索GitHub议题 |
| 资源 | resource | config://settings | 当前服务器配置 |
| 提示词 | prompt | summarize_pr | 为代码评审总结Pull Request |Phase 2: Scaffold
阶段2:搭建脚手架
Goal: Create the project directory, tests, and configure dependencies.
目标: 创建项目目录、测试文件并配置依赖。
2.1 Create Project Structure
2.1 创建项目结构
Run to scaffold:
wagents new mcp <name>mcp/<name>/
├── server.py # FastMCP entry point
├── pyproject.toml # uv project config
├── fastmcp.json # FastMCP CLI config
└── tests/
├── conftest.py # Client fixture, mock Context
└── test_server.py # Automated test suiteCustomize the scaffold:
- Set server name in :
server.py.mcp = FastMCP("name") - Set package name in :
pyproject.toml.name = "mcp-<name>" - Update description in .
pyproject.toml - Add service-specific dependencies to both and
pyproject.toml.fastmcp.json
运行生成脚手架:
wagents new mcp <name>mcp/<name>/
├── server.py # FastMCP入口文件
├── pyproject.toml # uv项目配置
├── fastmcp.json # FastMCP CLI配置
└── tests/
├── conftest.py # 客户端夹具、模拟Context
└── test_server.py # 自动化测试套件自定义脚手架:
- 在中设置服务器名称:
server.py。mcp = FastMCP("name") - 在中设置包名称:
pyproject.toml。name = "mcp-<name>" - 更新中的描述信息。
pyproject.toml - 在和
pyproject.toml中添加服务特定的依赖。fastmcp.json
2.2 Add Test Configuration
2.2 添加测试配置
Add to :
pyproject.tomltoml
[tool.pytest.ini_options]
asyncio_mode = "auto"
[dependency-groups]
dev = ["pytest>=8", "pytest-asyncio>=0.25"]Create — see §4 for the complete template.
tests/conftest.pyreferences/testing.md在中添加:
pyproject.tomltoml
[tool.pytest.ini_options]
asyncio_mode = "auto"
[dependency-groups]
dev = ["pytest>=8", "pytest-asyncio>=0.25"]创建 — 参考第4节获取完整模板。
tests/conftest.pyreferences/testing.md2.3 Configure and Verify
2.3 配置与验证
- Ensure root has
pyproject.toml.[tool.uv.workspace] members = ["mcp/*"] - Run to install dependencies.
cd mcp/<name> && uv sync - Verify: .
uv run python -c "from server import mcp; print(mcp.name)"
Note: validates skills/agents only, NOT MCP servers. Use the import check above for MCP server validation.
wagents validate- 确保根目录的包含
pyproject.toml。[tool.uv.workspace] members = ["mcp/*"] - 运行安装依赖。
cd mcp/<name> && uv sync - 验证安装:。
uv run python -c "from server import mcp; print(mcp.name)"
注意:仅验证技能/Agent,不验证MCP服务器。请使用上述导入检查验证MCP服务器。
wagents validatePhase 3: Implement
阶段3:功能实现
Goal: Build all tools, resources, and prompts from the Phase 1 inventory.
Load: (full API surface), (patterns)
references/fastmcp-v3-api.mdreferences/tool-design.md目标: 实现阶段1清单中的所有工具、资源和提示词。
参考文档: (完整API接口)、(工具模式)
references/fastmcp-v3-api.mdreferences/tool-design.md3.1 Server Setup
3.1 服务器初始化
python
from fastmcp import FastMCP, Context
mcp = FastMCP(
"server-name",
instructions="Description of what this server provides and when to use it.",
)For shared resources (HTTP clients, DB connections), add a composable lifespan:
python
from fastmcp.server.lifespan import lifespan
@lifespan
async def http_lifespan(server):
import httpx
async with httpx.AsyncClient() as client:
yield {"http": client}
mcp = FastMCP("server-name", lifespan=http_lifespan)python
from fastmcp import FastMCP, Context
mcp = FastMCP(
"server-name",
instructions="本服务器提供的功能及适用场景描述。",
)对于共享资源(HTTP客户端、数据库连接),添加可组合的生命周期管理:
python
from fastmcp.server.lifespan import lifespan
@lifespan
async def http_lifespan(server):
import httpx
async with httpx.AsyncClient() as client:
yield {"http": client}
mcp = FastMCP("server-name", lifespan=http_lifespan)Access in tools: ctx.lifespan_context["http"]
在工具中访问:ctx.lifespan_context["http"]
Combine lifespans with `|`: `mcp = FastMCP("name", lifespan=db_lifespan | cache_lifespan)`
使用`|`组合多个生命周期管理:`mcp = FastMCP("name", lifespan=db_lifespan | cache_lifespan)`3.2 Implement Tools
3.2 实现工具
For each tool in the inventory, follow this pattern:
python
from typing import Annotated
from pydantic import Field
from fastmcp import Context
from fastmcp.exceptions import ToolError
@mcp.tool(
annotations={
"readOnlyHint": True,
"openWorldHint": True,
},
)
async def search_items(
query: Annotated[str, Field(description="Search term to find items.", min_length=1)],
limit: Annotated[int, Field(description="Max results to return.", ge=1, le=100)] = 10,
ctx: Context | None = None,
) -> dict:
"""Search for items matching a query.
Use this tool when you need to find items by keyword. Returns a list of
matching items with their IDs and titles. Use the limit parameter to
control result count. Does not search archived items.
Returns a dictionary with 'items' list and 'total' count.
"""
if ctx:
await ctx.info(f"Searching for: {query}")
try:
results = await do_search(query, limit)
return {"items": results, "total": len(results)}
except ServiceError as e:
raise ToolError(f"Search failed: {e}")Key rules for every tool:
- on EVERY parameter.
Annotated[type, Field(description=...)] - Verbose docstring: WHAT, WHEN to use, WHEN NOT, WHAT it returns.
- for expected failures (always visible to client).
ToolError - dict on every tool — at minimum
annotations.readOnlyHint - for testability without MCP runtime.
ctx: Context | None = None
See §9 for 8 complete tool patterns (sync, async+Context, stateful, external API, data processing, dependency-injected, sampling, elicitation).
references/tool-design.md针对清单中的每个工具,遵循以下模式:
python
from typing import Annotated
from pydantic import Field
from fastmcp import Context
from fastmcp.exceptions import ToolError
@mcp.tool(
annotations={
"readOnlyHint": True,
"openWorldHint": True,
},
)
async def search_items(
query: Annotated[str, Field(description="用于查找项目的搜索关键词,长度至少1个字符。")],
limit: Annotated[int, Field(description="返回的最大结果数,范围1-100。")] = 10,
ctx: Context | None = None,
) -> dict:
"""搜索匹配指定查询条件的项目。
当你需要通过关键词查找项目时使用此工具。返回包含匹配项目ID和标题的列表。使用limit参数控制结果数量。**不搜索已归档的项目**。
返回包含'items'列表和'total'计数的字典。
"""
if ctx:
await ctx.info(f"正在搜索:{query}")
try:
results = await do_search(query, limit)
return {"items": results, "total": len(results)}
except ServiceError as e:
raise ToolError(f"搜索失败:{e}")每个工具必须遵循的规则:
- 所有参数必须使用定义。
Annotated[type, Field(description=...)] - 详细的文档字符串:说明功能、适用场景、不适用场景、返回结果。
- 预期失败时抛出(对客户端可见)。
ToolError - 每个工具必须包含字典 — 至少包含
annotations。readOnlyHint - 为了便于测试,添加,无需MCP运行时即可测试。
ctx: Context | None = None
参考第9节的8种完整工具模式(同步、异步+Context、有状态、外部API调用、数据处理、依赖注入、采样、启发式交互)。
references/tool-design.md3.3 Implement Resources
3.3 实现资源
python
import json
@mcp.resource("config://settings", mime_type="application/json")
async def get_settings() -> str:
"""Current server configuration."""
return json.dumps(settings)
@mcp.resource("users://{user_id}/profile")
async def get_user_profile(user_id: str) -> str:
"""User profile by ID."""
return json.dumps(await fetch_profile(user_id))See §6 for URI templates, query params, wildcards, and class-based resources.
references/fastmcp-v3-api.mdpython
import json
@mcp.resource("config://settings", mime_type="application/json")
async def get_settings() -> str:
"""当前服务器配置。"""
return json.dumps(settings)
@mcp.resource("users://{user_id}/profile")
async def get_user_profile(user_id: str) -> str:
"""根据ID获取用户资料。"""
return json.dumps(await fetch_profile(user_id))参考第6节了解URI模板、查询参数、通配符和基于类的资源实现。
references/fastmcp-v3-api.md3.4 Implement Prompts
3.4 实现提示词
python
from fastmcp.prompts import Message
@mcp.prompt
def summarize_pr(pr_number: int, detail_level: str = "brief") -> list[Message]:
"""Generate a prompt to summarize a pull request."""
return [Message(
role="user",
content=f"Summarize PR #{pr_number} at {detail_level} detail level.",
)]python
from fastmcp.prompts import Message
@mcp.prompt
def summarize_pr(pr_number: int, detail_level: str = "brief") -> list[Message]:
"""生成用于总结Pull Request的提示词。"""
return [Message(
role="user",
content=f"以{detail_level}详细级别总结PR #{pr_number}。",
)]3.5 Composition (if applicable)
3.5 服务器组合(如适用)
For large servers, split into domain modules and compose. See .
references/server-composition.mdpython
from fastmcp import FastMCP
from .issues import issues_server
from .repos import repos_server
mcp = FastMCP("github")
mcp.mount(issues_server, namespace="issues")
mcp.mount(repos_server, namespace="repos")对于大型服务器,可拆分为多个业务域模块并进行组合。参考。
references/server-composition.mdpython
from fastmcp import FastMCP
from .issues import issues_server
from .repos import repos_server
mcp = FastMCP("github")
mcp.mount(issues_server, namespace="issues")
mcp.mount(repos_server, namespace="repos")3.6 Auth (if applicable)
3.6 认证功能(如适用)
Load when implementing authentication.
references/auth-and-security.md- stdio transport: No MCP-level auth. Use env vars for backend API keys.
- HTTP transport: OAuth 2.1 via ,
JWTVerifier, orGitHubProvider.RemoteAuthProvider - Per-tool auth: .
@mcp.tool(auth=require_scopes("admin")) - Dual-mode pattern: with shared tools, separate auth/no-auth entry points.
common.py
实现认证时请参考。
references/auth-and-security.md- stdio传输: MCP层面不提供认证。后端API密钥使用环境变量。
- HTTP传输: 通过、
JWTVerifier或GitHubProvider实现OAuth 2.1。RemoteAuthProvider - 工具级认证: 使用。
@mcp.tool(auth=require_scopes("admin")) - 双模式方案: 在中定义共享工具,分别创建带认证和不带认证的入口文件。
common.py
Phase 4: Test
阶段4:测试
Goal: Verify all components work correctly with deterministic tests.
Load: (patterns, 18-item checklist)
references/testing.md目标: 通过确定性测试验证所有组件功能正常。
参考文档: (测试模式、18项检查清单)
references/testing.md4.1 Write Tests
4.1 编写测试
Use the in-memory — no network, no subprocess:
Clientpython
import pytest
from fastmcp import Client
from server import mcp
@pytest.fixture
async def client():
async with Client(mcp) as c:
yield c
async def test_search_items(client):
result = await client.call_tool("search_items", {"query": "test"})
assert result.data is not None
assert not result.is_error
async def test_list_tools(client):
tools = await client.list_tools()
names = [t.name for t in tools]
assert "search_items" in names使用内存 — 无需网络和子进程:
Clientpython
import pytest
from fastmcp import Client
from server import mcp
@pytest.fixture
async def client():
async with Client(mcp) as c:
yield c
async def test_search_items(client):
result = await client.call_tool("search_items", {"query": "test"})
assert result.data is not None
assert not result.is_error
async def test_list_tools(client):
tools = await client.list_tools()
names = [t.name for t in tools]
assert "search_items" in names4.2 Test Categories
4.2 测试分类
Cover all 8 categories from :
references/testing.md- Discovery — ,
list_tools(),list_resources()return expected names.list_prompts() - Happy path — Each tool with valid input returns expected output.
- Error handling — Invalid input produces , not crashes.
ToolError - Edge cases — Empty strings, boundary values, Unicode, large inputs.
- Resources — returns correct content and MIME type.
read_resource(uri) - Prompts — returns expected messages.
get_prompt(name, args) - Integration — Tool chains, lifespan setup/teardown.
- Concurrent — Multiple simultaneous calls don't interfere.
覆盖中的8类测试:
references/testing.md- 发现测试 — 、
list_tools()、list_resources()返回预期名称。list_prompts() - 正常流程测试 — 每个工具传入合法输入时返回预期输出。
- 错误处理测试 — 非法输入抛出,而非崩溃。
ToolError - 边缘场景测试 — 空字符串、边界值、Unicode字符、大型输入。
- 资源测试 — 返回正确内容和MIME类型。
read_resource(uri) - 提示词测试 — 返回预期消息。
get_prompt(name, args) - 集成测试 — 工具链、生命周期初始化/销毁。
- 并发测试 — 多个并发调用互不干扰。
4.3 Interactive Testing
4.3 交互式测试
bash
undefinedbash
undefinedMCP Inspector (browser-based)
MCP Inspector(基于浏览器)
fastmcp dev inspector mcp/<name>/server.py
fastmcp dev inspector mcp/<name>/server.py
CLI testing
CLI测试
fastmcp list mcp/<name>/server.py
fastmcp call mcp/<name>/server.py search_items '{"query": "test"}'
undefinedfastmcp list mcp/<name>/server.py
fastmcp call mcp/<name>/server.py search_items '{"query": "test"}'
undefined4.4 Run Tests
4.4 运行测试
bash
cd mcp/<name> && uv run pytest -vbash
cd mcp/<name> && uv run pytest -vPhase 5: Deploy & Configure
阶段5:部署与配置
Goal: Make the server available to MCP clients.
Load: (transports, client configs, Docker)
references/deployment.md目标: 让MCP服务器对客户端可用。
参考文档: (传输方式、客户端配置、Docker部署)
references/deployment.md5.1 Select Transport
5.1 选择传输方式
| Scenario | Transport | Command |
|---|---|---|
| Local / Claude Desktop | stdio | |
| Remote / multi-client | Streamable HTTP | |
| Development | Inspector | |
| 场景 | 传输方式 | 命令 |
|---|---|---|
| 本地 / Claude Desktop | stdio | |
| 远程 / 多客户端 | Streamable HTTP | |
| 开发阶段 | Inspector | |
5.2 Generate Client Config
5.2 生成客户端配置
Add to client config (Claude Desktop, Claude Code, Cursor):
json
{
"mcpServers": {
"server-name": {
"command": "uv",
"args": ["run", "--directory", "/path/to/mcp/<name>", "fastmcp", "run", "server.py"]
}
}
}See §7 for complete configs per client.
references/deployment.md添加到客户端配置(Claude Desktop、Claude Code、Cursor):
json
{
"mcpServers": {
"server-name": {
"command": "uv",
"args": ["run", "--directory", "/path/to/mcp/<name>", "fastmcp", "run", "server.py"]
}
}
}参考第7节获取各客户端的完整配置示例。
references/deployment.md5.3 Validate
5.3 验证部署
MCP server validation (wagents validate does NOT check MCP servers):
bash
undefinedMCP服务器验证(wagents validate 不检查MCP服务器):
bash
undefinedImport check
导入检查
uv run python -c "from server import mcp; print(mcp.name)"
uv run python -c "from server import mcp; print(mcp.name)"
List registered components
列出已注册组件
fastmcp list mcp/<name>/server.py
fastmcp list mcp/<name>/server.py
Interactive inspection
交互式检查
fastmcp dev inspector mcp/<name>/server.py
undefinedfastmcp dev inspector mcp/<name>/server.py
undefined5.4 Quality Checklist
5.4 质量检查清单
Before declaring the server complete:
- Every tool has +
Annotatedon all parametersField(description=...) - Every tool has a verbose docstring (WHAT, WHEN, WHEN NOT, RETURNS)
- Every tool has (at minimum
annotations)readOnlyHint - Every tool uses for expected failures
ToolError - No or
print()writes in any toolstdout - Resources have correct URI schemes and MIME types
- Tests pass:
uv run pytest -v - MCP Inspector shows all components correctly
- lists all required dependencies
fastmcp.json - has correct metadata and dependencies
pyproject.toml - No deprecated constructor kwargs (removed in rc1)
- Custom routes have manual auth if sensitive
- set for production deployment
mask_error_details=True
在宣布服务器完成前,请确认以下事项:
- 每个工具的所有参数均使用+
AnnotatedField(description=...) - 每个工具都有详细的文档字符串(功能、适用场景、不适用场景、返回结果)
- 每个工具都配置了(至少包含
annotations)readOnlyHint - 每个工具在预期失败时使用
ToolError - 所有工具中未使用或直接写入stdout
print() - 资源使用正确的URI scheme和MIME类型
- 测试全部通过:
uv run pytest -v - MCP Inspector正确显示所有组件
- 列出了所有必需的依赖
fastmcp.json - 包含正确的元数据和依赖
pyproject.toml - 未使用已弃用的构造函数参数(rc1中已移除)
- 自定义路由对敏感操作添加了手动认证
- 生产部署时设置了
mask_error_details=True
Reference File Index
参考文档索引
Load these files on demand during the relevant phase. Do NOT load all at once.
| File | Content | Load during |
|---|---|---|
| Complete v3 API surface: constructor, decorators, Context, return types, resources, prompts, providers, transforms, 14 middleware, background tasks, visibility, v2→v3 changes | Phase 3 |
| LLM-optimized naming, descriptions, parameters, annotations, error handling, 8 tool patterns, structured output, response patterns, anti-patterns | Phase 1, 3 |
| mount(), import_server(), proxy, FileSystemProvider, OpenAPI (OpenAPIProvider + from_openapi), FastAPI conversion, custom providers, transforms, gateway pattern, DRY registration | Phase 1, 3 |
| In-memory Client, pytest setup, conftest.py template, 8 test categories, MCP Inspector, CLI testing, 18-item checklist | Phase 4 |
| OAuth 2.1, JWTVerifier, per-component auth, custom auth checks, session-based visibility, custom route auth bypass, SSRF prevention, dual-mode pattern, 15 security rules | Phase 3 |
| Transports, FastMCP CLI, ASGI, custom routes, client configs, fastmcp.json schema, Docker, background task workers, production checklist | Phase 5 |
| Resources (static, dynamic, binary), prompts (single/multi-message), resource vs tool guidance, testing patterns | Phase 3 |
| 34 errors: symptom → cause → v3-updated fix, quick-fix lookup table | Debug mode |
| Minimal examples: server, tool, resource, prompt, lifespan, test, run | Quick start |
在对应阶段按需加载以下文档,请勿一次性加载所有文档。
| 文档 | 内容 | 加载阶段 |
|---|---|---|
| 完整v3 API接口:构造函数、装饰器、Context、返回类型、资源、提示词、Providers、Transforms、14种中间件、后台任务、可见性、v2→v3迁移说明 | 阶段3 |
| LLM优化的命名规则、描述规范、参数设计、注解、错误处理、8种工具模式、结构化输出、响应模式、反模式 | 阶段1、3 |
| mount()、import_server()、代理、FileSystemProvider、OpenAPI(OpenAPIProvider + from_openapi)、FastAPI转换、自定义Providers、Transforms、网关模式、DRY注册 | 阶段1、3 |
| 内存Client、pytest配置、conftest.py模板、8类测试、MCP Inspector、CLI测试、18项检查清单 | 阶段4 |
| OAuth 2.1、JWTVerifier、组件级认证、自定义认证检查、基于会话的可见性、自定义路由认证绕过、SSRF防护、双模式方案、15条安全规则 | 阶段3 |
| 传输方式、FastMCP CLI、ASGI、自定义路由、客户端配置、fastmcp.json schema、Docker部署、后台任务 worker、生产环境检查清单 | 阶段5 |
| 资源(静态、动态、二进制)、提示词(单条/多条消息)、资源与工具的选择指南、测试模式 | 阶段3 |
| 34种错误:症状→原因→v3修复方案、快速修复对照表 | 调试模式 |
| 极简示例:服务器、工具、资源、提示词、生命周期、测试、运行命令 | 快速入门 |
Critical Rules
核心规则
These are non-negotiable. Violating any of these produces broken MCP servers.
-
No stdout. Never useor write to stdout in tools/resources/prompts. Stdout is the MCP transport. Use
print(),ctx.info(),ctx.warning()for logging.ctx.error() -
ToolError for expected failures. Alwaysfor user-facing errors. Standard exceptions are masked by
raise ToolError("message")in production.mask_error_details -
Verbose descriptions. Every tool needs a 3-5 sentence docstring. Every parameter needs. LLMs cannot use tools they don't understand.
Field(description=...) -
Annotations on every tool. Set,
readOnlyHint,destructiveHint,idempotentHint. Clients use these for confirmation flows and retry logic.openWorldHint -
Noor
*args. MCP requires a fixed JSON schema for tool inputs. Dynamic signatures break schema generation.**kwargs -
Async state access. In v3,and
ctx.get_state()are async — alwaysctx.set_state()them.await -
URI schemes required. Every resource URI must have a scheme (,
data://,config://). Bare paths fail.users:// -
Test deterministically. Use in-memory, not manual prompting. Tests must be repeatable and automated.
Client(mcp) -
Module-levelvariable. The
mcpinstance must be importable at module level.FastMCPimportsfastmcp runby default.server:mcp -
Secrets in env vars only. Never hardcode API keys. Never accept tokens as tool parameters. Load from environment, validate on startup.
以下规则为强制要求,违反任何一条都会导致MCP服务器无法正常工作。
-
禁止写入stdout。工具/资源/提示词中绝对不能使用或直接写入标准输出。Stdout是MCP的传输通道。请使用
print()、ctx.info()、ctx.warning()进行日志记录。ctx.error() -
预期失败必须抛出ToolError。用户可见的错误必须使用。生产环境中标准异常会被
raise ToolError("message")屏蔽。mask_error_details -
详细的描述信息。每个工具都需要3-5句话的文档字符串。每个参数都需要。LLM无法使用它们不理解的工具。
Field(description=...) -
每个工具必须添加注解。设置、
readOnlyHint、destructiveHint、idempotentHint。客户端使用这些信息进行确认流程和重试逻辑。openWorldHint -
禁止使用或
*args。MCP要求工具输入有固定的JSON schema。动态签名会破坏schema生成。**kwargs -
异步访问状态。在v3中,和
ctx.get_state()是异步方法 — 必须使用ctx.set_state()调用。await -
资源URI必须包含scheme。每个资源URI必须有scheme(、
data://、config://)。裸路径会导致失败。users:// -
确定性测试。使用内存进行测试,而非手动交互。测试必须可重复且自动化。
Client(mcp) -
模块级变量。
mcp实例必须在模块级别可导入。FastMCP默认导入fastmcp run。server:mcp -
密钥仅存于环境变量。绝对不能硬编码API密钥。绝对不能通过工具参数接收令牌。从环境变量加载,在启动时验证。
Quick Reference
快速参考
Load for the complete quick reference with minimal examples for server, tool, resource, prompt, lifespan, test, and run commands.
references/quick-reference.md加载获取完整的快速参考,包含服务器、工具、资源、提示词、生命周期、测试和运行命令的极简示例。
references/quick-reference.mdCanonical Vocabulary
标准术语表
Use these terms consistently. Do not invent synonyms.
| Canonical term | Meaning | NOT |
|---|---|---|
| tool | A callable MCP function exposed to clients | "endpoint", "action", "command" |
| resource | URI-addressed read-only data exposed to clients | "asset", "file", "data source" |
| prompt | Reusable message template guiding LLM behavior | "instruction", "system message" |
| provider | Dynamic component source (e.g., | "plugin", "adapter" |
| transform | Middleware that modifies components at mount time | "filter", "interceptor" |
| middleware | Request/response processing hook in the server pipeline | "handler", "decorator" |
| lifespan | Async context manager for shared server resources | "startup hook", "init" |
| mount | Attach a child server with a namespace prefix | "register", "include" |
| namespace | Prefix added to component names during mount | "scope", "prefix" |
| Context | Runtime object passed to tools for logging, state, sampling | "request", "session" |
| ToolError | Exception class for user-visible error messages | "raise Exception" |
| annotation | Tool metadata hints ( | "tag", "label" |
| transport | Communication layer: stdio or Streamable HTTP | "protocol", "channel" |
请统一使用以下术语,不要自行创造同义词。
| 标准术语 | 含义 | 禁用术语 |
|---|---|---|
| tool(工具) | 暴露给客户端的可调用MCP函数 | "endpoint"、"action"、"command" |
| resource(资源) | 暴露给客户端的、通过URI访问的只读数据 | "asset"、"file"、"data source" |
| prompt(提示词) | 指导LLM行为的可复用消息模板 | "instruction"、"system message" |
| provider(提供者) | 动态组件源(例如: | "plugin"、"adapter" |
| transform(转换器) | 挂载时修改组件的中间件 | "filter"、"interceptor" |
| middleware(中间件) | 服务器管道中的请求/响应处理钩子 | "handler"、"decorator" |
| lifespan(生命周期) | 用于管理服务器共享资源的异步上下文管理器 | "startup hook"、"init" |
| mount(挂载) | 将子服务器附加到父服务器并添加命名空间前缀 | "register"、"include" |
| namespace(命名空间) | 挂载时添加到组件名称的前缀 | "scope"、"prefix" |
| Context(上下文) | 传递给工具的运行时对象,用于日志、状态、采样 | "request"、"session" |
| ToolError(工具错误) | 用于用户可见错误消息的异常类 | "raise Exception" |
| annotation(注解) | 工具元数据提示( | "tag"、"label" |
| transport(传输方式) | 通信层:stdio或Streamable HTTP | "protocol"、"channel" |