fastmcp-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

FastMCP 3.0 Server Development

FastMCP 3.0 服务器开发

Complete reference for building production-ready MCP (Model Context Protocol) servers with FastMCP 3.0 - the fast, Pythonic framework for connecting LLMs to tools and data.
使用FastMCP 3.0构建生产级MCP(Model Context Protocol,模型上下文协议)服务器的完整参考文档——FastMCP是一款轻量、符合Python风格的框架,用于将LLM连接到各类工具和数据。

When to use this skill

适用场景

Use FastMCP Server when:
  • Creating a new MCP server in Python
  • Adding tools, resources, or prompts to an MCP server
  • Implementing authentication (OAuth, OIDC, token verification)
  • Setting up middleware for logging, rate limiting, or authorization
  • Configuring providers (local, filesystem, skills, custom)
  • Building production MCP servers with telemetry and storage
  • Upgrading from FastMCP 2.x to 3.0
Key areas covered:
  • Tools & Resources (CORE): Decorators, validation, return types, templates
  • Context & DI (CORE): MCP context, dependency injection, background tasks
  • Authentication (SECURITY): OAuth, OIDC, token verification, proxy patterns
  • Authorization (SECURITY): Scope-based and role-based access control
  • Middleware (ADVANCED): Request/response pipeline, built-in middleware
  • Providers (ADVANCED): Local, filesystem, skills, and custom providers
  • Features (ADVANCED): Pagination, sampling, storage, OpenTelemetry, versioning
在以下场景使用FastMCP服务器:
  • 用Python创建新的MCP服务器
  • 为MCP服务器添加工具、资源或提示词
  • 实现认证功能(OAuth、OIDC、令牌验证)
  • 配置日志、限流或授权相关的中间件
  • 配置提供者(本地、文件系统、技能包、自定义)
  • 构建带有遥测和存储功能的生产级MCP服务器
  • 从FastMCP 2.x升级到3.0版本
核心覆盖领域:
  • 工具与资源(核心):装饰器、验证、返回类型、模板
  • 上下文与依赖注入(核心):MCP上下文、依赖注入、后台任务
  • 认证(安全):OAuth、OIDC、令牌验证、代理模式
  • 授权(安全):基于范围和角色的访问控制
  • 中间件(进阶):请求/响应管道、内置中间件
  • 提供者(进阶):本地、文件系统、技能包和自定义提供者
  • 功能特性(进阶):分页、采样、存储、OpenTelemetry、版本控制

Quick reference

快速参考

Core patterns

核心模式

Create a server with tools:
python
from fastmcp import FastMCP

mcp = FastMCP("MyServer")

@mcp.tool
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b
Create a resource:
python
@mcp.resource("data://config")
def get_config() -> dict:
    """Return server configuration"""
    return {"version": "1.0", "debug": False}
Create a resource template:
python
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> dict:
    """Get a user's profile by ID"""
    return fetch_user(user_id)
Create a prompt:
python
@mcp.prompt
def review_code(code: str, language: str = "python") -> str:
    """Review code for best practices"""
    return f"Review this {language} code:\n\n{code}"
Run the server:
python
if __name__ == "__main__":
    mcp.run()
创建带有工具的服务器:
python
from fastmcp import FastMCP

mcp = FastMCP("MyServer")

@mcp.tool
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b
创建资源:
python
@mcp.resource("data://config")
def get_config() -> dict:
    """Return server configuration"""
    return {"version": "1.0", "debug": False}
创建资源模板:
python
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> dict:
    """Get a user's profile by ID"""
    return fetch_user(user_id)
创建提示词:
python
@mcp.prompt
def review_code(code: str, language: str = "python") -> str:
    """Review code for best practices"""
    return f"Review this {language} code:\n\n{code}"
启动服务器:
python
if __name__ == "__main__":
    mcp.run()

Or with transport options:

或使用传输选项:

mcp.run(transport="sse", host="0.0.0.0", port=8000)

mcp.run(transport="sse", host="0.0.0.0", port=8000)

undefined
undefined

Using context in tools

在工具中使用上下文

python
from fastmcp import FastMCP, Context

mcp = FastMCP("MyServer")

@mcp.tool
def process_data(uri: str, ctx: Context) -> str:
    """Process data with logging and progress"""
    ctx.info(f"Processing {uri}")
    ctx.report_progress(0, 100)
    data = ctx.read_resource(uri)
    ctx.report_progress(100, 100)
    return f"Processed: {data}"
