mcp-creator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP 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:
mcp/<name>/
directory,
fastmcp.json
config,
uv
workspace member, imperative voice, kebab-case naming.
Target: FastMCP v3 rc2 — Provider/Transform architecture, 14 built-in middleware, OAuth 2.1, server composition, component versioning, structured output, background tasks, elicitation, sampling.
Input:
$ARGUMENTS
— the service, API, or capability to wrap as an MCP server.

使用FastMCP v3(3.0.0rc2)构建生产可用的MCP服务器。本指南将指导你完成调研、脚手架搭建、功能实现、测试和部署的全流程。所有输出需遵循本仓库的约定:
mcp/<name>/
目录结构、
fastmcp.json
配置文件、
uv
工作区成员、命令式语气、短横线分隔命名法(kebab-case)。
目标版本: FastMCP v3 rc2 — 采用Provider/Transform架构、内置14种中间件、支持OAuth 2.1、服务器组合、组件版本控制、结构化输出、后台任务、启发式交互、采样功能。
输入:
$ARGUMENTS
— 要封装为MCP服务器的服务、API或功能。

Dispatch

任务分发

Route
$ARGUMENTS
to the appropriate mode:
$ARGUMENTS patternModeStart at
Service/API name (e.g., "GitHub", "Stripe")New serverPhase 1
Path to existing server (e.g.,
mcp/myserver/
)
ExtendPhase 3
OpenAPI spec URL or file pathConvert OpenAPIPhase 2 (scaffold) then load
references/server-composition.md
§6
FastAPI app to convertConvert FastAPIPhase 2 (scaffold) then load
references/server-composition.md
§7
Error message or "debug" + descriptionDebugLoad
references/common-errors.md
, match symptom
"learn" or conceptual questionLearnLoad relevant reference file, explain
EmptyGallery / help overviewShow available modes and example invocations

根据
$ARGUMENTS
的匹配模式路由到对应工作模式:
$ARGUMENTS 模式模式起始阶段
服务/API名称(例如:"GitHub", "Stripe")新建服务器阶段1
现有服务器路径(例如:
mcp/myserver/
扩展服务器阶段3
OpenAPI规范URL或文件路径转换OpenAPI阶段2(脚手架),然后参考
references/server-composition.md
第6节
待转换的FastAPI应用转换FastAPI阶段2(脚手架),然后参考
references/server-composition.md
第7节
错误信息或包含"debug"的描述调试加载
references/common-errors.md
,匹配症状
"learn"或概念性问题学习加载相关参考文档并进行解释
空输入示例库/帮助概览展示可用模式及调用示例

Consult Live Documentation

查阅实时文档

Before implementation, fetch current FastMCP v3 docs. Bundled references capture rc2 — live docs may be newer.
  1. Context7
    resolve-library-id
    for "fastmcp", then
    query-docs
    for the topic.
  2. WebFetch
    https://gofastmcp.com/llms-full.txt
    — comprehensive LLM-optimized docs.
  3. WebSearch fallback
    site:gofastmcp.com <topic>
    for specific topics.
If live docs contradict bundled references, live docs win. Always fetch live docs first — API details shift between rc2 and stable.

在开始实现前,请获取最新的FastMCP v3文档。内置参考文档基于rc2版本,而实时文档可能更新。
  1. Context7 — 调用
    resolve-library-id
    获取"fastmcp"的库ID,再通过
    query-docs
    查询相关主题。
  2. WebFetch — 访问
    https://gofastmcp.com/llms-full.txt
    — 这是为LLM优化的完整文档。
  3. 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:
references/tool-design.md
(naming, descriptions, parameter design, 8 tool patterns)
目标: 了解目标服务并设计MCP服务器的工具/资源/提示词清单。
参考文档:
references/tool-design.md
(命名规则、描述规范、参数设计、8种工具模式)

1.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 →
    task=True
    , requires
    fastmcp[tasks]
    )
  • OpenAPI spec available? (→
    OpenAPIProvider
    or
    FastMCP.from_openapi()
    )
  • Multiple domains? (→ composed servers with
    mount()
    + namespaces)
