# https://github.com/tadata-org/fastapi_mcp 项目说明书

生成时间：2026-05-17 18:19:42 UTC

## 目录

- [FastAPI-MCP Home](#home)
- [System Architecture](#architecture)
- [Installation](#installation)
- [Quickstart Guide](#quickstart)
- [Examples Overview](#examples)
- [Authentication Overview](#auth-overview)
- [OAuth Authentication](#auth-oauth)
- [Endpoint Filtering and Selection](#endpoint-filtering)
- [Tool Naming and Schema](#tool-naming)
- [Transport Configuration](#transport-config)
- [Deployment Options](#deployment)
- [Dynamic Tool Registration](#dynamic-registration)

<a id='home'></a>

## FastAPI-MCP Home

### 相关页面

相关主题：[System Architecture](#architecture), [Quickstart Guide](#quickstart), [Installation](#installation)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)
- [fastapi_mcp/__init__.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/__init__.py)
- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)
- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)
</details>

# FastAPI-MCP Home

## Overview

FastAPI-MCP is a bridge library that converts FastAPI applications into MCP (Model Context Protocol) servers with minimal configuration. It allows developers to expose their existing FastAPI endpoints as MCP tools, enabling AI assistants to interact with FastAPI services through the MCP protocol.

资料来源：[README.md]()

## Key Features

| Feature | Description |
|---------|-------------|
| **Authentication Built-in** | Uses existing FastAPI dependencies for auth |
| **FastAPI-Native** | Not just another OpenAPI → MCP converter |
| **Zero/Minimal Configuration** | Point it at your FastAPI app and it works |
| **Schema Preservation** | Maintains request and response model schemas |
| **Documentation Preservation** | Keeps endpoint documentation from Swagger |
| **Flexible Deployment** | Mount MCP servers separately or with the API |

资料来源：[README.md]()

## Requirements

- Python 3.10+ (Recommended 3.12)
- `uv` package manager

资料来源：[README.md]()

## Installation

The package can be installed using `uv`:

```bash
uv add fastapi-mcp
```

For development dependencies:

```bash
uv add --group dev <package-name>
```

资料来源：[CONTRIBUTING.md]()

## Quick Start

The simplest way to use FastAPI-MCP is to create an instance and mount it to your FastAPI app:

```python
from examples.shared.apps.items import app  # Your FastAPI app
from fastapi_mcp import FastApiMCP

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

After mounting, your MCP server will be available at `/mcp` endpoint by default.

资料来源：[examples/01_basic_usage_example.py]()

## Architecture

### High-Level Architecture

```mermaid
graph TD
    A[FastAPI Application] --> B[FastApiMCP]
    B --> C[MCP Tools]
    B --> D[OpenAPI Schema]
    C --> E[AI Assistant]
    E --> F[MCP Protocol]
    F --> C
    G[Authentication] --> B
```

### Component Overview

The FastAPI-MCP library consists of the following key components:

| Component | File | Purpose |
|-----------|------|---------|
| `FastApiMCP` | `fastapi_mcp/__init__.py` | Main class for creating MCP servers from FastAPI apps |
| `AuthConfig` | `fastapi_mcp/types.py` | Configuration for MCP authentication |
| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata |
| Tool Conversion | `fastapi_mcp/openapi/convert.py` | Converts OpenAPI schemas to MCP tools |

资料来源：[fastapi_mcp/types.py]()
资料来源：[fastapi_mcp/server.py]()

## Configuration Options

### FastApiMCP Constructor Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `app` | FastAPI | Required | The FastAPI application instance |
| `name` | str | `"fastapi-mcp"` | MCP server name |
| `description` | str | `None` | MCP server description |
| `describe_all_responses` | bool | `False` | Include all possible response schemas |
| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |
| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client for API calls |
| `include_operations` | List[str] | `None` | Operation IDs to include |
| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |
| `include_tags` | List[str] | `None` | Tags to include |
| `exclude_tags` | List[str] | `None` | Tags to exclude |
| `auth_config` | AuthConfig | `None` | Authentication configuration |
| `headers` | List[str] | `["authorization"]` | Headers to forward |

资料来源：[fastapi_mcp/server.py]()

### Mounting Options

The MCP server can be mounted using `mount_http()`:

```python
mcp.mount_http(mount_path="/custom-mcp-path")
```

Default mount path is `/mcp`.

资料来源：[fastapi_mcp/server.py]()

## Endpoint Filtering

FastAPI-MCP supports filtering which endpoints are exposed as MCP tools through operation IDs and tags.

### Filtering Rules

- Cannot use both `include_operations` and `exclude_operations` simultaneously
- Cannot use both `include_tags` and `exclude_tags` simultaneously
- Can combine operation filtering with tag filtering (greedy approach)
- Endpoints matching either criteria will be included when combining filters

资料来源：[examples/03_custom_exposed_endpoints_example.py]()

### Filtering Examples

```python
from fastapi_mcp import FastApiMCP

# Include specific operation IDs
mcp1 = FastApiMCP(
    app,
    include_operations=["get_item", "list_items"]
)

# Exclude specific operation IDs
mcp2 = FastApiMCP(
    app,
    exclude_operations=["create_item", "update_item", "delete_item"]
)

# Include specific tags
mcp3 = FastApiMCP(
    app,
    include_tags=["items"]
)

# Combine filters (include mode)
mcp4 = FastApiMCP(
    app,
    include_operations=["delete_item"],
    include_tags=["search"],
)

# Mount with different paths
mcp1.mount_http(mount_path="/filtered-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py]()

### Internal Filtering Logic

The `_filter_tools` method processes filtering based on operation IDs and tags:

```mermaid
graph TD
    A[Tools List] --> B{Any Filters Set?}
    B -->|No| Z[Return All Tools]
    B -->|Yes| C[Build Operations by Tag Map]
    C --> D{Operation ID Filter?}
    D -->|Include| E[Keep Matching Operations]
    D -->|Exclude| F[Remove Matching Operations]
    E --> G{Tag Filter?}
    F --> G
    G -->|Include Tags| H[Keep Matching Tags]
    G -->|Exclude Tags| I[Remove Matching Tags]
    H --> J[Return Filtered Tools]
    I --> J
```

资料来源：[fastapi_mcp/server.py]()

## Authentication Configuration

FastAPI-MCP provides built-in support for MCP authentication using OAuth 2.0.

### AuthConfig Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `version` | Literal["2025-03-26"] | `"2025-03-26"` | MCP spec version |
| `dependencies` | Sequence[Depends] | `None` | FastAPI auth dependencies |
| `issuer` | str | `None` | OAuth 2.0 issuer URL |
| `oauth_metadata_url` | StrHttpUrl | `None` | OAuth metadata endpoint |
| `authorize_url` | StrHttpUrl | `None` | Authorization endpoint |
| `token_endpoint` | StrHttpUrl | `None` | Token endpoint |
| `revocation_endpoint` | StrHttpUrl | `None` | Token revocation endpoint |
| `jwks_uri` | StrHttpUrl | `None` | JWKS URI |
| `signing_key` | str | `None` | JWT signing key |

资料来源：[fastapi_mcp/types.py]()

### Token Passthrough Example

To reject requests without valid authorization tokens:

```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()
```

资料来源：[examples/08_auth_example_token_passthrough.py]()

### OAuth Configuration

The MCP client configuration for remote servers with auth headers:

```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}
```

资料来源：[examples/08_auth_example_token_passthrough.py]()

## Development Setup

### Local Development Environment

1. Fork the repository
2. Clone your fork:

```bash
git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp
git remote add upstream https://github.com/tadata-org/fastapi_mcp.git
```

3. Set up development environment:

```bash
uv sync
```

4. Install pre-commit hooks:

```bash
uv run pre-commit install
uv run pre-commit run
```

资料来源：[CONTRIBUTING.md]()

### Running Tests and Checks

```bash
# Run all tests
pytest

# Check code formatting and style
ruff check .
ruff format .

# Check types
mypy .
```

资料来源：[CONTRIBUTING.md]()

## Version History

| Version | Changes |
|---------|---------|
| Latest | Support for deploying MCP servers separately; endpoint filtering capabilities; `setup_server()` for dynamic routes |
| 0.1.8 | Removed unneeded dependency |
| 0.1.7 | Fixed syntax error (Issue #34) |
| 0.1.6 | Hid `handle_mcp_connection` tool (Issue #23) |

资料来源：[CHANGELOG.md]()

## Community

Join the [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg) to connect with other MCP enthusiasts, ask questions, and share experiences with FastAPI-MCP.

资料来源：[README.md]()

## License

MIT License. Copyright (c) 2024-2025 Tadata Inc.

资料来源：[README.md]()
资料来源：[README_zh-CN.md]()

---

<a id='architecture'></a>

## System Architecture

### 相关页面

相关主题：[FastAPI-MCP Home](#home), [Authentication Overview](#auth-overview), [Transport Configuration](#transport-config)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)
- [fastapi_mcp/transport/http.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/http.py)
- [fastapi_mcp/transport/sse.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/sse.py)
- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
</details>

# System Architecture

## Overview

FastAPI-MCP is a framework that automatically generates MCP (Model Context Protocol) servers from existing FastAPI applications. The architecture follows a **FastAPI-first approach**, meaning it integrates directly with FastAPI's ASGI interface rather than functioning as a separate HTTP service.

The primary design goals are:

- **Native dependencies**: Use familiar FastAPI `Depends()` for authentication
- **ASGI transport**: Communicate directly with the FastAPI app through its ASGI interface
- **Zero/minimal configuration**: Point it at a FastAPI app and it works immediately
- **Schema preservation**: Maintain request/response model schemas and documentation

资料来源：[README.md]()

## Core Components

### Component Architecture

```mermaid
graph TD
    subgraph "Client Layer"
        MCP_CLIENT[MCP Client<br/>Claude, etc.]
    end
    
    subgraph "FastAPI-MCP Core"
        MCP_SERVER[FastApiMCP Server]
        TRANSPORT[Transport Layer<br/>HTTP/SSE]
        CONVERT[OpenAPI Converter]
        FILTER[Tool Filter]
    end
    
    subgraph "FastAPI Application"
        FASTAPI[FastAPI App]
        DEPENDS[Dependencies<br/>Auth, etc.]
        ROUTES[Routes]
    end
    
    MCP_CLIENT <--> TRANSPORT
    MCP_SERVER --> TRANSPORT
    MCP_SERVER --> CONVERT
    MCP_SERVER --> FILTER
    TRANSPORT <--> FASTAPI
    FASTAPI --> DEPENDS
    FASTAPI --> ROUTES
```

### FastApiMCP Server

The `FastApiMCP` class is the main entry point for the library. It handles:

- MCP server initialization and lifecycle
- Tool discovery from FastAPI endpoints
- HTTP client operations for invoking endpoints
- Tool filtering based on operations and tags
- Mounting the MCP server to FastAPI applications

资料来源：[fastapi_mcp/server.py:1-100]()

### Transport Layer

FastAPI-MCP supports multiple transport mechanisms:

| Transport | Description | Use Case |
|-----------|-------------|----------|
| HTTP | Standard HTTP transport with JSON-RPC | Default transport |
| SSE | Server-Sent Events | Streaming responses |

The transport layer handles:
- Request/response serialization
- MCP protocol encoding/decoding
- Connection management

资料来源：[fastapi_mcp/transport/http.py](), [fastapi_mcp/transport/sse.py]()

### OpenAPI Schema Converter

The converter transforms FastAPI endpoint definitions into MCP tool schemas:

```mermaid
graph LR
    subgraph "FastAPI"
        OPERATION[Operation]
        PARAMETERS[Parameters]
        REQUEST_BODY[Request Body]
        RESPONSE[Response Schema]
    end
    
    subgraph "Conversion Process"
        VALIDATE[Validate Schema]
        ORGANIZE[Organize Params]
        BUILD[Build Tool Description]
    end
    
    subgraph "MCP Tool"
        TOOL[Tool Definition]
        INPUT_SCHEMA[Input Schema]
        DESCRIPTION[Description]
    end
    
    OPERATION --> VALIDATE
    PARAMETERS --> ORGANIZE
    REQUEST_BODY --> ORGANIZE
    VALIDATE --> BUILD
    ORGANIZE --> BUILD
    RESPONSE --> BUILD
    BUILD --> TOOL
    BUILD --> INPUT_SCHEMA
    BUILD --> DESCRIPTION
```

The converter processes:
- Path, query, and header parameters separately
- Request body schemas
- Response schemas with optional full schema inclusion
- Documentation from OpenAPI descriptions

资料来源：[fastapi_mcp/openapi/convert.py]()

## Data Flow

### Tool Invocation Flow

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant MCP as FastApiMCP Server
    participant Filter as Tool Filter
    participant Convert as OpenAPI Converter
    participant API as FastAPI App
    participant Auth as Auth Dependencies

    Client->>MCP: ListTools Request
    MCP->>Filter: Get filtered tools
    Filter->>Convert: Request tool definitions
    Convert->>API: Fetch OpenAPI schema
    API-->>Convert: OpenAPI spec
    Convert-->>Filter: Tool definitions
    Filter-->>MCP: Filtered tools
    MCP-->>Client: Tool list

    Client->>MCP: CallTool Request
    MCP->>Filter: Validate tool allowed
    Filter-->>MCP: Tool valid
    MCP->>API: Invoke endpoint (HTTP)
    API->>Auth: Run dependencies
    Auth-->>API: Auth OK
    API-->>MCP: Response
    MCP-->>Client: Tool result
```

### Parameter Organization

The converter organizes parameters into distinct categories:

| Category | OpenAPI Location | Processing |
|----------|------------------|------------|
| Path | `parameters[in=path]` | Required for route matching |
| Query | `parameters[in=query]` | Optional filters |
| Header | `parameters[in=header]` | Metadata forwarding |
| Body | `requestBody` | JSON payload |

资料来源：[fastapi_mcp/openapi/convert.py:50-80]()

## Tool Filtering System

### Filter Types

FastAPI-MCP provides granular control over which endpoints become MCP tools:

```mermaid
graph TD
    subgraph "Filter Configuration"
        INCL_OPS[include_operations]
        EXCL_OPS[exclude_operations]
        INCL_TAGS[include_tags]
        EXCL_TAGS[exclude_tags]
    end
    
    subgraph "Operations Index"
        OPS_BY_TAG[Operations by Tag]
        OPS_BY_ID[Operations by ID]
    end
    
    INCL_OPS --> OPS_BY_ID
    EXCL_OPS --> OPS_BY_ID
    INCL_TAGS --> OPS_BY_TAG
    EXCL_TAGS --> OPS_BY_TAG
```

### Filter Rules

| Filter Type | Description | Mutual Exclusion |
|-------------|-------------|-------------------|
| `include_operations` | Whitelist specific operation IDs | Cannot use with `exclude_operations` |
| `exclude_operations` | Blacklist specific operation IDs | Cannot use with `include_operations` |
| `include_tags` | Whitelist endpoints by tag | Cannot use with `exclude_tags` |
| `exclude_tags` | Blacklist endpoints by tag | Cannot use with `include_tags` |

**Greedy Matching**: When combining operation and tag filters, endpoints matching either criteria are included.

资料来源：[fastapi_mcp/server.py:80-120](), [examples/03_custom_exposed_endpoints_example.py]()

## Authentication Architecture

### AuthConfig Structure

```python
class AuthConfig(BaseType):
    version: Literal["2025-03-26"]  # MCP spec version
    dependencies: Sequence[Depends]  # FastAPI auth dependencies
    issuer: Optional[str]  # OAuth issuer URL
    oauth_metadata_url: Optional[StrHttpUrl]  # OAuth metadata endpoint
    authorize_url: Optional[StrHttpUrl]  # OAuth authorization endpoint
```

### Authentication Flow

```mermaid
graph LR
    subgraph "Client"
        REQUEST[MCP Request]
        HEADER[Auth Header]
    end
    
    subgraph "FastAPI-MCP"
        FORWARD[Forward Headers]
        VALIDATE[Validate with Depends]
    end
    
    subgraph "FastAPI App"
        AUTH_DEP[Auth Dependency]
        PROTECTED[Protected Endpoint]
    end
    
    REQUEST --> HEADER
    HEADER --> FORWARD
    FORWARD --> VALIDATE
    VALIDATE --> AUTH_DEP
    AUTH_DEP --> PROTECTED
```

### Header Forwarding

By default, the `authorization` header is forwarded from MCP requests to FastAPI endpoint invocations. Additional headers can be configured:

```python
mcp = FastApiMCP(
    app,
    headers=["authorization", "x-custom-header"]
)
```

资料来源：[fastapi_mcp/types.py:100-150](), [examples/08_auth_example_token_passthrough.py]()

## Configuration Options

### FastApiMCP Constructor Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `app` | FastAPI | Required | FastAPI application instance |
| `name` | str | Required | MCP server name |
| `describe_all_responses` | bool | `False` | Include all possible response schemas |
| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |
| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client |
| `include_operations` | List[str] | `None` | Operation IDs to include |
| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |
| `include_tags` | List[str] | `None` | Tags to include |
| `exclude_tags` | List[str] | `None` | Tags to exclude |
| `auth_config` | AuthConfig | `None` | Authentication configuration |
| `headers` | List[str] | `["authorization"]` | Headers to forward |

资料来源：[fastapi_mcp/server.py:150-200]()

## Type System

### Core Types

```mermaid
classDiagram
    class BaseType {
        +model_config: ConfigDict
        +model_dump() dict
    }
    
    class HTTPRequestInfo {
        +method: str
        +path: str
        +headers: Dict
        +cookies: Dict
        +query_params: Dict
        +body: Any
    }
    
    class OAuthMetadata {
        +issuer: StrHttpUrl
        +authorization_endpoint: StrHttpUrl
        +token_endpoint: StrHttpUrl
        +scopes_supported: List[str]
    }
    
    class AuthConfig {
        +version: str
        +dependencies: Sequence
        +issuer: str
    }
    
    BaseType <|-- HTTPRequestInfo
    BaseType <|-- OAuthMetadata
    BaseType <|-- AuthConfig
```

### HTTPRequestInfo

Captures incoming HTTP request details for authentication and routing:

```python
class HTTPRequestInfo(BaseType):
    method: str           # HTTP method (GET, POST, etc.)
    path: str             # Request path
    headers: Dict[str, str]
    cookies: Dict[str, str]
    query_params: Dict[str, str]
    body: Any             # Request body
```

资料来源：[fastapi_mcp/types.py:30-50]()

## Deployment Models

### Integrated Deployment (Default)

The MCP server is mounted directly into the FastAPI application:

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app, name="My MCP")
mcp.mount_http()

# MCP available at /mcp endpoint
```

### Separate Deployment

FastAPI-MCP also supports running the MCP server separately from the original FastAPI application for advanced deployment scenarios.

资料来源：[README.md](), [fastapi_mcp/server.py]()

## HTTP Client Operations

### Supported Methods

| Method | Handler | Body Support | Query Support |
|--------|---------|--------------|---------------|
| GET | `client.get()` | No | Yes |
| POST | `client.post()` | Yes | Yes |
| PUT | `client.put()` | Yes | Yes |
| DELETE | `client.delete()` | No | Yes |
| PATCH | `client.patch()` | Yes | Yes |

The internal HTTP client executes requests to FastAPI endpoints:

```python
async def _make_request(
    method: str,
    path: str,
    query: Dict[str, Any],
    headers: Dict[str, str],
    body: Any
) -> httpx.Response:
    if method.lower() == "get":
        return await client.get(path, params=query, headers=headers)
    elif method.lower() == "post":
        return await client.post(path, params=query, headers=headers, json=body)
    # ... other methods
```

资料来源：[fastapi_mcp/server.py:30-60]()

## Summary

The FastAPI-MCP architecture provides a seamless bridge between FastAPI applications and the MCP protocol:

1. **Non-intrusive integration**: Mounts directly onto existing FastAPI apps
2. **Flexible filtering**: Fine-grained control over exposed tools
3. **Native auth**: Leverages FastAPI's dependency injection system
4. **Schema preservation**: Maintains OpenAPI documentation and type information
5. **Multiple transports**: Supports both HTTP and SSE for different use cases

The system is designed for zero-configuration use while providing extensive customization options for advanced scenarios.

---

<a id='installation'></a>

## Installation

### 相关页面

相关主题：[FastAPI-MCP Home](#home), [Quickstart Guide](#quickstart)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)
- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)
- [README_zh-CN.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README_zh-CN.md)
- [pyproject.toml](https://github.com/tadata-org/fastapi_mcp/blob/main/pyproject.toml) (implicitly referenced through workflow descriptions)
</details>

# Installation

This page provides comprehensive instructions for setting up the **fastapi-mcp** development environment, including prerequisites, installation methods, and post-installation configuration.

## Overview

The **fastapi-mcp** project enables bridging FastAPI applications with the Model Context Protocol (MCP). The installation process involves setting up the Python environment, configuring the `uv` package manager, and preparing development tools for code quality assurance.

资料来源：[README.md]()

## Prerequisites

Before installing fastapi-mcp, ensure your system meets the following requirements.

### System Requirements

| Requirement | Version | Description |
|-------------|---------|-------------|
| Python | 3.10+ | Minimum supported Python version |
| Python (Recommended) | 3.12 | Preferred Python version for best compatibility |
| uv | Latest | ASTRA's Python package manager |

资料来源：[README.md](), [CONTRIBUTING.md:17]()

### Installing uv

The project uses `uv` as its package manager. Install `uv` by following the official documentation:

```bash
# Installation command (refer to https://docs.astral.sh/uv/getting-started/installation/)
curl -LsSf https://astral.sh/uv/install.sh | sh
```

Alternatively, for pip users:

```bash
pip install uv
```

资料来源：[CONTRIBUTING.md:18]()

## Installation Methods

### For Users: Installing the Package

For end users who want to use fastapi-mcp as a dependency:

```bash
# Using uv
uv add fastapi-mcp

# Or using pip
pip install fastapi-mcp
```

### For Developers: Setting Up the Development Environment

For contributors setting up the local development environment:

```mermaid
graph TD
    A[Fork Repository] --> B[Clone Your Fork]
    B --> C[Add Upstream Remote]
    C --> D[uv sync]
    D --> E[Install Pre-commit Hooks]
    E --> F[Ready for Development]
```

#### Step 1: Fork and Clone

```bash
# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp

# Add the upstream remote
git remote add upstream https://github.com/tadata-org/fastapi_mcp.git
```

资料来源：[CONTRIBUTING.md:24-35]()

#### Step 2: Sync Dependencies

The `uv sync` command automatically creates and manages a virtual environment:

```bash
uv sync
```

This command will:
- Create a `.venv` directory with a virtual environment
- Install all runtime dependencies from `pyproject.toml`
- Install development dependencies (marked with `--group dev`)

资料来源：[CONTRIBUTING.md:37-43]()

#### Step 3: Install Pre-commit Hooks

Pre-commit hooks automatically run code quality checks before each commit:

```bash
# Install the hooks
uv run pre-commit install

# Run all hooks manually (optional, for verification)
uv run pre-commit run
```

资料来源：[CONTRIBUTING.md:45-51]()

## Running Commands

You have two options for executing commands within the development environment.

### Option 1: Activate the Virtual Environment

```bash
# On Unix/macOS
source .venv/bin/activate

# On Windows
.venv\Scripts\activate

# Then run commands directly
pytest
mypy .
ruff check .
ruff format .
```

### Option 2: Use uv run Prefix

```bash
# Without activating the environment
uv run pytest
uv run mypy .
uv run ruff check .
uv run ruff format .
```

资料来源：[CONTRIBUTING.md:53-75]()

## Adding Dependencies

### Runtime Dependencies

Packages needed to run the application:

```bash
uv add new-package
```

### Development Dependencies

Packages needed for development, testing, or CI:

```bash
uv add --group dev new-package
```

After adding dependencies:

1. Test that everything works with the new package
2. Commit both `pyproject.toml` and `uv.lock` files:

```bash
git add pyproject.toml uv.lock
git commit -m "Add new-package dependency"
```

资料来源：[CONTRIBUTING.md:77-92]()

## Code Quality Tools

The project enforces code quality using the following tools:

| Tool | Purpose | Command |
|------|---------|---------|
| **ruff** | Linting and formatting | `ruff check .` / `ruff format .` |
| **mypy** | Type checking | `mypy .` |
| **pytest** | Testing | `pytest` |
| **pre-commit** | Automated checks | `pre-commit run` |

资料来源：[CONTRIBUTING.md:94-104]()

### Running All Checks

Before submitting a pull request, ensure all checks pass:

```bash
# Format code
ruff format .

# Check code style
ruff check .

# Type checking
mypy .

# Run tests
pytest
```

## Quick Start Checklist

Use this checklist to verify your installation is complete:

- [ ] Python 3.10+ is installed (`python --version`)
- [ ] uv is installed (`uv --version`)
- [ ] Repository is forked and cloned
- [ ] `uv sync` completed successfully
- [ ] `uv run pre-commit install` executed
- [ ] `uv run pre-commit run` passes (or first commit triggers it)
- [ ] `uv run pytest` runs successfully
- [ ] `uv run mypy .` passes type checking

## Troubleshooting

### Common Issues

**Virtual environment not found**
```bash
uv sync
```

**Pre-commit hooks not running**
```bash
uv run pre-commit install
uv run pre-commit run --all-files
```

**Dependency conflicts**
```bash
uv sync --refresh
```

## Related Documentation

- [Contributing Guide](CONTRIBUTING.md) - Full development workflow
- [README](README.md) - Project overview and features
- [GitHub Repository](https://github.com/tadata-org/fastapi_mcp) - Source code

---

<a id='quickstart'></a>

## Quickstart Guide

### 相关页面

相关主题：[FastAPI-MCP Home](#home), [Examples Overview](#examples), [Endpoint Filtering and Selection](#endpoint-filtering)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)
- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)
- [examples/shared/setup.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/setup.py)
- [examples/02_full_schema_description_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/02_full_schema_description_example.py)
- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
</details>

# Quickstart Guide

This guide provides a comprehensive walkthrough for getting started with **FastAPI-MCP**, a library that seamlessly integrates FastAPI applications with the Model Context Protocol (MCP). It allows you to expose your FastAPI endpoints as MCP tools with minimal configuration.

## Prerequisites

Before getting started, ensure you have the following installed:

| Requirement | Version | Notes |
|-------------|---------|-------|
| Python | 3.10+ (Recommended 3.12) | The project uses modern Python features |
| uv | Latest | Package manager for dependency installation |

资料来源：[README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)

## Installation

Install FastAPI-MCP using uv:

```bash
uv add fastapi-mcp
```

For development setup with all dependencies:

```bash
git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp
uv sync
```

资料来源：[CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)

## Basic Usage

The simplest way to add an MCP server to your FastAPI application involves three steps:

### 1. Import FastApiMCP

```python
from fastapi_mcp import FastApiMCP
```

资料来源：[examples/01_basic_usage_example.py:1]()

### 2. Create the MCP Server Instance

Pass your FastAPI app to the `FastApiMCP` constructor:

```python
from examples.shared.apps.items import app  # Your FastAPI app
from examples.shared.setup import setup_logging

from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)
```

资料来源：[examples/01_basic_usage_example.py:1-9]()

### 3. Mount the MCP Server

Mount the MCP server to your FastAPI app using `mount_http()`:

```python
# Mount the MCP server to the FastAPI app
mcp.mount_http()
```

资料来源：[examples/01_basic_usage_example.py:12]()

### 4. Run the Server

Start the uvicorn server:

```python
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```

资料来源：[examples/01_basic_usage_example.py:15-18]()

## Complete Basic Example

Here is the full minimal example from `examples/01_basic_usage_example.py`:

```python
from examples.shared.apps.items import app  # The FastAPI app
from examples.shared.setup import setup_logging

from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```

资料来源：[examples/01_basic_usage_example.py:1-19]()

## Architecture Overview

```mermaid
graph TD
    A[FastAPI Application] --> B[FastApiMCP]
    B --> C[MCP Server]
    C --> D[HTTP Endpoint /mcp]
    D --> E[MCP Client]
    
    F[OpenAPI Schema] --> B
    B --> G[MCP Tools]
    
    style A fill:#e1f5ff
    style C fill:#fff3e0
    style D fill:#e8f5e9
```

## Enhanced Schema Description

By default, FastAPI-MCP provides concise tool descriptions. You can enhance the descriptions by enabling additional options:

```python
mcp = FastApiMCP(
    app,
    name="Item API MCP",
    description="MCP server for the Item API",
    describe_full_response_schema=True,  # Describe the full response JSON-schema
    describe_all_responses=True,         # Describe all possible responses, not just 2XX
)

mcp.mount_http()
```

资料来源：[examples/02_full_schema_description_example.py:1-18]()

## Filtering Exposed Endpoints

You can control which endpoints are exposed as MCP tools using operation IDs or tags:

### Filter by Operation IDs

```python
# Include specific operations
include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)
```

### Filter by Tags

```python
# Include endpoints with specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)

# Exclude endpoints with specific tags
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()

## Adding Authentication

FastAPI-MCP supports authentication by leveraging your existing FastAPI dependencies. Use the `AuthConfig` class to configure authentication:

```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

# Define your authentication scheme
token_auth_scheme = HTTPBearer()

# Create protected endpoint
@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

# Configure MCP with authentication
mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()
```

资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()

## Key Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `app` | FastAPI | Required | The FastAPI application instance |
| `name` | str | Auto-generated | Name of the MCP server |
| `description` | str | Auto-generated | Description of the MCP server |
| `describe_full_response_schema` | bool | False | Include full JSON schema for responses |
| `describe_all_responses` | bool | False | Include all response types, not just success |
| `include_operations` | List[str] | None | Operation IDs to include |
| `exclude_operations` | List[str] | None | Operation IDs to exclude |
| `include_tags` | List[str] | None | Tags to include |
| `exclude_tags` | List[str] | None | Tags to exclude |
| `auth_config` | AuthConfig | None | Authentication configuration |
| `headers` | List[str] | ["authorization"] | Headers to forward to tool invocations |

资料来源：[fastapi_mcp/server.py:1-100]()

## Running the Quickstart

To run the basic example:

```bash
# Navigate to the examples directory
cd examples

# Run the basic usage example
uv run python 01_basic_usage_example.py
```

Once running, the MCP server will be available at `http://localhost:8000/mcp`.

## Verification

After starting the server, you can verify it's working by:

1. Accessing the OpenAPI docs at `http://localhost:8000/docs`
2. Checking the MCP endpoint at `http://localhost:8000/mcp`

## Next Steps

- Explore [Authentication Examples](examples/08_auth_example_token_passthrough.py) for securing your MCP server
- Learn about [Custom Endpoint Filtering](examples/03_custom_exposed_endpoints_example.py) for granular control
- Review the [Full Schema Description](examples/02_full_schema_description_example.py) for detailed tool documentation

---

<a id='examples'></a>

## Examples Overview

### 相关页面

相关主题：[Quickstart Guide](#quickstart), [OAuth Authentication](#auth-oauth), [Deployment Options](#deployment), [Dynamic Tool Registration](#dynamic-registration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)
- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)
- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)
- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)
</details>

# Examples Overview

The `examples/` directory in the FastAPI-MCP repository provides a comprehensive collection of runnable examples demonstrating the library's capabilities. These examples serve as practical guides for developers learning how to integrate FastAPI applications with the MCP (Model Context Protocol) server infrastructure.

## Directory Structure

The examples directory follows a modular organization pattern:

```
examples/
├── README.md
├── 01_basic_usage_example.py
├── 02_multiple_apps_example.py
├── 03_custom_exposed_endpoints_example.py
├── 04_separate_server_example.py
├── 05_reregister_tools_example.py
├── 06_custom_tools_example.py
├── 07_external_app_example.py
├── 08_auth_example_token_passthrough.py
├── 09_auth_example_auth0.py
├── 10_standalone_server.py
└── shared/
    ├── apps/
    │   └── items.py
    └── setup.py
```

资料来源：[examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)

## Example Categories

### Category 1: Basic Integration

The foundational examples demonstrate core FastAPI-MCP functionality.

#### 01 - Basic Usage

This is the simplest possible integration demonstrating how to mount an MCP server onto a FastAPI application.

```python
from examples.shared.apps.items import app  # The FastAPI app
from examples.shared.setup import setup_logging
from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

**Key Components:**
| Component | Purpose |
|-----------|---------|
| `FastApiMCP(app)` | Creates MCP server instance bound to FastAPI app |
| `mcp.mount_http()` | Exposes MCP endpoint at `/mcp` path |
| `setup_logging()` | Configures logging for debugging |

资料来源：[examples/01_basic_usage_example.py:1-19](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)

### Category 2: Endpoint Filtering

These examples demonstrate how to control which FastAPI endpoints are exposed as MCP tools.

#### 03 - Custom Exposed Endpoints

The filtering system allows selective exposure of endpoints using operation IDs or tags.

**Filtering Rules:**
- Cannot use both `include_operations` and `exclude_operations` simultaneously
- Cannot use both `include_tags` and `exclude_tags` simultaneously
- Operation filtering can be combined with tag filtering (greedy approach)

```python
# Filter by including specific operation IDs
include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Filter by excluding specific operation IDs
exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)

# Filter by including specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:1-39](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)

**Filtering Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `include_operations` | `List[str]` | Operation IDs to include as MCP tools |
| `exclude_operations` | `List[str]` | Operation IDs to exclude from MCP tools |
| `include_tags` | `List[str]` | Tags to include as MCP tools |
| `exclude_tags` | `List[str]` | Tags to exclude from MCP tools |

资料来源：[fastapi_mcp/server.py:85-100](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)

### Category 3: Authentication Examples

FastAPI-MCP supports OAuth 2.0 authentication integration using FastAPI's dependency injection system.

#### 08 - Token Passthrough Authentication

This example demonstrates protecting endpoints using HTTP Bearer tokens passed through the MCP client.

**Configuration for MCP Client:**
```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    }
  }
}
```

**Server Implementation:**
```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)
mcp.mount_http()
```

资料来源：[examples/08_auth_example_token_passthrough.py:1-47](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)

#### 09 - Auth0 Integration

This example shows integration with Auth0 as an OAuth 2.0 provider, demonstrating the full OAuth flow setup.

```python
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="Auth0 Protected MCP",
    auth_config=AuthConfig(
        issuer="https://your-tenant.auth0.com",
        # Additional OAuth configuration
    ),
)
```

**AuthConfig Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `version` | `Literal["2025-03-26"]` | MCP spec version (currently only "2025-03-26") |
| `dependencies` | `Sequence[Depends]` | FastAPI dependencies for auth checking |
| `issuer` | `Optional[str]` | OAuth 2.0 server issuer URL |
| `oauth_metadata_url` | `Optional[StrHttpUrl]` | Full OAuth provider metadata endpoint URL |
| `authorize_url` | `Optional[StrHttpUrl]` | OAuth provider authorization endpoint |

资料来源：[examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py) and [fastapi_mcp/types.py:95-140](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)

### Category 4: Advanced Integration Patterns

#### 04 - Separate Server Example

Demonstrates running the MCP server as a standalone process, separate from the main FastAPI application.

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Create MCP server
mcp = FastApiMCP(
    app,
    name="Separate MCP Server",
    # Configuration options
)

# Run MCP as standalone server
if __name__ == "__main__":
    mcp.run(...)
```

资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)

#### 05 - Reregister Tools Example

Demonstrates dynamic tool reregistration, useful for applications where available tools may change at runtime.

```python
from fastapi_mcp import FastApiMCP

mcp = FastApiMCP(app)

# Initial registration
mcp.mount_http()

# Later, reregister tools
mcp.reregister_tools()
```

资料来源：[examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)

## Architecture Diagram

```mermaid
graph TD
    A[FastAPI Application] --> B[FastApiMCP Instance]
    B --> C[mount_http]
    B --> D[Separate Server]
    
    C --> E[MCP Endpoint /mcp]
    D --> F[Standalone MCP Server]
    
    E --> G[MCP Client]
    F --> G
    
    G --> H[Tool Invocations]
    H --> I[HTTP Requests to FastAPI]
    I --> A
    
    J[AuthConfig] --> B
    J --> K[OAuth 2.0 Flow]
    K --> L[Auth0 / OAuth Provider]
    
    M[Filtering Options] --> B
    M --> N[include_operations]
    M --> O[exclude_operations]
    M --> P[include_tags]
    M --> Q[exclude_tags]
```

## Common Setup Module

All examples share a common setup module that configures logging:

```python
from examples.shared.setup import setup_logging

setup_logging()
```

The shared items application provides a sample FastAPI app with CRUD operations for an `Item` model, used across multiple examples:

资料来源：[examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)

## Running Examples

### Using uv (Recommended)

```bash
# Install dependencies
uv sync

# Run an example
uv run python examples/01_basic_usage_example.py
```

### Using pre-commit hooks

```bash
uv run pre-commit install
uv run pre-commit run
```

资料来源：[CONTRIBUTING.md:1-30](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)

## Requirements Summary

| Requirement | Version | Notes |
|-------------|---------|-------|
| Python | 3.10+ | Recommended 3.12 |
| Package Manager | uv | Required for development |

资料来源：[README.md:45-48](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)

## Example Selection Guide

| Use Case | Recommended Example |
|----------|---------------------|
| First-time integration | 01_basic_usage_example.py |
| Selective endpoint exposure | 03_custom_exposed_endpoints_example.py |
| OAuth with existing tokens | 08_auth_example_token_passthrough.py |
| Auth0 integration | 09_auth_example_auth0.py |
| Standalone MCP server | 04_separate_server_example.py |
| Dynamic tool updates | 05_reregister_tools_example.py |

---

<a id='auth-overview'></a>

## Authentication Overview

### 相关页面

相关主题：[System Architecture](#architecture), [OAuth Authentication](#auth-oauth)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)
- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)
</details>

# Authentication Overview

FastAPI-MCP provides a built-in authentication system that leverages your existing FastAPI dependencies. This approach eliminates the need to configure a separate authentication mechanism and seamlessly integrates with MCP clients that support OAuth 2.0 flows.

## Architecture Overview

The authentication system in FastAPI-MCP is built around the MCP specification version `2025-03-26`. It supports two primary authentication modes:

1. **Token Passthrough** - Validates bearer tokens using FastAPI dependencies
2. **OAuth 2.0 Flow** - Full OAuth 2.0 authorization code flow with proxy endpoints

```mermaid
graph TD
    A[MCP Client] -->|HTTP Request| B[FastAPI-MCP Server]
    B -->|Validate| C{FastAPI Dependencies}
    C -->|Valid| D[Tool Execution]
    C -->|Invalid| E[401 Unauthorized]
    
    F[OAuth Flow] -->|Token Request| G[OAuth Provider]
    G -->|Access Token| F
    
    B -->|Proxy| H[OAuth Metadata Endpoint]
    B -->|Proxy| I[Authorization Endpoint]
```

## Core Data Models

### AuthConfig

The `AuthConfig` class is the central configuration model for authentication in FastAPI-MCP.

资料来源：[fastapi_mcp/types.py:88-147]()

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `version` | `Literal["2025-03-26"]` | `"2025-03-26"` | MCP spec version for authorization |
| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for authentication checks |
| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata instead of proxy setup |
| `issuer` | `str` | `None` | OAuth 2.0 server issuer URL |
| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |
| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint URL |
| `token_endpoint` | `StrHttpUrl` | `None` | OAuth provider's token endpoint URL |
| `metadata_path` | `str` | `"/.well-known/oauth-authorization-server"` | Path to serve OAuth metadata |
| `client_id` | `str` | `None` | OAuth client ID |
| `client_secret` | `str` | `None` | OAuth client secret |
| `audience` | `str` | `None` | Expected audience claim in tokens |
| `setup_proxies` | `bool` | `False` | Whether to set up OAuth proxy endpoints |
| `setup_fake_dynamic_registration` | `bool` | `False` | Setup fake dynamic client registration endpoint |
| `default_scope` | `str` | `"openid profile email"` | Default OAuth scope |

### OAuthMetadata

Represents OAuth 2.0 Server Metadata according to RFC 8414.

资料来源：[fastapi_mcp/types.py:33-86]()

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `issuer` | `StrHttpUrl` | Yes | Authorization server's issuer identifier (HTTPS URL) |
| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |
| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |
| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes |
| `response_types_supported` | `List[str]` | No | Supported response types |
| `grant_types_supported` | `List[str]` | No | Supported grant types |

## Authentication Setup Flow

The authentication system is initialized during `FastApiMCP` construction. The `_setup_auth_2025_03_26()` method handles the setup based on the configuration.

资料来源：[fastapi_mcp/server.py:150-190]()

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as FastAPI-MCP
    participant Proxy as OAuth Proxies
    participant Provider as OAuth Provider
    
    Note over Server: AuthConfig provided
    Server->>Server: _setup_auth_2025_03_26()
    
    alt Custom OAuth Metadata
        Server->>Proxy: setup_oauth_custom_metadata()
        Note over Proxy: Serve custom metadata at metadata_path
    else Setup Proxies
        Server->>Proxy: setup_oauth_metadata_proxy()
        Server->>Proxy: setup_oauth_authorize_proxy()
        
        alt Fake Dynamic Registration
            Server->>Proxy: setup_oauth_fake_dynamic_register_endpoint()
        end
    end
    
    Client->>Server: Request with Auth Header
    Server->>Server: Run dependencies
    alt Dependencies Pass
        Server->>Server: Execute Tool
    else Dependencies Fail
        Server-->>Client: 401 Unauthorized
    end
```

## Proxy Endpoints

FastAPI-MCP automatically sets up proxy endpoints when `setup_proxies=True` is configured.

资料来源：[fastapi_mcp/auth/proxy.py:1-50]()

### Metadata Proxy

Serves OAuth 2.0 server metadata. When `oauth_metadata_url` is not provided, it constructs the URL from `issuer` and `metadata_path`.

```python
setup_oauth_metadata_proxy(
    app=self.fastapi,
    metadata_url=f"{issuer}{metadata_path}",
    path="/.well-known/oauth-authorization-server",
    register_path="/oauth/register"  # if setup_fake_dynamic_registration is True
)
```

### Authorization Proxy

Proxies authorization requests to the OAuth provider, with fallback handling for missing parameters.

资料来源：[fastapi_mcp/auth/proxy.py:80-140]()

| Parameter | Purpose |
|-----------|---------|
| `client_id` | Default client ID when not provided by client |
| `authorize_url` | Target OAuth authorization endpoint |
| `audience` | Default audience when not specified |
| `default_scope` | Default scope (`openid profile email`) |

### Fake Dynamic Registration

For development or testing environments, a fake dynamic client registration endpoint can be enabled.

```python
setup_oauth_fake_dynamic_register_endpoint(
    app=self.fastapi,
    client_id="test-client-id",
    client_secret="test-client-secret"
)
```

## Usage Examples

### Token Passthrough Authentication

The simplest form of authentication uses FastAPI dependencies to validate bearer tokens.

资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()

```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)]
    )
)

mcp.mount_http()
```

### Auth0 Integration

Full OAuth 2.0 flow with Auth0 as the identity provider.

资料来源：[examples/09_auth_example_auth0.py:1-60]()

```python
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="MCP With Auth0",
    auth_config=AuthConfig(
        issuer=f"https://{settings.auth0_domain}/",
        authorize_url=f"https://{settings.auth0_domain}/authorize",
        oauth_metadata_url=settings.auth0_oauth_metadata_url,
        audience=settings.auth0_audience,
        client_id=settings.auth0_client_id,
        client_secret=settings.auth0_client_secret,
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
    )
)

mcp.mount_http()
```

## MCP Client Configuration

For token passthrough authentication, configure your MCP client to include the authorization header.

```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}
```

## Key Implementation Details

### Dependency Injection

Authentication is enforced through standard FastAPI dependency injection. Any `Depends()` callable that raises `HTTPException(401)` or `HTTPException(403)` will trigger the OAuth flow in supporting clients.

资料来源：[fastapi_mcp/types.py:103-130]()

```python
async def authenticate_request(request: Request, token: str = Depends(oauth2_scheme)):
    payload = verify_token(request, token)
    if payload is None:
        raise HTTPException(status_code=401, detail="Unauthorized")
    return payload
```

### Metadata Serialization

The `OAuthMetadata` model uses special serialization to ensure compatibility with OAuth clients:

- `exclude_unset=True` - Never include unset fields
- `exclude_none=True` - Never include fields with `None` values

资料来源：[fastapi_mcp/types.py:69-86]()

### Base Type Configuration

All authentication-related models inherit from `BaseType` which configures:

- `extra="ignore"` - Silently ignore unexpected fields
- `arbitrary_types_allowed=True` - Allow complex type annotations

## Workflow Summary

| Step | Component | Action |
|------|-----------|--------|
| 1 | `FastApiMCP.__init__()` | Accept `AuthConfig` parameter |
| 2 | `setup_server()` | Call `_setup_auth_2025_03_26()` |
| 3 | Proxy Setup | Register endpoints based on config |
| 4 | Request Handling | Dependencies validate tokens |
| 5 | Tool Execution | Proceed if authentication succeeds |

The authentication system is designed to be non-intrusive, requiring minimal configuration while providing full OAuth 2.0 compatibility for production deployments.

---

<a id='auth-oauth'></a>

## OAuth Authentication

### 相关页面

相关主题：[Authentication Overview](#auth-overview), [Deployment Options](#deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)
- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
</details>

# OAuth Authentication

## Overview

FastAPI-MCP provides built-in OAuth 2.0 authentication support that integrates seamlessly with your existing FastAPI dependencies. The authentication system follows the MCP (Model Context Protocol) specification version 2025-03-26, enabling MCP clients to authenticate requests using OAuth 2.0 flows.

The authentication layer serves three primary purposes:

1. **Metadata Discovery** - Exposes OAuth server metadata at standardized endpoints
2. **Authorization Flow** - Proxies authorization requests to your OAuth provider
3. **Dynamic Client Registration** - Provides a fake dynamic client registration endpoint for clients that require it

## Architecture

The OAuth authentication system consists of several coordinated components that work together to bridge MCP clients with your OAuth provider.

```mermaid
graph TD
    subgraph "MCP Client"
        A[MCP Client] -->|OAuth Request| B[MCP Server]
    end
    
    subgraph "FastAPI-MCP Server"
        B --> C{Auth Dependencies Check}
        C -->|Valid Token| D[MCP Tool Handler]
        C -->|Invalid/Missing| E[401 Unauthorized]
        C -->|Trigger OAuth| F[OAuth Proxy Endpoints]
        
        F --> G[Metadata Proxy<br/>/.well-known/oauth-authorization-server]
        F --> H[Authorize Proxy<br/>/oauth/authorize]
        F --> I[Dynamic Registration<br/>/oauth/register]
    end
    
    subgraph "External OAuth Provider"
        G -->|Fetch & Transform| J[Provider Metadata]
        H -->|Redirect| K[Provider Authorization]
        I -->|Fake Response| L[Client Credentials]
    end
```

### Core Components

| Component | File | Purpose |
|-----------|------|---------|
| `AuthConfig` | `fastapi_mcp/types.py` | Configuration container for OAuth settings |
| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata model (RFC 8414) |
| `setup_oauth_custom_metadata()` | `fastapi_mcp/auth/proxy.py` | Serves custom OAuth metadata |
| `setup_oauth_metadata_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies external OAuth metadata with modifications |
| `setup_oauth_authorize_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies authorization endpoint |
| `setup_oauth_fake_dynamic_register_endpoint()` | `fastapi_mcp/auth/proxy.py` | Provides fake client registration |

## AuthConfig Specification

The `AuthConfig` class is the central configuration point for OAuth authentication in FastAPI-MCP.

资料来源：[fastapi_mcp/types.py:127-217]()

### Configuration Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `version` | `Literal["2025-03-26"]` | `"2025-03-26"` | MCP spec version for authorization |
| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for auth verification |
| `issuer` | `str` | `None` | OAuth provider issuer URL |
| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |
| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint |
| `audience` | `str` | `None` | Default audience for requests |
| `default_scope` | `str` | `"openid profile email"` | Default OAuth scopes |
| `client_id` | `str` | `None` | Default client ID |
| `client_secret` | `str` | `None` | Client secret for dynamic registration |
| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata object |
| `setup_proxies` | `bool` | `False` | Enable OAuth proxy setup |
| `setup_fake_dynamic_registration` | `bool` | `False` | Enable fake dynamic client registration |
| `metadata_path` | `str` | `"/.well-known/oauth-authorization-server"` | Path for metadata endpoint |

### Example Configuration

```python
from fastapi import Depends
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        issuer="https://your-tenant.auth0.com/",
        authorize_url="https://your-tenant.auth0.com/authorize",
        oauth_metadata_url="https://your-tenant.auth0.com/.well-known/openid-configuration",
        audience="https://your-tenant.auth0.com/api/v2/",
        client_id="your-client-id",
        client_secret="your-client-secret",
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
        setup_fake_dynamic_registration=True,
    ),
)
```

资料来源：[examples/09_auth_example_auth0.py:1-50]()

## OAuthMetadata Model

The `OAuthMetadata` class represents OAuth 2.0 Authorization Server Metadata as defined in RFC 8414.

资料来源：[fastapi_mcp/types.py:36-118]()

### Metadata Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `issuer` | `StrHttpUrl` | Yes | Authorization server issuer identifier (https URL) |
| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |
| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |
| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes (default: `["openid", "profile", "email"]`) |
| `response_types_supported` | `List[str]` | No | Supported response types (default: `["code"]`) |
| `grant_types_supported` | `List[str]` | No | Supported grant types (default: `["authorization_code", "client_credentials"]`) |
| `token_endpoint_auth_methods_supported` | `List[str]` | No | Client auth methods (default: `["none"]`) |
| `code_challenge_methods_supported` | `List[str]` | No | PKCE challenge methods (default: `["S256"]`) |
| `registration_endpoint` | `StrHttpUrl` | No | Client registration endpoint URL |

## Authentication Dependencies

FastAPI-MCP leverages FastAPI's dependency injection system for authentication checks. Dependencies must raise 401 or 403 errors when requests are unauthorized, which triggers the MCP client to initiate an OAuth flow.

资料来源：[fastapi_mcp/types.py:149-174]()

### Dependency Implementation Pattern

```python
from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

security = HTTPBearer()

async def verify_auth(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)):
    """Verify the bearer token and return user information."""
    token = credentials.credentials
    
    # Validate token with your OAuth provider
    payload = verify_token(token)
    
    if payload is None:
        raise HTTPException(
            status_code=401,
            detail="Unauthorized",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return payload

# Usage with FastAPI-MCP
mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(dependencies=[Depends(verify_auth)]),
)
```

资料来源：[fastapi_mcp/types.py:155-172]()

## OAuth Proxy Setup Functions

### setup_oauth_custom_metadata()

Serves custom OAuth metadata provided directly in the `AuthConfig`.

资料来源：[fastapi_mcp/auth/proxy.py:50-75]()

```python
def setup_oauth_custom_metadata(
    app: FastAPI,
    auth_config: AuthConfig,
    metadata: OAuthMetadataDict,
    include_in_schema: bool = False,
) -> None:
    """
    Serve custom metadata at the path specified in auth_config.metadata_path.
    """
    auth_config = AuthConfig.model_validate(auth_config)
    metadata = OAuthMetadata.model_validate(metadata)

    @app.get(
        auth_config.metadata_path,
        response_model=OAuthMetadata,
        response_model_exclude_unset=True,
        response_model_exclude_none=True,
        include_in_schema=include_in_schema,
        operation_id="oauth_custom_metadata",
    )
    async def oauth_metadata_proxy():
        return metadata
```

### setup_oauth_metadata_proxy()

Proxies an external OAuth provider's metadata endpoint while modifying specific fields.

资料来源：[fastapi_mcp/auth/proxy.py:78-135]()

```python
def setup_oauth_metadata_proxy(
    app: FastAPI,
    metadata_url: str,
    path: str = "/.well-known/oauth-authorization-server",
    authorize_path: str = "/oauth/authorize",
    register_path: Optional[str] = None,
    include_in_schema: bool = False,
) -> None:
    """
    Fetch OAuth metadata from provider and override specific endpoints.
    """
    @app.get(
        path,
        response_model=OAuthMetadata,
        response_model_exclude_unset=True,
        response_model_exclude_none=True,
        include_in_schema=include_in_schema,
        operation_id="oauth_metadata_proxy",
    )
    async def oauth_metadata_proxy(request: Request):
        base_url = str(request.base_url).rstrip("/")

        async with httpx.AsyncClient() as client:
            response = await client.get(metadata_url)
            if response.status_code != 200:
                raise HTTPException(
                    status_code=502,
                    detail="Failed to fetch OAuth metadata",
                )
            oauth_metadata = response.json()

        # Override registration endpoint if provided
        if register_path:
            oauth_metadata["registration_endpoint"] = f"{base_url}{register_path}"

        # Replace authorization endpoint with our proxy
        oauth_metadata["authorization_endpoint"] = f"{base_url}{authorize_path}"

        return OAuthMetadata.model_validate(oauth_metadata)
```

### setup_oauth_authorize_proxy()

Creates a proxy for the OAuth provider's authorization endpoint.

资料来源：[fastapi_mcp/auth/proxy.py:138-210]()

```python
def setup_oauth_authorize_proxy(
    app: FastAPI,
    client_id: str,
    authorize_url: Optional[StrHttpUrl] = None,
    audience: Optional[str] = None,
    default_scope: str = "openid profile email",
    path: str = "/oauth/authorize",
) -> None:
    """
    Proxy authorization requests to the OAuth provider.
    """
    @app.get(
        path,
        response_class=RedirectResponse,
        operation_id="oauth_authorize_proxy",
    )
    async def oauth_authorize_proxy(request: Request, redirect_uri: str):
        params = {
            "client_id": client_id,
            "redirect_uri": redirect_uri,
            "response_type": "code",
            "scope": default_scope,
        }
        
        if audience:
            params["audience"] = audience
            
        # Redirect to actual OAuth provider
        query = urlencode(params)
        return f"{authorize_url}?{query}"
```

## Authorization Flow

### MCP Spec Version 2025-03-26 Setup

The auth setup is triggered in the `FastApiMCP` initialization flow.

资料来源：[fastapi_mcp/server.py:1-50]()

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant FastAPI as FastAPI App
    participant Proxy as OAuth Proxies
    participant Provider as OAuth Provider

    Client->>FastAPI: MCP Request with Bearer Token
    FastAPI->>FastAPI: Run Auth Dependencies
    alt Token Invalid or Missing
        FastAPI-->>Client: 401 Unauthorized
        Client->>Proxy: Discover OAuth Metadata
        Proxy->>Provider: Fetch Metadata
        Provider-->>Proxy: OAuth Metadata
        Proxy-->>Client: Modified Metadata
        Client->>Proxy: Authorization Request
        Proxy->>Provider: Redirect to /authorize
        Provider-->>Client: Authorization Code
        Client->>Proxy: Token Request
        Proxy->>Provider: Token Exchange
        Provider-->>Proxy: Access Token
        Proxy-->>Client: Access Token
        Client->>FastAPI: MCP Request with Token
        FastAPI->>FastAPI: Validate Token
    end
```

### Server-Side Setup Logic

The `_setup_auth_2025_03_26()` method in `FastApiMCP` orchestrates the OAuth setup:

资料来源：[fastapi_mcp/server.py:50-100]()

```python
def _setup_auth_2025_03_26(self):
    if self._auth_config:
        if self._auth_config.custom_oauth_metadata:
            setup_oauth_custom_metadata(
                app=self.fastapi,
                auth_config=self._auth_config,
                metadata=self._auth_config.custom_oauth_metadata,
            )
        elif self._auth_config.setup_proxies:
            metadata_url = self._auth_config.oauth_metadata_url
            if not metadata_url:
                metadata_url = f"{self._auth_config.issuer}{self._auth_config.metadata_path}"

            setup_oauth_metadata_proxy(
                app=self.fastapi,
                metadata_url=metadata_url,
                path=self._auth_config.metadata_path,
                register_path="/oauth/register" if self._auth_config.setup_fake_dynamic_registration else None,
            )
            setup_oauth_authorize_proxy(
                app=self.fastapi,
                client_id=self._auth_config.client_id,
                authorize_url=self._auth_config.authorize_url,
                audience=self._auth_config.audience,
                default_scope=self._auth_config.default_scope,
            )
            if self._auth_config.setup_fake_dynamic_registration:
                setup_oauth_fake_dynamic_register_endpoint(
                    app=self.fastapi,
                    client_id=self._auth_config.client_id,
                    client_secret=self._auth_config.client_secret,
                )
```

## Complete Example: Auth0 Integration

This example demonstrates a full OAuth authentication setup with Auth0.

资料来源：[examples/09_auth_example_auth0.py:1-80]()

```python
from fastapi import FastAPI, Depends, HTTPException, Request, status
from pydantic_settings import BaseSettings
import logging

from fastapi_mcp import FastApiMCP, AuthConfig
from examples.shared.auth import fetch_jwks_public_key

setup_logging()
logger = logging.getLogger(__name__)

class Settings(BaseSettings):
    auth0_domain: str
    auth0_audience: str
    auth0_client_id: str
    auth0_client_secret: str

    @property
    def auth0_oauth_metadata_url(self):
        return f"https://{self.auth0_domain}/.well-known/openid-configuration"

    class Config:
        env_file = ".env"

settings = Settings()

async def lifespan(app: FastAPI):
    app.state.jwks_public_key = await fetch_jwks_public_key(
        settings.auth0_jwks_url
    )
    logger.info(f"Auth0 client ID: {settings.auth0_client_id}")

app = FastAPI(lifespan=lifespan)

async def verify_auth(request: Request):
    """Verify JWT token from Auth0."""
    # Token verification logic
    pass

mcp = FastApiMCP(
    app,
    name="MCP With Auth0",
    description="Example of FastAPI-MCP with Auth0 authentication",
    auth_config=AuthConfig(
        issuer=f"https://{settings.auth0_domain}/",
        authorize_url=f"https://{settings.auth0_domain}/authorize",
        oauth_metadata_url=settings.auth0_oauth_metadata_url,
        audience=settings.auth0_audience,
        client_id=settings.auth0_client_id,
        client_secret=settings.auth0_client_secret,
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
    ),
)

mcp.mount_http()
```

## Token Passthrough Example

For simpler scenarios where you just need to verify bearer tokens:

资料来源：[examples/08_auth_example_token_passthrough.py:1-60]()

```python
from fastapi import Depends
from fastapi.security import HTTPBearer

from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()
```

## Environment Configuration

For Auth0, create a `.env` file:

```bash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://your-tenant.auth0.com/api/v2/
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
```

## MCP Client Configuration

Configure your MCP client to use OAuth authentication:

```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}
```

资料来源：[examples/08_auth_example_token_passthrough.py:8-22]()

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| 401 on all requests | Auth dependencies always fail | Ensure token verification returns user info instead of raising 401 |
| Metadata endpoint returns 502 | OAuth provider unreachable | Verify `oauth_metadata_url` is correct and accessible |
| Client not triggering OAuth | Dependencies not raising 401 | Dependencies must raise HTTPException with 401 for OAuth flow |
| Dynamic registration fails | Fake endpoint not enabled | Set `setup_fake_dynamic_registration=True` in AuthConfig |

### Debug Logging

Enable debug logging to trace authentication issues:

```python
import logging
logging.basicConfig(level=logging.DEBUG)

---

<a id='endpoint-filtering'></a>

## Endpoint Filtering and Selection

### 相关页面

相关主题：[Quickstart Guide](#quickstart), [Tool Naming and Schema](#tool-naming)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)
- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)
- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)
- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)
</details>

# Endpoint Filtering and Selection

The Endpoint Filtering and Selection feature in FastAPI-MCP provides granular control over which FastAPI endpoints are exposed as MCP tools. This allows developers to create specialized MCP servers that expose only a subset of their FastAPI API, enabling targeted integrations, improved security through principle of least privilege, and support for multi-tenant or use-case-specific MCP deployments.

## Overview

FastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. The filtering system operates on top of this conversion, enabling selective exposure of endpoints based on operation IDs and tags defined in the OpenAPI specification.

This feature was introduced to support:
- **Multi-tenant deployments**: Different MCP servers for different client types
- **Security isolation**: Limiting exposed functionality to minimize attack surface
- **Use-case specificity**: Creating focused MCP servers for particular workflows
- **Separate deployment**: Deploying MCP servers independently from the main API service

资料来源：[CHANGELOG.md:5-11]()

## Filter Parameters

The filtering is controlled through four mutually-exclusive parameters in the `FastApiMCP` constructor:

| Parameter | Type | Description |
|-----------|------|-------------|
| `include_operations` | `Optional[List[str]]` | List of operation IDs to include as MCP tools |
| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to exclude from MCP tools |
| `include_tags` | `Optional[List[str]]` | List of tags to include as MCP tools |
| `exclude_tags` | `Optional[List[str]]` | List of tags to exclude from MCP tools |

资料来源：[fastapi_mcp/server.py:1-100](fastapi_mcp/server.py)

### Parameter Validation Rules

The filtering system enforces several validation constraints to prevent ambiguous configurations:

1. **Operation exclusion**: `include_operations` and `exclude_operations` cannot be used together
2. **Tag exclusion**: `include_tags` and `exclude_tags` cannot be used together
3. **Flexible combination**: Operation filtering can be combined with tag filtering using a greedy approach

When combining filters in include mode, endpoints matching **either** the operation criteria **or** the tag criteria will be included in the MCP server.

资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()

## Architecture

```mermaid
graph TD
    A[FastAPI Application] --> B[OpenAPI Schema Generation]
    B --> C[FastApiMCP Constructor]
    C --> D{Filtering Parameters?}
    D -->|No filters| E[All Tools Exposed]
    D -->|With filters| F[_filter_tools Method]
    
    F --> G{include_operations?}
    G -->|Yes| H[Filter by Operation IDs]
    
    F --> I{exclude_operations?}
    I -->|Yes| J[Exclude by Operation IDs]
    
    F --> K{include_tags?}
    K -->|Yes| L[Filter by Tags]
    
    F --> M{exclude_tags?}
    M -->|Yes| N[Exclude by Tags]
    
    H --> O[Build Operations Map]
    J --> O
    L --> O
    N --> O
    O --> P[Filtered Tool List]
    
    P --> Q[MCP Server]
    E --> Q
```

### Filter Logic Flow

```mermaid
graph LR
    A[Tools List] --> B{_include_operations<br/>is None?}
    B -->|Yes| C{_exclude_operations<br/>is None?}
    B -->|No| D[Keep only tools with<br/>matching operationId]
    C -->|No| E[Remove tools with<br/>matching operationId]
    C -->|Yes| F{_include_tags<br/>is None?}
    D --> G[Operations By Tag Map]
    E --> G
    F -->|No| H[Keep tools with<br/>matching tags]
    F -->|Yes| I{_exclude_tags<br/>is None?}
    H --> J[Final Tool Set]
    I -->|No| K[Remove tools with<br/>matching tags]
    I -->|Yes| J
    K --> J
```

## Implementation Details

### The `_filter_tools` Method

The core filtering logic resides in the `_filter_tools` method within `fastapi_mcp/server.py`. This method:

1. Returns the original tool list if no filters are configured
2. Builds a mapping of tags to operation IDs from the OpenAPI schema
3. Applies inclusion/exclusion logic based on operation IDs and tags
4. Returns the filtered tool list

```python
def _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:
    """
    Filter tools based on operation IDs and tags.
    """
    if (
        self._include_operations is None
        and self._exclude_operations is None
        and self._include_tags is None
        and self._exclude_tags is None
    ):
        return tools

    operations_by_tag: Dict[str, List[str]] = {}
    for path, path_item in openapi_schema.get("paths", {}).items():
        for method, operation in path_item.items():
            if method not in ["get", "post", "put", "delete", "patch"]:
                continue
            # ... filtering logic continues
```

资料来源：[fastapi_mcp/server.py:1-50]()

### Parameter Organization in OpenAPI Conversion

When endpoints are converted to MCP tools, parameters are organized into four categories:

| Parameter Type | OpenAPI Location | Description |
|----------------|------------------|-------------|
| Path Parameters | `parameters[in=path]` | URL path variables |
| Query Parameters | `parameters[in=query]` | Query string parameters |
| Header Parameters | `parameters[in=header]` | HTTP header values |
| Body Parameters | `requestBody` | Request body content |

资料来源：[fastapi_mcp/openapi/convert.py:1-80]()

## Usage Examples

### Basic Operation ID Filtering

```python
from fastapi_mcp import FastApiMCP

# Include only specific operations
include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
exclude_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:18-30]()

### Tag-Based Filtering

```python
# Include only operations with specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)

# Exclude operations with specific tags
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)
```

### Combined Filtering

```python
# Combine operation IDs and tags in include mode
combined_include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Combined Include",
    include_operations=["delete_item"],
    include_tags=["search"],
)
```

When using combined include filters, the MCP server exposes endpoints that match **either** criteria—the operation ID filter **or** the tag filter. This greedy approach ensures comprehensive coverage of relevant endpoints.

资料来源：[examples/03_custom_exposed_endpoints_example.py:55-65]()

## Available Examples

FastAPI-MCP provides a dedicated example demonstrating endpoint filtering capabilities:

| Example | File | Description |
|---------|------|-------------|
| Custom Exposed Endpoints | `03_custom_exposed_endpoints_example.py` | Comprehensive filtering examples |

资料来源：[examples/README.md:1-15]()

To run the example:

```bash
cd examples
uv run python 03_custom_exposed_endpoints_example.py
```

## Mounting Filtered Servers

After creating filtered MCP servers, mount them at different HTTP paths:

```python
include_operations_mcp.mount_http(mount_path="/include-operations-mcp")
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")
```

This allows clients to connect to specific filtered MCP servers based on their needs.

资料来源：[examples/03_custom_exposed_endpoints_example.py:68-74]()

## Best Practices

1. **Use descriptive operation IDs**: Ensure your FastAPI endpoints have clear, consistent `operationId` values for easier filtering
2. **Leverage tags for organization**: Group related endpoints with consistent tags to enable effective tag-based filtering
3. **Principle of least privilege**: Only expose the minimum set of endpoints required for each MCP use case
4. **Combine filters strategically**: Use combined include filters to create focused MCP servers that serve specific workflows
5. **Test filtering combinations**: Verify that the greedy approach of combined filters produces the expected tool set

---

<a id='tool-naming'></a>

## Tool Naming and Schema

### 相关页面

相关主题：[Endpoint Filtering and Selection](#endpoint-filtering), [System Architecture](#architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)
- [fastapi_mcp/openapi/utils.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/utils.py)
- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)
</details>

# Tool Naming and Schema

This page documents how FastAPI-MCP derives MCP tool names, descriptions, and input schemas from FastAPI/OpenAPI endpoint definitions.

## Overview

When a FastAPI application is mounted as an MCP server, every route operation becomes an MCP tool. The conversion pipeline performs the following high-level steps:

1. **Resolve** all `$ref` references in the OpenAPI schema
2. **Extract** operation metadata (operationId, summary, description)
3. **Classify** parameters by location (path, query, header)
4. **Parse** request body schemas into tool input schemas
5. **Generate** human-readable tool descriptions including example values
6. **Build** the `types.Tool` objects returned to the MCP runtime

资料来源：[fastapi_mcp/openapi/convert.py:21-45]()

```mermaid
graph TD
    A[OpenAPI Schema] --> B[resolve_schema_references]
    B --> C[Iterate paths]
    C --> D[Extract operationId]
    D --> E[Classify Parameters]
    E --> F[Parse Request Body]
    F --> G[Build Tool Description]
    G --> H[types.Tool]
```

## Tool Naming

Tool names are derived directly from the `operationId` field in the OpenAPI operation object. The function `convert_openapi_to_mcp_tools` skips any operation that lacks an `operationId`:

```python
operation_id = operation.get("operationId")
if not operation_id:
    logger.warning(f"Skipping non-HTTP method: {method}")
    continue
```

资料来源：[fastapi_mcp/openapi/convert.py:56-62]()

The resulting tool names are exactly the `operationId` strings, without any namespace prefix. For example, given a FastAPI route:

```python
@app.get("/items/{item_id}", response_model=Item, operation_id="get_item")
async def get_item(item_id: int):
    ...
```

The MCP tool will be named `get_item`.

## Schema Resolution

Before any schema processing occurs, all JSON Pointer references (`$ref`) are resolved upfront by calling `resolve_schema_references`:

```python
resolved_openapi_schema = resolve_schema_references(openapi_schema, openapi_schema)
```

This single-pass resolution replaces all `$ref` values with their referenced definitions, ensuring that downstream code works with concrete schemas rather than indirection.

资料来源：[fastapi_mcp/openapi/convert.py:50-53]()

## Parameter Classification

Parameters are classified by their `in` field into four groups:

| Group | `in` value | Description |
|-------|------------|-------------|
| Path parameters | `"path"` | Required URL segment parameters |
| Query parameters | `"query"` | Optional query string parameters |
| Header parameters | `"header"` | HTTP header parameters |
| Body parameters | `"requestBody"` | JSON request body (handled separately) |

The classification code:

```python
for param in operation.get("parameters", []):
    param_name = param.get("name")
    param_in = param.get("in")
    required = param.get("required", False)

    if param_in == "path":
        path_params.append((param_name, param))
    elif param_in == "query":
        query_params.append((param_name, param))
    elif param_in == "header":
        header_params.append((param_name, param))
```

资料来源：[fastapi_mcp/openapi/convert.py:79-93]()

## Example Generation

The utility `generate_example_from_schema` produces human-readable example values for each schema type to include in tool descriptions. The function handles the following OpenAPI types:

| OpenAPI Type | Generated Example |
|--------------|-------------------|
| `string` (no format) | `"string"` or the `title` field value |
| `string` with `format: date-time` | `"2023-01-01T00:00:00Z"` |
| `string` with `format: date` | `"2023-01-01"` |
| `string` with `format: email` | `"user@example.com"` |
| `string` with `format: uri` | `"https://example.com"` |
| `integer` | `1` |
| `number` | `1.0` |
| `boolean` | `true` |
| `array` | A single-item array with an example of the `items` type |
| `object` | A dict with one example per `properties` entry |
| `null` | `null` |

资料来源：[fastapi_mcp/openapi/utils.py:45-70]()

### Object Schema Example

```python
elif schema_type == "object":
    result = {}
    if "properties" in schema:
        for prop_name, prop_schema in schema["properties"].items():
            prop_example = generate_example_from_schema(prop_schema)
            if prop_example is not None:
                result[prop_name] = prop_example
    return result
```

### Array Schema Example

```python
elif schema_type == "array":
    if "items" in schema:
        item_example = generate_example_from_schema(schema["items"])
        if item_example is not None:
            return [item_example]
    return []
```

## Tool Description Building

The `convert_openapi_to_mcp_tools` function constructs a human-readable `description` field for each tool by concatenating:

1. The operation's `summary` and `description` fields from OpenAPI
2. Parameter documentation with names, types, required status, and descriptions
3. Request body schema details (if present)
4. Output schema with example values

```python
tool_description += response_info
```

The response information is only included when the `describe_all_responses` or `describe_full_response_schema` flags are set. The description includes:
- The HTTP method and path
- Parameter documentation grouped by type
- Request body schema examples
- Output schema examples for both array and object responses

## Output Schema Handling

Response schemas are processed to produce two display formats:

1. **Array responses**: The `items` schema is extracted and shown as an array of items with the item structure
2. **Object responses**: The full `properties` schema is displayed

```python
if items_schema := schema.get("items", {}).get("properties"):
    response_info += "\n\n**Output Schema:** Array of items with the following structure:\n```json\n"
    response_info += json.dumps(items_schema, indent=2)
elif "properties" in display_schema:
    response_info += "\n\n**Output Schema:**\n```json\n"
    response_info += json.dumps(display_schema, indent=2)
```

## Supported HTTP Methods

Only standard HTTP methods are converted to tools:

```python
if method not in ["get", "post", "put", "delete", "patch"]:
    logger.warning(f"Skipping non-HTTP method: {method}")
    continue
```

| Method | Supported |
|--------|-----------|
| GET | Yes |
| POST | Yes |
| PUT | Yes |
| DELETE | Yes |
| PATCH | Yes |
| HEAD, OPTIONS, etc. | No (logged and skipped) |

## Related Utilities

| Function | File | Purpose |
|----------|------|---------|
| `resolve_schema_references` | `openapi/utils.py` | Resolves all `$ref` pointers in the schema |
| `generate_example_from_schema` | `openapi/utils.py` | Creates example values for tool descriptions |
| `clean_schema_for_display` | `openapi/utils.py` | Sanitizes schema for display |
| `get_single_param_type_from_schema` | `openapi/utils.py` | Extracts parameter type from schema |
| `convert_openapi_to_mcp_tools` | `openapi/convert.py` | Main conversion function |

---

<a id='transport-config'></a>

## Transport Configuration

### 相关页面

相关主题：[System Architecture](#architecture), [Deployment Options](#deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)
- [examples/07_configure_http_timeout_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/07_configure_http_timeout_example.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
</details>

# Transport Configuration

FastAPI-MCP supports multiple transport mechanisms for exposing MCP (Model Context Protocol) servers. This document covers the available transport options, configuration parameters, and how to customize transport behavior for different deployment scenarios.

## Overview

FastAPI-MCP provides two primary transport mechanisms:

| Transport Type | Method | Description |
|----------------|--------|-------------|
| HTTP | `mount_http()` | Standard HTTP transport for MCP communication |
| SSE | `mount_sse()` | Server-Sent Events transport for streaming responses |
| Legacy | `mount()` | Deprecated combined method (use `mount_http()` or `mount_sse()` instead) |

资料来源：[fastapi_mcp/server.py:1-200]()

## Transport Architecture

```mermaid
graph TD
    A[FastAPI Application] --> B[FastApiMCP Server]
    B --> C[mount_http]
    B --> D[mount_sse]
    C --> E[HTTP Transport]
    D --> F[SSE Transport]
    E --> G[httpx.AsyncClient]
    F --> H[FastApiSseTransport]
    G --> I[ASGI Transport]
    H --> I
```

## HTTP Transport Configuration

The HTTP transport is the recommended method for MCP communication. It uses an `httpx.AsyncClient` internally with ASGI transport.

### Basic HTTP Mounting

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app)
mcp.mount_http()
```

资料来源：[examples/01_basic_usage_example.py:1-15]()

### HTTP Client Configuration

The `FastApiMCP` class accepts an optional `http_client` parameter for custom HTTP client configuration:

```python
import httpx
from fastapi_mcp import FastApiMCP

# Custom HTTP client with specific timeout
custom_client = httpx.AsyncClient(
    timeout=30.0
)

mcp = FastApiMCP(
    app,
    http_client=custom_client
)
```

### Default Timeout Behavior

When no custom client is provided, FastAPI-MCP creates an internal HTTP client with a default timeout of 10.0 seconds:

```python
self._http_client = http_client or httpx.AsyncClient(
    transport=httpx.ASGITransport(app=self.fastapi, raise_app_exceptions=False),
    base_url=self._base_url,
    timeout=10.0,
)
```

资料来源：[fastapi_mcp/server.py:1-100]()

### Configuring Custom Timeouts

For long-running API operations, you can configure custom timeout values:

```python
import httpx
from fastapi_mcp import FastApiMCP

# Create client with extended timeout
client = httpx.AsyncClient(timeout=httpx.Timeout(60.0))

mcp = FastApiMCP(
    app,
    name="Extended Timeout MCP",
    http_client=client,
)
```

资料来源：[examples/07_configure_http_timeout_example.py]()

## SSE Transport Configuration

The SSE (Server-Send Events) transport provides streaming capabilities for MCP communication.

### Basic SSE Mounting

```python
from fastapi_mcp import FastApiMCP

mcp = FastApiMCP(app)
mcp.mount_sse(router, mount_path="/sse")
```

资料来源：[fastapi_mcp/server.py:1-200]()

### SSE Endpoint Registration

The SSE transport registers two endpoints:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `{mount_path}` | GET | SSE connection establishment |
| `{mount_path}/messages/` | POST | Message handling |

```python
def _register_mcp_connection_endpoint_sse(
    self,
    router: FastAPI | APIRouter,
    transport: FastApiSseTransport,
    mount_path: str,
    dependencies: Optional[Sequence[params.Depends]],
):
    @router.get(mount_path, include_in_schema=False, operation_id="mcp_connection", dependencies=dependencies)
    async def handle_mcp_connection(request: Request):
        async with transport.connect_sse(request.scope, request.receive, request._send) as (reader, writer):
            await self.server.run(
                reader,
                writer,
                self.server.create_initialization_options(notification_options=None, experimental_capabilities={}),
                raise_exceptions=False,
            )
```

资料来源：[fastapi_mcp/server.py:100-200]()

## Header Forwarding Configuration

FastAPI-MCP allows forwarding specific HTTP headers from incoming MCP requests to tool invocations.

### Default Header Forwarding

By default, only the `authorization` header is forwarded:

```python
headers: Annotated[
    List[str],
    Doc(
        """
        List of HTTP header names to forward from the incoming MCP request into each tool invocation.
        Only headers in this allowlist will be forwarded. Defaults to ['authorization'].
        """
    ),
] = ["authorization"],
```

资料来源：[fastapi_mcp/server.py:1-100]()

### Custom Header Forwarding

```python
from fastapi_mcp import FastApiMCP

# Forward multiple headers
mcp = FastApiMCP(
    app,
    headers=["authorization", "x-api-key", "x-request-id"],
)
```

### Token Passthrough Example

For authenticated APIs, headers can be forwarded to maintain authentication:

```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
    headers=["authorization"],  # Forward the auth header
)
```

资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()

## Authentication Configuration

The `AuthConfig` class provides OAuth and authentication support:

| Parameter | Type | Description |
|-----------|------|-------------|
| `version` | Literal["2025-03-26"] | MCP spec version for authorization |
| `dependencies` | Optional[Sequence[params.Depends]] | FastAPI dependencies for auth checks |
| `issuer` | Optional[str] | OAuth 2.0 issuer URL |
| `oauth_metadata_url` | Optional[StrHttpUrl] | Full URL of OAuth metadata endpoint |
| `authorize_url` | Optional[StrHttpUrl] | Authorization endpoint URL |

资料来源：[fastapi_mcp/types.py:1-100]()

### OAuth Configuration Example

```python
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(
        version="2025-03-26",
        issuer="https://your-tenant.auth0.com",
        dependencies=[Depends(authenticate_request)],
    ),
)
```

## Tool Filtering by Transport

When mounting the MCP server, you can filter which operations are exposed:

| Parameter | Type | Description |
|-----------|------|-------------|
| `include_operations` | Optional[List[str]] | Operation IDs to include |
| `exclude_operations` | Optional[List[str]] | Operation IDs to exclude |
| `include_tags` | Optional[List[str]] | Tags to include |
| `exclude_tags` | Optional[List[str]] | Tags to exclude |

```python
# Include specific operations only
mcp = FastApiMCP(
    app,
    name="Filtered MCP",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
mcp = FastApiMCP(
    app,
    name="Filtered MCP",
    exclude_operations=["delete_item", "update_item"],
)
```

资料来源：[examples/03_custom_exposed_endpoints_example.py]()

## Deprecation Notice

The legacy `mount()` method is deprecated and will be removed in a future version:

```python
# DEPRECATED - Do not use
mcp.mount(router, mount_path, transport="sse")

# RECOMMENDED - Use these instead
mcp.mount_http()
mcp.mount_sse(router, mount_path)
```

资料来源：[fastapi_mcp/server.py:1-100]()

## Complete Configuration Example

```python
import httpx
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

app = FastAPI()
token_auth_scheme = HTTPBearer()

# Custom authentication dependency
async def authenticate_request(request: Request, token: str = Depends(token_auth_scheme)):
    payload = verify_token(request, token)
    if payload is None:
        raise HTTPException(status_code=401, detail="Unauthorized")
    return payload

# Configure MCP with all transport options
mcp = FastApiMCP(
    app,
    name="Complete Example MCP",
    describe_all_responses=True,
    describe_full_response_schema=True,
    http_client=httpx.AsyncClient(timeout=30.0),
    include_tags=["items", "search"],
    auth_config=AuthConfig(
        dependencies=[Depends(authenticate_request)],
    ),
    headers=["authorization", "x-api-key"],
)

# Mount with HTTP transport
mcp.mount_http()
```

## Summary

FastAPI-MCP provides flexible transport configuration options:

- **HTTP Transport**: Default transport using httpx.AsyncClient with configurable timeouts
- **SSE Transport**: Server-Sent Events for streaming scenarios
- **Header Forwarding**: Customizable header allowlist for request passthrough
- **Authentication**: OAuth and dependency-based authentication support
- **Tool Filtering**: Operation ID and tag-based filtering for exposed endpoints

Choose the appropriate transport based on your deployment requirements, with HTTP being the recommended default for most use cases.

---

<a id='deployment'></a>

## Deployment Options

### 相关页面

相关主题：[Transport Configuration](#transport-config), [Dynamic Tool Registration](#dynamic-registration), [Examples Overview](#examples)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)
- [examples/06_custom_mcp_router_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/06_custom_mcp_router_example.py)
- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)
- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)
- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)
</details>

# Deployment Options

FastAPI-MCP provides multiple deployment options for integrating MCP (Model Context Protocol) servers with FastAPI applications. These options allow developers to mount MCP servers using different transports (HTTP and SSE), deploy them separately from the main API service, or integrate them with custom APIRouter configurations.

## Overview

FastAPI-MCP supports three primary deployment patterns:

| Deployment Mode | Transport | Description | Use Case |
|-----------------|-----------|-------------|----------|
| Integrated (HTTP) | HTTP | MCP server mounted directly into the FastAPI app | Default option, simple deployment |
| Integrated (SSE) | Server-Sent Events | MCP server using SSE transport | Legacy support, browser compatibility |
| Separate Server | HTTP | MCP server running as standalone service | Microservices architecture, independent scaling |

资料来源：[fastapi_mcp/server.py:1-50]()

## Transport Types

### HTTP Transport

HTTP transport is the **recommended** deployment option for FastAPI-MCP. It provides a FastAPI-native approach that integrates seamlessly with the existing FastAPI ecosystem.

**Key characteristics:**
- Uses `httpx.AsyncClient` for making HTTP requests
- Supports streaming responses
- Compatible with all major MCP clients
- Better performance compared to SSE

资料来源：[fastapi_mcp/server.py:85-120]()

```mermaid
graph TD
    A[MCP Client] -->|HTTP Request| B[FastAPI App /mcp]
    B --> C[FastApiMCP Server]
    C -->|Tool Call| D[FastAPI Endpoints]
    D -->|Response| C
    C -->|MCP Response| A
```

### SSE Transport

Server-Sent Events (SSE) transport is provided for legacy compatibility and specific use cases requiring browser-based connections.

**Key characteristics:**
- Bidirectional communication via SSE streams
- Requires specific endpoint registration
- Uses `FastApiSseTransport` class

资料来源：[fastapi_mcp/server.py:150-200]()

## Mounting Methods

### Basic HTTP Mount

The simplest deployment option mounts the MCP server directly to the root FastAPI application using HTTP transport.

```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI(__name__)
mcp = FastApiMCP(app, name="My MCP Server")

# Mount with HTTP transport (default)
mcp.mount_http()
```

资料来源：[examples/08_auth_example_token_passthrough.py:40-48]()

### Custom Router Mount

Deploy the MCP server to a specific `APIRouter` instead of the root application. This is useful for organizing endpoints under a specific path prefix.

```python
from fastapi import FastAPI, APIRouter
from fastapi_mcp import FastApiMCP

app = FastAPI(__name__)

# Create a custom router with a prefix
other_router = APIRouter(prefix="/other/route")
app.include_router(other_router)

mcp = FastApiMCP(app)

# Mount to the custom router
# MCP will be available at /other/route/mcp
mcp.mount_http(other_router)
```

资料来源：[examples/06_custom_mcp_router_example.py:1-28]()

### SSE Mount

For SSE transport, the server provides dedicated mounting methods:

```python
mcp.mount_sse(router=app, mount_path="/mcp")
```

The SSE transport registers two endpoints:
- `GET /mcp` - Connection endpoint
- `POST /mcp/messages/` - Message handling endpoint

资料来源：[fastapi_mcp/server.py:200-250]()

## Separate Server Deployment

FastAPI-MCP supports deploying MCP servers as separate, standalone services. This is particularly useful in microservices architectures where the MCP server and API service need independent scaling and deployment.

### Architecture

```mermaid
graph LR
    subgraph "API Service"
        A[FastAPI App] --> B[API Endpoints]
    end
    
    subgraph "MCP Server"
        C[MCP Server] --> D[Tool Definitions]
        D --> E[HTTP Client]
        E -->|Forward Requests| B
    end
    
    F[MCP Client] --> C
```

### Configuration

When deploying separately, the MCP server configuration specifies the remote server URL:

```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp"
      ]
    }
  }
}
```

### Implementation

To enable separate server deployment:

1. Configure the API service to run normally
2. Mount the MCP server with appropriate transport
3. Configure the remote MCP client to connect to the API service

资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)

### Advantages

| Benefit | Description |
|---------|-------------|
| Independent Scaling | Scale MCP server and API separately based on load |
| Independent Deployment | Deploy updates without coordinating both services |
| Resource Isolation | Different resource allocation for each service |
| Network Flexibility | Services can run on different hosts/ports |

## Endpoint Filtering

When deploying MCP servers, you can control which FastAPI endpoints are exposed as MCP tools using operation IDs and tags.

### Filter by Operation IDs

```python
# Include only specific operations
mcp = FastApiMCP(
    app,
    include_operations=["get_item", "list_items"]
)

# Exclude specific operations
mcp = FastApiMCP(
    app,
    exclude_operations=["create_item", "update_item", "delete_item"]
)
```

### Filter by Tags

```python
# Include only operations with specific tags
mcp = FastApiMCP(
    app,
    include_tags=["items"]
)

# Exclude operations with specific tags
mcp = FastApiMCP(
    app,
    exclude_tags=["search"]
)
```

### Combining Filters

Operation and tag filters can be combined. When combining filters, a greedy approach is taken—endpoints matching **either** criteria will be included.

资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()

## Authentication Integration

FastAPI-MCP integrates with FastAPI's dependency injection system for authentication. When mounting the MCP server, you can configure authentication that will be applied to all MCP tool executions.

### Token Passthrough

```python
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()
```

资料来源：[examples/08_auth_example_token_passthrough.py:1-55]()

### Auth Configuration Options

| Parameter | Type | Description |
|-----------|------|-------------|
| `dependencies` | `List[Depends]` | FastAPI dependencies for authentication |
| `issuer` | `str` | OAuth 2.0 issuer URL |
| `oauth_metadata_url` | `StrHttpUrl` | Full OAuth metadata endpoint URL |
| `authorize_url` | `StrHttpUrl` | OAuth authorization endpoint URL |

## Running the Server

### Development Mode

```bash
uvicorn.run(app, host="0.0.0.0", port=8000)
```

### With uv

```bash
# Install dependencies
uv sync

# Run the server
uv run uvicorn main:app --host 0.0.0.0 --port 8000
```

资料来源：[CONTRIBUTING.md:1-80]()

## Migration from Deprecated `mount()`

The `mount()` method is deprecated. Use the specific transport methods instead:

| Deprecated | Replacement |
|------------|-------------|
| `mount(transport="sse")` | `mount_sse()` |
| `mount(transport="http")` | `mount_http()` |

```python
# Old (deprecated)
mcp.mount(app, "/mcp", transport="sse")

# New (recommended)
mcp.mount_sse(app, "/mcp")
```

资料来源：[CHANGELOG.md:1-50]()

## Summary

FastAPI-MCP provides flexible deployment options to accommodate various architectural requirements:

- **HTTP Transport**: Recommended for most use cases, provides best performance
- **SSE Transport**: Legacy support for browser-compatible deployments
- **Separate Server**: Ideal for microservices architectures
- **Custom Router**: Organize MCP endpoints under specific paths
- **Endpoint Filtering**: Control which tools are exposed to MCP clients
- **Auth Integration**: Leverage existing FastAPI authentication

---

<a id='dynamic-registration'></a>

## Dynamic Tool Registration

### 相关页面

相关主题：[Deployment Options](#deployment), [Endpoint Filtering and Selection](#endpoint-filtering)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)
- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)
- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)
- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)
- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)
</details>

# Dynamic Tool Registration

Dynamic Tool Registration is a core feature of FastAPI-MCP that enables runtime filtering, registration, and management of MCP tools derived from FastAPI endpoints. This capability allows developers to create multiple MCP server instances with different tool subsets from a single FastAPI application, providing fine-grained control over which tools are exposed to MCP clients.

## Overview

FastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. Dynamic Tool Registration extends this capability by allowing selective exposure of tools based on operation IDs and tags, enabling scenarios such as:

- Creating multiple specialized MCP servers from one FastAPI app
- Protecting sensitive endpoints by excluding them from MCP exposure
- Creating tenant-specific or role-based tool visibility
- Supporting incremental updates to tool availability

The feature is implemented through the `FastApiMCP` class constructor parameters that control which operations are registered as MCP tools.

## Architecture

```mermaid
graph TD
    A[FastAPI Application] --> B[OpenAPI Schema Analysis]
    B --> C[All Discovered Endpoints]
    C --> D{Filter Criteria}
    D -->|include_operations| E[Whitelist Mode]
    D -->|exclude_operations| F[Blacklist Mode]
    D -->|include_tags| G[Tag Filter - Include]
    D -->|exclude_tags| H[Tag Filter - Exclude]
    E --> I[Filtered Tool Set]
    F --> I
    G --> I
    H --> I
    I --> J[MCP Server Instance]
```

## Core Filter Parameters

The `FastApiMCP` class accepts four mutually-exclusive filter parameters:

| Parameter | Type | Description |
|-----------|------|-------------|
| `include_operations` | `Optional[List[str]]` | List of operation IDs to **include** as MCP tools |
| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to **exclude** from MCP tools |
| `include_tags` | `Optional[List[str]]` | List of tags to **include** as MCP tools |
| `exclude_tags` | `Optional[List[str]]` | List of tags to **exclude** from MCP tools |

资料来源：[fastapi_mcp/server.py:1-100]()

### Mutual Exclusivity Rules

The filtering parameters follow strict mutual exclusivity rules:

1. **Operation filters**: Cannot use `include_operations` and `exclude_operations` together
2. **Tag filters**: Cannot use `include_tags` and `exclude_tags` together
3. **Cross-type combination**: Can combine operation filters with tag filters (greedy approach)

When combining filters, a greedy union strategy is applied: endpoints matching **either** the operation criteria **or** the tag criteria will be included.

资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()

## Filter Implementation

The filtering logic is implemented in the `_filter_tools` method of the `FastApiMCP` class:

```python
def _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:
    """
    Filter tools based on operation IDs and tags.

    Args:
        tools: List of tools to filter
        openapi_schema: The OpenAPI schema

    Returns:
        Filtered list of tools
    """
    if (
        self._include_operations is None
        and self._exclude_operations is None
        and self._include_tags is None
        and self._exclude_tags is None
    ):
        return tools
```

资料来源：[fastapi_mcp/server.py:85-105]()

### Operation ID Mapping

The filtering mechanism builds an operations map indexed by both operation ID and tags:

```python
operations_by_tag: Dict[str, List[str]] = {}
for path, path_item in openapi_schema.get("paths", {}).items():
    for method, operation in path_item.items():
        if method not in ["get", "post", "put", "delete", "patch"]:
            continue

        operation_id = operation.get("operationId")
        if not operation_id:
            continue

        tags = operation.get("tags", [])
        for tag in tags:
            if tag not in operations_by_tag:
                operations_by_tag[tag] = []
            operations_by_tag[tag].append(operation_id)
```

资料来源：[fastapi_mcp/server.py:107-125]()

## Usage Patterns

### Include Specific Operations

Create an MCP server exposing only specified operation IDs:

```python
include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)
include_operations_mcp.mount_http(mount_path="/include-operations-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:20-26]()

### Exclude Specific Operations

Create an MCP server with all operations except specified ones:

```python
exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:28-34]()

### Tag-Based Inclusion

Filter tools by including endpoints with specific OpenAPI tags:

```python
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:36-41]()

### Tag-Based Exclusion

Exclude all endpoints with specific tags:

```python
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:43-48]()

### Combined Filtering

Combine operation ID and tag filters for complex scenarios:

```python
combined_include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Combined Include",
    include_operations=["delete_item"],
    include_tags=["search"],
)
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:50-57]()

## Re-registering Tools

The library supports re-registering tools at runtime through multiple `FastApiMCP` instances mounted on different paths:

```python
# Mount all MCP servers with different paths
include_operations_mcp.mount_http(mount_path="/include-operations-mcp")
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")
```

资料来源：[examples/03_custom_exposed_endpoints_example.py:62-68]()

Each mounted instance operates independently, allowing different clients to access different tool sets from the same underlying FastAPI application.

## Custom Tools Integration

Beyond API-derived tools, FastAPI-MCP supports adding custom MCP tools alongside auto-generated ones:

### Added
- Main `add_mcp_server` function for simple MCP server integration
- Support for adding custom MCP tools alongside API-derived tools

资料来源：[CHANGELOG.md:1-20]()

This enables scenarios where developers need to add supplementary tools that don't correspond to FastAPI endpoints, such as helper utilities or integration points with external services.

## HTTP Client Configuration

The tool registration system includes support for custom HTTP client configuration:

```python
http_client: Annotated[
    Optional[httpx.AsyncClient],
    Doc(
        """
        Optional custom HTTP client to use for API calls to the FastAPI app.
        Has to be an instance of `httpx.AsyncClient`.
        """
    ),
] = None,
```

资料来源：[fastapi_mcp/server.py:50-58]()

This allows fine-grained control over the HTTP client used to invoke tools, enabling custom timeouts, authentication, or proxy configuration.

## Header Passthrough

The system supports forwarding specific HTTP headers from MCP requests to tool invocations:

```python
headers: Annotated[
    List[str],
    Doc(
        """
        List of HTTP header names to forward from the incoming MCP request 
        into each tool invocation. Only headers in this allowlist will be 
        forwarded. Defaults to ['authorization'].
        """
    ),
] = ["authorization"],
```

资料来源：[fastapi_mcp/server.py:85-93]()

This is particularly important for maintaining authentication context when tools are invoked through the MCP protocol.

## Summary

Dynamic Tool Registration in FastAPI-MCP provides a flexible mechanism for controlling which FastAPI endpoints become MCP tools. By supporting operation ID filtering, tag-based filtering, and their combinations, developers can:

- Create specialized MCP servers for different use cases
- Implement fine-grained access control
- Support multi-tenant or role-based tool visibility
- Combine auto-generated and custom tools in a single MCP server

The implementation uses a greedy union strategy when combining filters, ensuring maximum flexibility while maintaining predictable behavior. All filtering occurs at registration time, ensuring optimal runtime performance for tool invocation.

---

---

## Doramagic 踩坑日志

项目：tadata-org/fastapi_mcp

摘要：发现 22 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：[BUG] MCP session 404 in multi worker production environment。

## 1. 配置坑 · 来源证据：[BUG] MCP session 404 in multi worker production environment

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：v0.1.8

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。

## 3. 安装坑 · 来源证据：v0.2.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。

## 4. 安装坑 · 来源证据：v0.3.4

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。

## 5. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor

## 6. 配置坑 · 来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 配置坑 · 来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 8. 配置坑 · 来源证据：v0.3.6

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。

## 9. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.

## 10. 维护坑 · 来源证据：[BUG] Description incorrectly passed as version to MCP Server

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 11. 维护坑 · 来源证据：v0.3.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_bc6b7bd2988b48d48920e4ffb259f147 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0 | 来源类型 github_release 暴露的待验证使用条件。

## 12. 维护坑 · 来源证据：v0.3.3 - Fix OpenAPI Conversion Regression

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.3 - Fix OpenAPI Conversion Regression
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_79b96b9d35b9444c938c355c081410ac | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3 | 来源类型 github_release 暴露的待验证使用条件。

## 13. 维护坑 · 来源证据：v0.4.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.4.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4382c9c951e14187b76777ad8561ded9 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0 | 来源类型 github_release 暴露的待验证使用条件。

## 14. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | last_activity_observed missing

## 15. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium

## 16. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | No sandbox install has been executed yet; downstream must verify before user use.

## 17. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium

## 18. 安全/权限坑 · 来源证据：v0.3.1 - Authorization

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.1 - Authorization
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_41bf79ee5bd04da1b943d22449a0d649 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1 | 来源类型 github_release 暴露的待验证使用条件。

## 19. 安全/权限坑 · 来源证据：v0.3.2

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.2
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_aa60828a6a6c4cc2b0b28fb72bf2ddad | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2 | 来源类型 github_release 暴露的待验证使用条件。

## 20. 安全/权限坑 · 来源证据：v0.3.7

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.7
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_31faa7de6a364174958daaffa9d9204b | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7 | 来源类型 github_release 暴露的待验证使用条件。

## 21. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | issue_or_pr_quality=unknown

## 22. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | release_recency=unknown

<!-- canonical_name: tadata-org/fastapi_mcp; human_manual_source: deepwiki_human_wiki -->