python
from fastmcp import FastMCP, Context

mcp = FastMCP("MyServer")

@mcp.tool
def process_data(uri: str, ctx: Context) -> str:
    """Process data with logging and progress"""
    ctx.info(f"Processing {uri}")
    ctx.report_progress(0, 100)
    data = ctx.read_resource(uri)
    ctx.report_progress(100, 100)
    return f"Processed: {data}"

Authentication setup

认证设置

python
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider

auth = BearerAuthProvider(
    jwks_uri="https://your-provider/.well-known/jwks.json",
    audience="your-api",
    issuer="https://your-provider/"
)

mcp = FastMCP("SecureServer", auth=auth)
python
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider

auth = BearerAuthProvider(
    jwks_uri="https://your-provider/.well-known/jwks.json",
    audience="your-api",
    issuer="https://your-provider/"
)

mcp = FastMCP("SecureServer", auth=auth)

Key concepts

核心概念

Tools

工具

Functions exposed as executable capabilities for LLMs. Decorated with
@mcp.tool
. Support Pydantic validation, async, custom return types, and annotations (readOnlyHint, destructiveHint).
为LLM暴露的可执行功能,使用
@mcp.tool
装饰器标记。支持Pydantic验证、异步执行、自定义返回类型以及各类注解(readOnlyHint、destructiveHint)。

Resources & Templates

资源与模板

Static or dynamic data sources identified by URIs. Resources use fixed URIs (
data://config
), templates use parameterized URIs (
users://{id}/profile
). Support MIME types, annotations, and wildcard parameters.
由URI标识的静态或动态数据源。资源使用固定URI(如
data://config
),模板使用参数化URI(如
users://{id}/profile
)。支持MIME类型、注解和通配符参数。

Context

上下文

The
Context
object provides access to MCP features within tools/resources: logging, progress reporting, resource access, LLM sampling, user elicitation, and session state.
Context
对象为工具/资源内部提供MCP功能的访问入口:日志记录、进度报告、资源访问、LLM采样、用户触发以及会话状态管理。

Dependency Injection

依赖注入

Inject values into tool/resource functions using
Depends()
. Supports HTTP requests, access tokens, custom dependencies, and generator-based cleanup patterns.
使用
Depends()
向工具/资源函数注入值。支持HTTP请求、访问令牌、自定义依赖项以及基于生成器的清理模式。

Providers

提供者

Control where components come from.
LocalProvider
(default, decorator-based),
FileSystemProvider
(load from Python files on disk),
SkillsProvider
(packaged bundles), or custom providers.
控制组件的来源。包括
LocalProvider
(默认,基于装饰器)、
FileSystemProvider
(从磁盘上的Python文件加载)、
SkillsProvider
(打包的组件包)或自定义提供者。

Authentication & Authorization

认证与授权

Multiple auth patterns: token verification (JWT, JWKS), OAuth proxy, OIDC proxy, remote OAuth, and full OAuth server. Authorization via scopes on components and middleware.
多种认证模式:令牌验证(JWT、JWKS)、OAuth代理、OIDC代理、远程OAuth以及完整的OAuth服务器。通过组件上的范围和中间件实现授权。

Middleware

中间件

Intercept and modify requests/responses. Built-in middleware for rate limiting, error handling, logging, and response size limits. Custom middleware via
@mcp.middleware
.
拦截并修改请求/响应。内置中间件支持限流、错误处理、日志记录和响应大小限制。可通过
@mcp.middleware
创建自定义中间件。

Using the references

参考文档使用

Detailed documentation is organized in the
references/
folder:
详细文档组织在
references/
目录下:

Getting Started

入门指南

  • getting-started/installation.md - Install FastMCP, optional dependencies, verify setup
  • getting-started/upgrade-guide.md - Migrate from FastMCP 2.x to 3.0
  • getting-started/quickstart.md - First server, tools, resources, prompts, running
  • getting-started/installation.md - FastMCP安装、可选依赖配置、环境验证
  • getting-started/upgrade-guide.md - 从FastMCP 2.x升级到3.0版本的指南
  • getting-started/quickstart.md - 第一个服务器、工具、资源、提示词的创建与启动

Server