在进入下一阶段前,请确认以下事项:
  • 是否需要认证?(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:
FieldRequirement
Name
snake_case
,
verb_noun
format, max 64 chars
Description3-5 sentences: WHAT, WHEN to use, WHEN NOT, WHAT it returns
ParametersEach with type, description, constraints via
Annotated[type, Field(...)]
Annotations
readOnlyHint
,
destructiveHint
,
idempotentHint
,
openWorldHint
Error casesWhat
ToolError
messages to raise for expected failures
每个服务器规划5-15个工具。针对每个工具,需定义:
字段要求
名称使用
snake_case
格式,遵循
动词_名词
结构,最长64字符
描述3-5句话:说明功能、适用场景、不适用场景、返回结果
参数每个参数需使用
Annotated[type, Field(...)]
定义类型、描述和约束
注解包含
readOnlyHint
destructiveHint
idempotentHint
openWorldHint
错误场景定义预期失败时需抛出的
ToolError
消息

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
    references/fastmcp-v3-api.md
    §6-7 for URI patterns and prompt design.
  • 资源(Resources):用于静态/慢变更数据(配置、 schema、状态),通过URI访问。
  • 提示词(Prompts):用于指导LLM行为的可复用消息模板。
  • 参考
    references/fastmcp-v3-api.md
    第6-7节了解URI模式和提示词设计规范。

1.5 Plan Architecture

1.5 规划架构

Decide on composition strategy:
  • Single server — Most cases. One
    FastMCP
    instance with all tools.
  • Composed servers — Large APIs. Domain servers mounted via
    mount()
    with namespaces.
  • Provider-based — Dynamic tool registration.
    FileSystemProvider
    or custom
    Provider
    .
  • OpenAPI conversion — Auto-generate tools from OpenAPI spec.
    OpenAPIProvider
    or
    FastMCP.from_openapi()
    .
See
references/server-composition.md
for patterns.
确定服务器组合策略:
  • 单服务器:大多数场景适用。一个
    FastMCP
    实例包含所有工具。
  • 组合服务器:适用于大型API。将业务域服务器通过
    mount()
    挂载并添加命名空间。
  • 基于Provider:动态注册工具。使用
    FileSystemProvider
    或自定义
    Provider
  • OpenAPI转换:从OpenAPI规范自动生成工具。使用
    OpenAPIProvider
    FastMCP.from_openapi()
参考
references/server-composition.md
了解具体模式。

1.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
wagents new mcp <name>
to scaffold:
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 suite
Customize 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
    pyproject.toml
    and
    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.toml
:
toml
[tool.pytest.ini_options]
asyncio_mode = "auto"

[dependency-groups]
dev = ["pytest>=8", "pytest-asyncio>=0.25"]
Create
tests/conftest.py
— see
references/testing.md
§4 for the complete template.
pyproject.toml
中添加:
toml
[tool.pytest.ini_options]
asyncio_mode = "auto"

[dependency-groups]
dev = ["pytest>=8", "pytest-asyncio>=0.25"]
创建
tests/conftest.py
— 参考
references/testing.md
第4节获取完整模板。

2.3 Configure and Verify

2.3 配置与验证

  • Ensure root
    pyproject.toml
    has
    [tool.uv.workspace] members = ["mcp/*"]
    .
  • Run
    cd mcp/<name> && uv sync
    to install dependencies.
  • Verify:
    uv run python -c "from server import mcp; print(mcp.name)"
    .
Note:
wagents validate
validates skills/agents only, NOT MCP servers. Use the import check above for MCP server validation.

  • 确保根目录的
    pyproject.toml
    包含
    [tool.uv.workspace] members = ["mcp/*"]
  • 运行
    cd mcp/<name> && uv sync
    安装依赖。
  • 验证安装:
    uv run python -c "from server import mcp; print(mcp.name)"
注意:
wagents validate
仅验证技能/Agent,不验证MCP服务器。请使用上述导入检查验证MCP服务器。

Phase 3: Implement

阶段3:功能实现

Goal: Build all tools, resources, and prompts from the Phase 1 inventory.
Load:
references/fastmcp-v3-api.md
(full API surface),
references/tool-design.md
(patterns)
目标: 实现阶段1清单中的所有工具、资源和提示词。
参考文档:
references/fastmcp-v3-api.md
(完整API接口)、
references/tool-design.md
(工具模式)

3.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:
  • Annotated[type, Field(description=...)]
    on EVERY parameter.
  • Verbose docstring: WHAT, WHEN to use, WHEN NOT, WHAT it returns.
  • ToolError
    for expected failures (always visible to client).
  • annotations
    dict on every tool — at minimum
    readOnlyHint
    .
  • ctx: Context | None = None
    for testability without MCP runtime.
See
references/tool-design.md
§9 for 8 complete tool patterns (sync, async+Context, stateful, external API, data processing, dependency-injected, sampling, elicitation).
针对清单中的每个工具,遵循以下模式:
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
  • 为了便于测试,添加
    ctx: Context | None = None
    ,无需MCP运行时即可测试。
参考
references/tool-design.md
第9节的8种完整工具模式(同步、异步+Context、有状态、外部API调用、数据处理、依赖注入、采样、启发式交互)。

3.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
references/fastmcp-v3-api.md
§6 for URI templates, query params, wildcards, and class-based resources.
python
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))
参考
references/fastmcp-v3-api.md
第6节了解URI模板、查询参数、通配符和基于类的资源实现。

3.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.md
.
python
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.md
python
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
references/auth-and-security.md
when implementing authentication.
  • stdio transport: No MCP-level auth. Use env vars for backend API keys.
  • HTTP transport: OAuth 2.1 via
    JWTVerifier
    ,
    GitHubProvider
    , or
    RemoteAuthProvider
    .
  • Per-tool auth:
    @mcp.tool(auth=require_scopes("admin"))
    .
  • Dual-mode pattern:
    common.py
    with shared tools, separate auth/no-auth entry points.

实现认证时请参考
references/auth-and-security.md
  • stdio传输: MCP层面不提供认证。后端API密钥使用环境变量。
  • HTTP传输: 通过
    JWTVerifier
    GitHubProvider
    RemoteAuthProvider
    实现OAuth 2.1。
  • 工具级认证: 使用
    @mcp.tool(auth=require_scopes("admin"))
  • 双模式方案:
    common.py
    中定义共享工具,分别创建带认证和不带认证的入口文件。

Phase 4: Test

阶段4:测试

Goal: Verify all components work correctly with deterministic tests.
Load:
references/testing.md
(patterns, 18-item checklist)
目标: 通过确定性测试验证所有组件功能正常。
参考文档:
references/testing.md
(测试模式、18项检查清单)

4.1 Write Tests

4.1 编写测试

Use the in-memory
Client
— no network, no subprocess:
python
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
使用内存
Client
— 无需网络和子进程:
python
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

4.2 Test Categories

4.2 测试分类

Cover all 8 categories from
references/testing.md
:
  1. Discovery
    list_tools()
    ,
    list_resources()
    ,
    list_prompts()
    return expected names.
  2. Happy path — Each tool with valid input returns expected output.
  3. Error handling — Invalid input produces
    ToolError
    , not crashes.
  4. Edge cases — Empty strings, boundary values, Unicode, large inputs.
  5. Resources
    read_resource(uri)
    returns correct content and MIME type.
  6. Prompts
    get_prompt(name, args)
    returns expected messages.
  7. Integration — Tool chains, lifespan setup/teardown.
  8. Concurrent — Multiple simultaneous calls don't interfere.
覆盖
references/testing.md
中的8类测试:
  1. 发现测试
    list_tools()
    list_resources()
    list_prompts()
    返回预期名称。
  2. 正常流程测试 — 每个工具传入合法输入时返回预期输出。
  3. 错误处理测试 — 非法输入抛出
    ToolError
    ,而非崩溃。
  4. 边缘场景测试 — 空字符串、边界值、Unicode字符、大型输入。
  5. 资源测试
    read_resource(uri)
    返回正确内容和MIME类型。
  6. 提示词测试
    get_prompt(name, args)
    返回预期消息。
  7. 集成测试 — 工具链、生命周期初始化/销毁。
  8. 并发测试 — 多个并发调用互不干扰。