服务器

  • server/server-class.md - FastMCP server configuration, transport options, tag filtering
  • server/tools.md - Tool decorator, parameters, validation, return types, annotations
  • server/resources-and-templates.md - Resources, templates, URIs, wildcards, MIME types
  • server/server-class.md - FastMCP服务器配置、传输选项、标签过滤
  • server/tools.md - 工具装饰器、参数、验证、返回类型、注解
  • server/resources-and-templates.md - 资源、模板、URI、通配符、MIME类型

Context

上下文

  • context/mcp-context.md - Context object, logging, progress, resource access, sampling
  • context/background-tasks.md - Long-running operations with task support
  • context/dependency-injection.md - Depends(), custom deps, HTTP request, access tokens
  • context/user-elicitation.md - Request structured input from users during execution
  • context/mcp-context.md - Context对象、日志、进度、资源访问、采样
  • context/background-tasks.md - 支持后台任务的长时运行操作
  • context/dependency-injection.md - Depends()、自定义依赖、HTTP请求、访问令牌
  • context/user-elicitation.md - 在执行过程中向用户请求结构化输入

Features

功能特性

  • features/icons.md - Custom icons for tools, resources, prompts, and servers
  • features/lifespans.md - Server lifecycle management and startup/shutdown hooks
  • features/client-logging.md - Send log messages to MCP clients
  • features/middleware.md - Request/response pipeline, built-in and custom middleware
  • features/pagination.md - Paginate large component lists
  • features/progress-reporting.md - Report progress for long-running operations
  • features/sampling.md - Request LLM completions from the client
  • features/storage-backends.md - Memory, file, and Redis storage for caching and tokens
  • features/opentelemetry.md - Distributed tracing and observability
  • features/versioning.md - Version components and filter by version ranges
  • features/icons.md - 为工具、资源、提示词和服务器设置自定义图标
  • features/lifespans.md - 服务器生命周期管理与启动/关闭钩子
  • features/client-logging.md - 向MCP客户端发送日志消息
  • features/middleware.md - 请求/响应管道、内置与自定义中间件
  • features/pagination.md - 对大型组件列表进行分页
  • features/progress-reporting.md - 为长时运行操作报告进度
  • features/sampling.md - 向客户端请求LLM补全结果
  • features/storage-backends.md - 内存、文件和Redis存储,用于缓存和令牌管理
  • features/opentelemetry.md - 分布式追踪与可观测性
  • features/versioning.md - 组件版本管理与版本范围过滤

Authentication

认证

  • authentication/token-verification.md - JWT, JWKS, introspection, static keys, custom
  • authentication/remote-oauth.md - Delegate auth to upstream OAuth provider
  • authentication/oauth-proxy.md - Full OAuth proxy with PKCE, client management
  • authentication/oidc-proxy.md - OpenID Connect proxy with auto-discovery
  • authentication/full-oauth-server.md - Complete built-in OAuth server
  • authentication/token-verification.md - JWT、JWKS、内省、静态密钥、自定义验证
  • authentication/remote-oauth.md - 将认证委托给上游OAuth提供者
  • authentication/oauth-proxy.md - 完整的OAuth代理,支持PKCE、客户端管理
  • authentication/oidc-proxy.md - OpenID Connect代理,支持自动发现
  • authentication/full-oauth-server.md - 完整的内置OAuth服务器

Authorization

授权

  • authorization.md - Scope-based access control, middleware authorization, patterns
  • authorization.md - 基于范围的访问控制、中间件授权、实现模式

Providers

提供者

  • providers/local.md - Default provider, decorator-based component registration
  • providers/filesystem.md - Load components from Python files on disk
  • providers/skills.md - Package and distribute component bundles
  • providers/custom.md - Build custom providers for any component source
  • providers/local.md - 默认提供者,基于装饰器的组件注册
  • providers/filesystem.md - 从磁盘上的Python文件加载组件
  • providers/skills.md - 打包与分发组件包
  • providers/custom.md - 为任意组件源构建自定义提供者

Version history

版本历史

v1.0.0 (February 2026)
  • Initial release covering FastMCP 3.0 (release candidate)
  • 30 reference files across 7 categories
  • Complete coverage of tools, resources, context, auth, providers, and features
v1.0.0(2026年2月)
  • 初始版本,覆盖FastMCP 3.0(候选发布版)
  • 7个分类下共30份参考文档
  • 完整覆盖工具、资源、上下文、认证、提供者和功能特性