4.3 Interactive Testing

4.3 交互式测试

bash
undefined
bash
undefined

MCP 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"}'
undefined
fastmcp list mcp/<name>/server.py fastmcp call mcp/<name>/server.py search_items '{"query": "test"}'
undefined

4.4 Run Tests

4.4 运行测试

bash
cd mcp/<name> && uv run pytest -v

bash
cd mcp/<name> && uv run pytest -v

Phase 5: Deploy & Configure

阶段5:部署与配置

Goal: Make the server available to MCP clients.
Load:
references/deployment.md
(transports, client configs, Docker)
目标: 让MCP服务器对客户端可用。
参考文档:
references/deployment.md
(传输方式、客户端配置、Docker部署)

5.1 Select Transport

5.1 选择传输方式

ScenarioTransportCommand
Local / Claude Desktopstdio
fastmcp run server.py
Remote / multi-clientStreamable HTTP
fastmcp run server.py --transport http --port 8000
DevelopmentInspector
fastmcp dev inspector server.py
场景传输方式命令
本地 / Claude Desktopstdio
fastmcp run server.py
远程 / 多客户端Streamable HTTP
fastmcp run server.py --transport http --port 8000
开发阶段Inspector
fastmcp dev inspector server.py

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
references/deployment.md
§7 for complete configs per client.
添加到客户端配置(Claude Desktop、Claude Code、Cursor):
json
{
  "mcpServers": {
    "server-name": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/mcp/<name>", "fastmcp", "run", "server.py"]
    }
  }
}
参考
references/deployment.md
第7节获取各客户端的完整配置示例。

5.3 Validate

5.3 验证部署

MCP server validation (wagents validate does NOT check MCP servers):
bash
undefined
MCP服务器验证(wagents validate 不检查MCP服务器):
bash
undefined

Import 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
undefined
fastmcp dev inspector mcp/<name>/server.py
undefined

5.4 Quality Checklist

5.4 质量检查清单

Before declaring the server complete:
  • Every tool has
    Annotated
    +
    Field(description=...)
    on all parameters
  • Every tool has a verbose docstring (WHAT, WHEN, WHEN NOT, RETURNS)
  • Every tool has
    annotations
    (at minimum
    readOnlyHint
    )
  • Every tool uses
    ToolError
    for expected failures
  • No
    print()
    or
    stdout
    writes in any tool
  • Resources have correct URI schemes and MIME types
  • Tests pass:
    uv run pytest -v
  • MCP Inspector shows all components correctly
  • fastmcp.json
    lists all required dependencies
  • pyproject.toml
    has correct metadata and dependencies
  • No deprecated constructor kwargs (removed in rc1)
  • Custom routes have manual auth if sensitive
  • mask_error_details=True
    set for production deployment

在宣布服务器完成前,请确认以下事项:
  • 每个工具的所有参数均使用
    Annotated
    +
    Field(description=...)
  • 每个工具都有详细的文档字符串(功能、适用场景、不适用场景、返回结果)
  • 每个工具都配置了
    annotations
    (至少包含
    readOnlyHint
  • 每个工具在预期失败时使用
    ToolError
  • 所有工具中未使用
    print()
    或直接写入stdout
  • 资源使用正确的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.
FileContentLoad during
references/fastmcp-v3-api.md
Complete v3 API surface: constructor, decorators, Context, return types, resources, prompts, providers, transforms, 14 middleware, background tasks, visibility, v2→v3 changesPhase 3
references/tool-design.md
LLM-optimized naming, descriptions, parameters, annotations, error handling, 8 tool patterns, structured output, response patterns, anti-patternsPhase 1, 3
references/server-composition.md
mount(), import_server(), proxy, FileSystemProvider, OpenAPI (OpenAPIProvider + from_openapi), FastAPI conversion, custom providers, transforms, gateway pattern, DRY registrationPhase 1, 3
references/testing.md
In-memory Client, pytest setup, conftest.py template, 8 test categories, MCP Inspector, CLI testing, 18-item checklistPhase 4
references/auth-and-security.md
OAuth 2.1, JWTVerifier, per-component auth, custom auth checks, session-based visibility, custom route auth bypass, SSRF prevention, dual-mode pattern, 15 security rulesPhase 3
references/deployment.md
Transports, FastMCP CLI, ASGI, custom routes, client configs, fastmcp.json schema, Docker, background task workers, production checklistPhase 5
references/resources-and-prompts.md
Resources (static, dynamic, binary), prompts (single/multi-message), resource vs tool guidance, testing patternsPhase 3
references/common-errors.md
34 errors: symptom → cause → v3-updated fix, quick-fix lookup tableDebug mode
references/quick-reference.md
Minimal examples: server, tool, resource, prompt, lifespan, test, runQuick start

在对应阶段按需加载以下文档,请勿一次性加载所有文档
文档内容加载阶段
references/fastmcp-v3-api.md
完整v3 API接口:构造函数、装饰器、Context、返回类型、资源、提示词、Providers、Transforms、14种中间件、后台任务、可见性、v2→v3迁移说明阶段3
references/tool-design.md
LLM优化的命名规则、描述规范、参数设计、注解、错误处理、8种工具模式、结构化输出、响应模式、反模式阶段1、3
references/server-composition.md
mount()、import_server()、代理、FileSystemProvider、OpenAPI(OpenAPIProvider + from_openapi)、FastAPI转换、自定义Providers、Transforms、网关模式、DRY注册阶段1、3
references/testing.md
内存Client、pytest配置、conftest.py模板、8类测试、MCP Inspector、CLI测试、18项检查清单阶段4
references/auth-and-security.md
OAuth 2.1、JWTVerifier、组件级认证、自定义认证检查、基于会话的可见性、自定义路由认证绕过、SSRF防护、双模式方案、15条安全规则阶段3
references/deployment.md
传输方式、FastMCP CLI、ASGI、自定义路由、客户端配置、fastmcp.json schema、Docker部署、后台任务 worker、生产环境检查清单阶段5
references/resources-and-prompts.md
资源(静态、动态、二进制)、提示词(单条/多条消息)、资源与工具的选择指南、测试模式阶段3
references/common-errors.md
34种错误:症状→原因→v3修复方案、快速修复对照表调试模式
references/quick-reference.md
极简示例:服务器、工具、资源、提示词、生命周期、测试、运行命令快速入门

Critical Rules

核心规则

These are non-negotiable. Violating any of these produces broken MCP servers.
  1. No stdout. Never use
    print()
    or write to stdout in tools/resources/prompts. Stdout is the MCP transport. Use
    ctx.info()
    ,
    ctx.warning()
    ,
    ctx.error()
    for logging.
  2. ToolError for expected failures. Always
    raise ToolError("message")
    for user-facing errors. Standard exceptions are masked by
    mask_error_details
    in production.
  3. Verbose descriptions. Every tool needs a 3-5 sentence docstring. Every parameter needs
    Field(description=...)
    . LLMs cannot use tools they don't understand.
  4. Annotations on every tool. Set
    readOnlyHint
    ,
    destructiveHint
    ,
    idempotentHint
    ,
    openWorldHint
    . Clients use these for confirmation flows and retry logic.
  5. No
    *args
    or
    **kwargs
    .
    MCP requires a fixed JSON schema for tool inputs. Dynamic signatures break schema generation.
  6. Async state access. In v3,
    ctx.get_state()
    and
    ctx.set_state()
    are async — always
    await
    them.
  7. URI schemes required. Every resource URI must have a scheme (
    data://
    ,
    config://
    ,
    users://
    ). Bare paths fail.
  8. Test deterministically. Use in-memory
    Client(mcp)
    , not manual prompting. Tests must be repeatable and automated.
  9. Module-level
    mcp
    variable.
    The
    FastMCP
    instance must be importable at module level.
    fastmcp run
    imports
    server:mcp
    by default.
  10. Secrets in env vars only. Never hardcode API keys. Never accept tokens as tool parameters. Load from environment, validate on startup.

以下规则为强制要求,违反任何一条都会导致MCP服务器无法正常工作。
  1. 禁止写入stdout。工具/资源/提示词中绝对不能使用
    print()
    或直接写入标准输出。Stdout是MCP的传输通道。请使用
    ctx.info()
    ctx.warning()
    ctx.error()
    进行日志记录。
  2. 预期失败必须抛出ToolError。用户可见的错误必须使用
    raise ToolError("message")
    。生产环境中标准异常会被
    mask_error_details
    屏蔽。
  3. 详细的描述信息。每个工具都需要3-5句话的文档字符串。每个参数都需要
    Field(description=...)
    。LLM无法使用它们不理解的工具。
  4. 每个工具必须添加注解。设置
    readOnlyHint
    destructiveHint
    idempotentHint
    openWorldHint
    。客户端使用这些信息进行确认流程和重试逻辑。
  5. 禁止使用
    *args
    **kwargs
    。MCP要求工具输入有固定的JSON schema。动态签名会破坏schema生成。
  6. 异步访问状态。在v3中,
    ctx.get_state()
    ctx.set_state()
    是异步方法 — 必须使用
    await
    调用。
  7. 资源URI必须包含scheme。每个资源URI必须有scheme(
    data://
    config://
    users://
    )。裸路径会导致失败。
  8. 确定性测试。使用内存
    Client(mcp)
    进行测试,而非手动交互。测试必须可重复且自动化。
  9. 模块级
    mcp
    变量
    FastMCP
    实例必须在模块级别可导入。
    fastmcp run
    默认导入
    server:mcp
  10. 密钥仅存于环境变量。绝对不能硬编码API密钥。绝对不能通过工具参数接收令牌。从环境变量加载,在启动时验证。

Quick Reference

快速参考

Load
references/quick-reference.md
for the complete quick reference with minimal examples for server, tool, resource, prompt, lifespan, test, and run commands.

加载
references/quick-reference.md
获取完整的快速参考,包含服务器、工具、资源、提示词、生命周期、测试和运行命令的极简示例。

Canonical Vocabulary

标准术语表

Use these terms consistently. Do not invent synonyms.
Canonical termMeaningNOT
toolA callable MCP function exposed to clients"endpoint", "action", "command"
resourceURI-addressed read-only data exposed to clients"asset", "file", "data source"
promptReusable message template guiding LLM behavior"instruction", "system message"
providerDynamic component source (e.g.,
FileSystemProvider
,
OpenAPIProvider
)
"plugin", "adapter"
transformMiddleware that modifies components at mount time"filter", "interceptor"
middlewareRequest/response processing hook in the server pipeline"handler", "decorator"
lifespanAsync context manager for shared server resources"startup hook", "init"
mountAttach a child server with a namespace prefix"register", "include"
namespacePrefix added to component names during mount"scope", "prefix"
ContextRuntime object passed to tools for logging, state, sampling"request", "session"
ToolErrorException class for user-visible error messages"raise Exception"
annotationTool metadata hints (
readOnlyHint
,
destructiveHint
, etc.)
"tag", "label"
transportCommunication layer: stdio or Streamable HTTP"protocol", "channel"
请统一使用以下术语,不要自行创造同义词。
标准术语含义禁用术语
tool(工具)暴露给客户端的可调用MCP函数"endpoint"、"action"、"command"
resource(资源)暴露给客户端的、通过URI访问的只读数据"asset"、"file"、"data source"
prompt(提示词)指导LLM行为的可复用消息模板"instruction"、"system message"
provider(提供者)动态组件源(例如:
FileSystemProvider
、自定义
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(注解)工具元数据提示(
readOnlyHint
destructiveHint
等)
"tag"、"label"
transport(传输方式)通信层:stdio或Streamable HTTP"protocol"、"channel"