Full Code of tadata-org/fastapi_mcp for AI

main e5cad13cabfc cached
80 files
280.4 KB
66.7k tokens
191 symbols
1 requests
Download .txt
Showing preview only (300K chars total). Download the full file or copy to clipboard to get everything.
Repository: tadata-org/fastapi_mcp
Branch: main
Commit: e5cad13cabfc
Files: 80
Total size: 280.4 KB

Directory structure:
gitextract_ks2z9rdn/

├── .coveragerc
├── .cursorignore
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── documentation.md
│   │   └── feature_request.md
│   ├── codecov.yml
│   ├── dependabot.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── ci.yml
│       └── release.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .python-version
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── README_zh-CN.md
├── docs/
│   ├── advanced/
│   │   ├── asgi.mdx
│   │   ├── auth.mdx
│   │   ├── deploy.mdx
│   │   ├── refresh.mdx
│   │   └── transport.mdx
│   ├── configurations/
│   │   ├── customization.mdx
│   │   └── tool-naming.mdx
│   ├── docs.json
│   └── getting-started/
│       ├── FAQ.mdx
│       ├── best-practices.mdx
│       ├── installation.mdx
│       ├── quickstart.mdx
│       └── welcome.mdx
├── examples/
│   ├── 01_basic_usage_example.py
│   ├── 02_full_schema_description_example.py
│   ├── 03_custom_exposed_endpoints_example.py
│   ├── 04_separate_server_example.py
│   ├── 05_reregister_tools_example.py
│   ├── 06_custom_mcp_router_example.py
│   ├── 07_configure_http_timeout_example.py
│   ├── 08_auth_example_token_passthrough.py
│   ├── 09_auth_example_auth0.py
│   ├── README.md
│   ├── __init__.py
│   └── shared/
│       ├── __init__.py
│       ├── apps/
│       │   ├── __init__.py
│       │   └── items.py
│       ├── auth.py
│       └── setup.py
├── fastapi_mcp/
│   ├── __init__.py
│   ├── auth/
│   │   ├── __init__.py
│   │   └── proxy.py
│   ├── openapi/
│   │   ├── __init__.py
│   │   ├── convert.py
│   │   └── utils.py
│   ├── server.py
│   ├── transport/
│   │   ├── __init__.py
│   │   ├── http.py
│   │   └── sse.py
│   ├── types.py
│   └── utils/
│       └── __init__.py
├── mypy.ini
├── pyproject.toml
├── pytest.ini
└── tests/
    ├── __init__.py
    ├── conftest.py
    ├── fixtures/
    │   ├── complex_app.py
    │   ├── conftest.py
    │   ├── example_data.py
    │   ├── simple_app.py
    │   └── types.py
    ├── test_basic_functionality.py
    ├── test_configuration.py
    ├── test_http_real_transport.py
    ├── test_mcp_complex_app.py
    ├── test_mcp_execute_api_tool.py
    ├── test_mcp_simple_app.py
    ├── test_openapi_conversion.py
    ├── test_sse_mock_transport.py
    ├── test_sse_real_transport.py
    └── test_types_validation.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .coveragerc
================================================
[run]
omit =
    examples/*
    tests/*
concurrency = multiprocessing
parallel = true
sigterm = true
data_file = .coverage
source = fastapi_mcp

[report]
show_missing = true

[paths]
source =
    fastapi_mcp/

================================================
FILE: .cursorignore
================================================
# Repomix output
!repomix-output.txt
!repomix-output.xml

================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior, including example code.

**System Info**
Please specify the relevant information of your work environment.


================================================
FILE: .github/ISSUE_TEMPLATE/documentation.md
================================================
---
name: Documentation
about: Report an issue related to the fastapi-mcp documentation/examples
title: ''
labels: documentation
assignees: ''

---




================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.


================================================
FILE: .github/codecov.yml
================================================
coverage:
  status:
    project:
      default:
        base: pr
        target: auto
        threshold: 0.5%
        informational: false
        only_pulls: true


================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 10
    labels:
      - "dependencies"
      - "github-actions"

  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 10
    labels:
      - "dependencies"
      - "python"

================================================
FILE: .github/pull_request_template.md
================================================
## Describe your changes

## Issue ticket number and link (if applicable)

## Screenshots of the feature / bugfix

## Checklist before requesting a review
- [ ] Added relevant tests
- [ ] Run ruff & mypy
- [ ] All tests pass


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  ruff:
    name: Ruff
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v5
        with:
          version: "0.6.12"
          enable-cache: true
          cache-dependency-glob: "uv.lock"

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version-file: ".python-version"

      - name: Install dependencies
        run: uv sync --all-extras --dev

      - name: Lint with Ruff
        run: uv run ruff check .

  mypy:
    name: MyPy
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v5
        with:
          version: "0.6.12"
          enable-cache: true
          cache-dependency-glob: "uv.lock"

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version-file: ".python-version"

      - name: Install dependencies
        run: uv sync --all-extras --dev

      - name: Type check with MyPy
        run: uv run mypy .

  test:
    name: Test Python ${{ matrix.python-version }}
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.10", "3.11", "3.12"]

    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v5
        with:
          version: "0.6.12"
          python-version: ${{ matrix.python-version }}
          enable-cache: true
          cache-dependency-glob: "uv.lock"

      - name: Install dependencies
        run: uv sync --all-extras --dev

      - name: Run tests
        run: uv run pytest --cov=fastapi_mcp --cov-report=xml

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          fail_ci_if_error: false


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

on:
  release:
    types: [created]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install uv
        uses: astral-sh/setup-uv@v5
        with:
          version: "0.6.12"
          enable-cache: true

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version-file: ".python-version"

      - name: Install build dependencies
        run: |
          uv sync --all-extras --dev
          uv pip install build twine

      - name: Build and publish
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          uv run python -m build
          uv run twine check dist/*
          uv run twine upload dist/*


================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
#  and can be added to the global gitignore or merged into this file.
.idea/
*.iml
*.iws
*.ipr
*.iws
.idea_modules/

# VSCode
.vscode/

# Ruff linter
.ruff_cache/

# Mac/OSX
.DS_Store

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini

# Repomix output
repomix-output.txt
repomix-output.xml

================================================
FILE: .pre-commit-config.yaml
================================================
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
        exclude: \.(md|mdx)$
      - id: check-yaml
      - id: check-added-large-files

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.9.10
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format


================================================
FILE: .python-version
================================================
3.12

================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.4.0]

🚀 **FastAPI-MCP now supports Streamable HTTP transport.**

HTTP transport is now the recommended approach, following the specification that positions HTTP as the standard while maintaining SSE for backwards compatibility.

### ⚠️ Breaking Changes
- **`mount()` method is deprecated** and will be removed in a future version. Use `mount_http()` for HTTP transport (recommended) or `mount_sse()` for SSE transport.

### Added
- 🎉 **Streamable HTTP Transport Support** - New `mount_http()` method implementing the MCP Streamable HTTP specification
- 🎉 **Stateful Session Management** - For both HTTP and SSE transports

## [0.3.7]

### Fixed
- 🐛 Fix a bug with OAuth default_scope (#123)

## [0.3.6]

Skipped 0.3.5 due to a broken release attempt.

### Added
- 🚀 Add configurable HTTP header forwarding (#181)

### Fixed
- 🐛 Fix a bug with handling FastAPI `root_path` parameter (#163)

## [0.3.4]

### Fixed
- 🐛 Update the `mcp` dependency to `1.8.1`. Fixes [Issue #134](https://github.com/tadata-org/fastapi_mcp/issues/134) that was caused after a breaking change in mcp sdk 1.8.0.

## [0.3.3]

Fixes the broken release from 0.3.2.

### Fixed
- 🐛 Fix critical bug in openapi conversion (missing `param_desc` definition) (#107, #99)
- 🐛 Fix non-ascii support (#66)

## [0.3.2] - Broken

This is a broken release and should not be used.

### Fixed
- 🐛 Fix a bug preventing simple setup of [basic token passthrough](docs/03_authentication_and_authorization.md#basic-token-passthrough)

## [0.3.1]

🚀 FastApiMCP now supports MCP Authorization!

You can now add MCP-compliant OAuth configuration in a FastAPI-native way, using your existing FastAPI `Depends()` that we all know and love.

### Added
- 🎉 Support for Authentication / Authorization compliant to [MCP 2025-03-26 Specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization), using OAuth 2.1. (#10)
- 🎉 Support passing http headers to tool calls (#82)

## [0.3.0]

🚀 FastApiMCP now works with ASGI-transport by default.

This means the `base_url` argument is redundant, and thus has been removed.

You can still set up an explicit base URL using the `http_client` argument, and injecting your own `httpx.AsyncClient` if necessary.

### Removed
- ⚠️ Breaking Change: Removed `base_url` argument since it's not used anymore by the MCP transport.

### Fixed
- 🐛 Fix short timeout issue (#71), increasing the default timeout to 10


## [0.2.0]

### Changed
- Complete refactor from function-based API to a new class-based API with `FastApiMCP`
- Explicit separation between MCP instance creation and mounting with `mcp = FastApiMCP(app)` followed by `mcp.mount()`
- FastAPI-native approach for transport providing more flexible routing options
- Updated minimum MCP dependency to v1.6.0

### Added
- Support for deploying MCP servers separately from API service
- Support for "refreshing" with `setup_server()` when dynamically adding FastAPI routes. Fixes [Issue #19](https://github.com/tadata-org/fastapi_mcp/issues/19)
- Endpoint filtering capabilities through new parameters:
  - `include_operations`: Expose only specific operations by their operation IDs
  - `exclude_operations`: Expose all operations except those with specified operation IDs
  - `include_tags`: Expose only operations with specific tags
  - `exclude_tags`: Expose all operations except those with specific tags

### Fixed
- FastAPI-native approach for transport. Fixes [Issue #28](https://github.com/tadata-org/fastapi_mcp/issues/28)
- Numerous bugs in OpenAPI schema to tool conversion, addressing [Issue #40](https://github.com/tadata-org/fastapi_mcp/issues/40) and [Issue #45](https://github.com/tadata-org/fastapi_mcp/issues/45)

### Removed
- Function-based API (`add_mcp_server`, `create_mcp_server`, etc.)
- Custom tool support via `@mcp.tool()` decorator

## [0.1.8]

### Fixed
- Remove unneeded dependency.

## [0.1.7]

### Fixed
- [Issue #34](https://github.com/tadata-org/fastapi_mcp/issues/34): Fix syntax error.

## [0.1.6]

### Fixed
- [Issue #23](https://github.com/tadata-org/fastapi_mcp/issues/23): Hide handle_mcp_connection tool.

## [0.1.5]

### Fixed
- [Issue #25](https://github.com/tadata-org/fastapi_mcp/issues/25): Dynamically creating tools function so tools are useable.

## [0.1.4]

### Fixed
- [Issue #8](https://github.com/tadata-org/fastapi_mcp/issues/8): Converted tools unuseable due to wrong passing of arguments.

## [0.1.3]

### Fixed
- Dependency resolution issue with `mcp` package and `pydantic-settings`

## [0.1.2]

### Changed
- Complete refactor: transformed from a code generator to a direct integration library
- Replaced the CLI-based approach with a direct API for adding MCP servers to FastAPI applications
- Integrated MCP servers now mount directly to FastAPI apps at runtime instead of generating separate code
- Simplified the API with a single `add_mcp_server` function for quick integration
- Removed code generation entirely in favor of runtime integration

### Added
- Main `add_mcp_server` function for simple MCP server integration
- Support for adding custom MCP tools alongside API-derived tools
- Improved test suite
- Manage with uv

### Removed
- CLI interface and all associated commands (generate, run, install, etc.)
- Code generation functionality

## [0.1.1] - 2024-07-03

### Fixed
- Added support for PEP 604 union type syntax (e.g., `str | None`) in FastAPI endpoints
- Improved type handling in model field generation for newer Python versions (3.10+)
- Fixed compatibility issues with modern type annotations in path parameters, query parameters, and Pydantic models

## [0.1.0] - 2024-03-08

### Added
- Initial release of FastAPI-MCP
- Core functionality for converting FastAPI applications to MCP servers
- CLI tool for generating, running, and installing MCP servers
- Automatic discovery of FastAPI endpoints
- Type-safe conversion from FastAPI endpoints to MCP tools
- Documentation preservation from FastAPI to MCP
- Claude integration for easy installation and use
- API integration that automatically makes HTTP requests to FastAPI endpoints
- Examples directory with sample FastAPI application
- Basic test suite

================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to FastAPI-MCP

First off, thank you for considering contributing to FastAPI-MCP!

## Development Setup

1.  Make sure you have Python 3.10+ installed
2.  Install [uv](https://docs.astral.sh/uv/getting-started/installation/) package manager
3.  Fork the repository
4.  Clone your fork

    ```bash
    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
    ```

5.  Set up the development environment:

    ```bash
    uv sync
    ```

    That's it! The `uv sync` command will automatically create and use a virtual environment.

6.  Install pre-commit hooks:

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

    Pre-commit hooks will automatically run checks (like ruff, formatting, etc.) when you make a commit, ensuring your code follows our style guidelines.

### Running Commands

You have two options for running commands:

1.  **With the virtual environment activated**:
    ```bash
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate

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

2.  **Without activating the virtual environment**:
    ```bash
    # Use uv run prefix for all commands
    uv run pytest
    uv run mypy .
    uv run ruff check .
    ```

Both approaches work - use whichever is more convenient for you.

> **Note:** For simplicity, commands in this guide are mostly written **without** the `uv run` prefix. If you haven't activated your virtual environment, remember to prepend `uv run` to all python-related commands and tools.

### Adding Dependencies

When adding new dependencies to the library:

1.  **Runtime dependencies** - packages needed to run the application:
    ```bash
    uv add new-package
    ```

2.  **Development dependencies** - packages needed for development, testing, or CI:
    ```bash
    uv add --group dev new-package
    ```

After adding dependencies, make sure to:
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"
    ```

## Development Process

1. Fork the repository and set the upstream remote
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run type checking (`mypy .`)
5. Run the tests (`pytest`)
6. Format your code (`ruff check .` and `ruff format .`). Not needed if pre-commit is installed, as it will run it for you.
7. Commit your changes (`git commit -m 'Add some amazing feature'`)
8. Push to the branch (`git push origin feature/amazing-feature`)
9. Open a Pull Request. Make sure the Pull Request's base branch is [the original repository's](https://github.com/tadata-org/fastapi_mcp/) `main` branch.

## Code Style

We use the following tools to ensure code quality:

- **ruff** for linting and formatting
- **mypy** for type checking

Please make sure your code passes all checks before submitting a pull request:

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

# Check types
mypy .
```

## Testing

We use pytest for testing. Please write tests for any new features and ensure all tests pass:

```bash
# Run all tests
pytest
```

## Pull Request Process

1. Ensure your code follows the style guidelines of the project
2. Update the README.md with details of changes if applicable
3. The versioning scheme we use is [SemVer](http://semver.org/)
4. Include a descriptive commit message
5. Your pull request will be merged once it's reviewed and approved

## Code of Conduct

Please note we have a code of conduct, please follow it in all your interactions with the project.

- Be respectful and inclusive
- Be collaborative
- When disagreeing, try to understand why
- A diverse community is a strong community

## Questions?

Don't hesitate to open an issue if you have any questions about contributing to FastAPI-MCP.

================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2024 Tadata Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: MANIFEST.in
================================================
include LICENSE
include README.md
include INSTALL.md
include pyproject.toml
include setup.py

recursive-include examples *.py *.md
recursive-include tests *.py

global-exclude *.py[cod] __pycache__ *.so *.dylib .DS_Store 

================================================
FILE: README.md
================================================
<p align="center"><a href="https://github.com/tadata-org/fastapi_mcp"><img src="https://github.com/user-attachments/assets/7e44e98b-a0ba-4aff-a68a-4ffee3a6189c" alt="fastapi-to-mcp" height=100/></a></p>

<div align="center">
  <span style="font-size: 0.85em; font-weight: normal;">Built by <a href="https://tadata.com">Tadata</a></span>
</div>

<h1 align="center">
  FastAPI-MCP
</h1>

<div align="center">
<a href="https://trendshift.io/repositories/14064" target="_blank"><img src="https://trendshift.io/api/badge/repositories/14064" alt="tadata-org%2Ffastapi_mcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>

<p align="center">Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!</p>
<div align="center">

[![PyPI version](https://img.shields.io/pypi/v/fastapi-mcp?color=%2334D058&label=pypi%20package)](https://pypi.org/project/fastapi-mcp/)
[![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-mcp.svg)](https://pypi.org/project/fastapi-mcp/)
[![FastAPI](https://img.shields.io/badge/FastAPI-009485.svg?logo=fastapi&logoColor=white)](#)
[![CI](https://github.com/tadata-org/fastapi_mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/tadata-org/fastapi_mcp/actions/workflows/ci.yml)
[![Coverage](https://codecov.io/gh/tadata-org/fastapi_mcp/branch/main/graph/badge.svg)](https://codecov.io/gh/tadata-org/fastapi_mcp)

</div>


<p align="center"><a href="https://github.com/tadata-org/fastapi_mcp"><img src="https://github.com/user-attachments/assets/b205adc6-28c0-4e3c-a68b-9c1a80eb7d0c" alt="fastapi-mcp-usage" height="400"/></a></p>


## Features

- **Authentication** built in, using your existing FastAPI dependencies!

- **FastAPI-native:** Not just another OpenAPI -> MCP converter

- **Zero/Minimal configuration** required - just point it at your FastAPI app and it works

- **Preserving schemas** of your request models and response models

- **Preserve documentation** of all your endpoints, just as it is in Swagger

- **Flexible deployment** - Mount your MCP server to the same app, or deploy separately

- **ASGI transport** - Uses FastAPI's ASGI interface directly for efficient communication


## Hosted Solution

If you prefer a managed hosted solution check out [tadata.com](https://tadata.com).

## Installation

We recommend using [uv](https://docs.astral.sh/uv/), a fast Python package installer:

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

Alternatively, you can install with pip:

```bash
pip install fastapi-mcp
```

## Basic Usage

The simplest way to use FastAPI-MCP is to add an MCP server directly to your FastAPI application:

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

app = FastAPI()

mcp = FastApiMCP(app)

# Mount the MCP server directly to your FastAPI app
mcp.mount()
```

That's it! Your auto-generated MCP server is now available at `https://app.base.url/mcp`.

## Documentation, Examples and Advanced Usage

FastAPI-MCP provides [comprehensive documentation](https://fastapi-mcp.tadata.com/). Additionaly, check out the [examples directory](examples) for code samples demonstrating these features in action.

## FastAPI-first Approach

FastAPI-MCP is designed as a native extension of FastAPI, not just a converter that generates MCP tools from your API. This approach offers several key advantages:

- **Native dependencies**: Secure your MCP endpoints using familiar FastAPI `Depends()` for authentication and authorization

- **ASGI transport**: Communicates directly with your FastAPI app using its ASGI interface, eliminating the need for HTTP calls from the MCP to your API

- **Unified infrastructure**: Your FastAPI app doesn't need to run separately from the MCP server (though [separate deployment](https://fastapi-mcp.tadata.com/advanced/deploy#deploying-separately-from-original-fastapi-app) is also supported)

This design philosophy ensures minimum friction when adding MCP capabilities to your existing FastAPI services.


## Development and Contributing

Thank you for considering contributing to FastAPI-MCP! We encourage the community to post Issues and create Pull Requests.

Before you get started, please see our [Contribution Guide](CONTRIBUTING.md).

## Community

Join [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 your experiences with FastAPI-MCP.

## Requirements

- Python 3.10+ (Recommended 3.12)
- uv

## License

MIT License. Copyright (c) 2025 Tadata Inc.


================================================
FILE: README_zh-CN.md
================================================
<p align="center"><a href="https://github.com/tadata-org/fastapi_mcp"><img src="https://github.com/user-attachments/assets/609d5b8b-37a1-42c4-87e2-f045b60026b1" alt="fastapi-to-mcp" height="100"/></a></p>
<h1 align="center">FastAPI-MCP</h1>
<p align="center">一个零配置工具,用于自动将 FastAPI 端点公开为模型上下文协议(MCP)工具。</p>
<div align="center">

[![PyPI version](https://badge.fury.io/py/fastapi-mcp.svg)](https://pypi.org/project/fastapi-mcp/)
[![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-mcp.svg)](https://pypi.org/project/fastapi-mcp/)
[![FastAPI](https://img.shields.io/badge/FastAPI-009485.svg?logo=fastapi&logoColor=white)](#)
![](https://badge.mcpx.dev?type=dev 'MCP Dev')
[![CI](https://github.com/tadata-org/fastapi_mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/tadata-org/fastapi_mcp/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/tadata-org/fastapi_mcp/branch/main/graph/badge.svg)](https://codecov.io/gh/tadata-org/fastapi_mcp)

</div>

<p align="center"><a href="https://github.com/tadata-org/fastapi_mcp"><img src="https://github.com/user-attachments/assets/1cba1bf2-2fa4-46c7-93ac-1e9bb1a95257" alt="fastapi-mcp-usage" height="400"/></a></p>

> 注意:最新版本请参阅 [README.md](README.md).

## 特点

- **直接集成** - 直接将 MCP 服务器挂载到您的 FastAPI 应用
- **零配置** - 只需指向您的 FastAPI 应用即可工作
- **自动发现** - 所有 FastAPI 端点并转换为 MCP 工具
- **保留模式** - 保留您的请求模型和响应模型的模式
- **保留文档** - 保留所有端点的文档,就像在 Swagger 中一样
- **灵活部署** - 将 MCP 服务器挂载到同一应用,或单独部署
- **ASGI 传输** - 默认使用 FastAPI 的 ASGI 接口直接通信,提高效率

## 安装

我们推荐使用 [uv](https://docs.astral.sh/uv/),一个快速的 Python 包安装器:

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

或者,您可以使用 pip 安装:

```bash
pip install fastapi-mcp
```

## 基本用法

使用 FastAPI-MCP 的最简单方法是直接将 MCP 服务器添加到您的 FastAPI 应用中:

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

app = FastAPI()

mcp = FastApiMCP(app)

# 直接将 MCP 服务器挂载到您的 FastAPI 应用
mcp.mount()
```

就是这样!您的自动生成的 MCP 服务器现在可以在 `https://app.base.url/mcp` 访问。

## 工具命名

FastAPI-MCP 使用 FastAPI 路由中的`operation_id`作为 MCP 工具的名称。如果您不指定`operation_id`,FastAPI 会自动生成一个,但这些名称可能比较晦涩。

比较以下两个端点定义:

```python
# 自动生成的 operation_id(类似于 "read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

# 显式 operation_id(工具将被命名为 "get_user_info")
@app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
    return {"user_id": user_id}
```

为了获得更清晰、更直观的工具名称,我们建议在 FastAPI 路由定义中添加显式的`operation_id`参数。

要了解更多信息,请阅读 FastAPI 官方文档中关于 [路径操作的高级配置](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/) 的部分。

## 高级用法

FastAPI-MCP 提供了多种方式来自定义和控制 MCP 服务器的创建和配置。以下是一些高级用法模式:

### 自定义模式描述

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

app = FastAPI()

mcp = FastApiMCP(
    app,
    name="我的 API MCP",
    describe_all_responses=True,     # 在工具描述中包含所有可能的响应模式
    describe_full_response_schema=True  # 在工具描述中包含完整的 JSON 模式
)

mcp.mount()
```

### 自定义公开的端点

您可以使用 Open API 操作 ID 或标签来控制哪些 FastAPI 端点暴露为 MCP 工具:

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

app = FastAPI()

# 仅包含特定操作
mcp = FastApiMCP(
    app,
    include_operations=["get_user", "create_user"]
)

# 排除特定操作
mcp = FastApiMCP(
    app,
    exclude_operations=["delete_user"]
)

# 仅包含具有特定标签的操作
mcp = FastApiMCP(
    app,
    include_tags=["users", "public"]
)

# 排除具有特定标签的操作
mcp = FastApiMCP(
    app,
    exclude_tags=["admin", "internal"]
)

# 结合操作 ID 和标签(包含模式)
mcp = FastApiMCP(
    app,
    include_operations=["user_login"],
    include_tags=["public"]
)

mcp.mount()
```

关于过滤的注意事项:
- 您不能同时使用`include_operations`和`exclude_operations`
- 您不能同时使用`include_tags`和`exclude_tags`
- 您可以将操作过滤与标签过滤结合使用(例如,使用`include_operations`和`include_tags`)
- 当结合过滤器时,将采取贪婪方法。匹配任一标准的端点都将被包含

### 与原始 FastAPI 应用分开部署

您不限于在创建 MCP 的同一个 FastAPI 应用上提供 MCP 服务。

您可以从一个 FastAPI 应用创建 MCP 服务器,并将其挂载到另一个应用上:

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

# 您的 API 应用
api_app = FastAPI()
# ... 在 api_app 上定义您的 API 端点 ...

# 一个单独的 MCP 服务器应用
mcp_app = FastAPI()

# 从 API 应用创建 MCP 服务器
mcp = FastApiMCP(api_app)

# 将 MCP 服务器挂载到单独的应用
mcp.mount(mcp_app)

# 现在您可以分别运行两个应用:
# uvicorn main:api_app --host api-host --port 8001
# uvicorn main:mcp_app --host mcp-host --port 8000
```

### 在 MCP 服务器创建后添加端点

如果您在创建 MCP 服务器后向 FastAPI 应用添加端点,您需要刷新服务器以包含它们:

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

app = FastAPI()
# ... 定义初始端点 ...

# 创建 MCP 服务器
mcp = FastApiMCP(app)
mcp.mount()

# 在 MCP 服务器创建后添加新端点
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
    return {"message": "Hello, world!"}

# 刷新 MCP 服务器以包含新端点
mcp.setup_server()
```

### 与 FastAPI 应用的通信

FastAPI-MCP 默认使用 ASGI 传输,这意味着它直接与您的 FastAPI 应用通信,而不需要发送 HTTP 请求。这样更高效,也不需要基础 URL。

如果您需要指定自定义基础 URL 或使用不同的传输方法,您可以提供自己的 `httpx.AsyncClient`:

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

app = FastAPI()

# 使用带有特定基础 URL 的自定义 HTTP 客户端
custom_client = httpx.AsyncClient(
    base_url="https://api.example.com",
    timeout=30.0
)

mcp = FastApiMCP(
    app,
    http_client=custom_client
)

mcp.mount()
```

## 示例

请参阅 [examples](examples) 目录以获取完整示例。

## 使用 SSE 连接到 MCP 服务器

一旦您的集成了 MCP 的 FastAPI 应用运行,您可以使用任何支持 SSE 的 MCP 客户端连接到它,例如 Cursor:

1. 运行您的应用。

2. 在 Cursor -> 设置 -> MCP 中,使用您的 MCP 服务器端点的URL(例如,`http://localhost:8000/mcp`)作为 sse。

3. Cursor 将自动发现所有可用的工具和资源。

## 使用 [mcp-proxy stdio](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#1-stdio-to-sse) 连接到 MCP 服务器

如果您的 MCP 客户端不支持 SSE,例如 Claude Desktop:

1. 运行您的应用。

2. 安装 [mcp-proxy](https://github.com/sparfenyuk/mcp-proxy?tab=readme-ov-file#installing-via-pypi),例如:`uv tool install mcp-proxy`。

3. 在 Claude Desktop 的 MCP 配置文件(`claude_desktop_config.json`)中添加:

在 Windows 上:
```json
{
  "mcpServers": {
    "my-api-mcp-proxy": {
        "command": "mcp-proxy",
        "args": ["http://127.0.0.1:8000/mcp"]
    }
  }
}
```
在 MacOS 上:
```json
{
  "mcpServers": {
    "my-api-mcp-proxy": {
        "command": "/Full/Path/To/Your/Executable/mcp-proxy",
        "args": ["http://127.0.0.1:8000/mcp"]
    }
  }
}
```
通过在终端运行`which mcp-proxy`来找到 mcp-proxy 的路径。

4. Claude Desktop 将自动发现所有可用的工具和资源

## 开发和贡献

感谢您考虑为 FastAPI-MCP 做出贡献!我们鼓励社区发布问题和拉取请求。

在开始之前,请参阅我们的 [贡献指南](CONTRIBUTING.md)。

## 社区

加入 [MCParty Slack 社区](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg),与其他 MCP 爱好者联系,提问,并分享您使用 FastAPI-MCP 的经验。

## 要求

- Python 3.10+(推荐3.12)
- uv

## 许可证

MIT License. Copyright (c) 2024 Tadata Inc.


================================================
FILE: docs/advanced/asgi.mdx
================================================
---
title: Transport
description: How to communicate with the FastAPI app
icon: microchip
---

FastAPI-MCP uses ASGI transport by default, which means it communicates directly with your FastAPI app without making HTTP requests. This is more efficient and doesn't require a base URL.

It's not even necessary that the FastAPI server will run.

If you need to specify a custom base URL or use a different transport method, you can provide your own `httpx.AsyncClient`:

```python {7-10, 14}
import httpx
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

custom_client = httpx.AsyncClient(
    base_url="https://api.example.com",
    timeout=30.0
)

mcp = FastApiMCP(
    app,
    http_client=custom_client
)

mcp.mount()
```


================================================
FILE: docs/advanced/auth.mdx
================================================
---
title: Authentication & Authorization
icon: key
---

FastAPI-MCP supports authentication and authorization using your existing FastAPI dependencies.

It also supports the full OAuth 2 flow, compliant with [MCP Spec 2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).

It's worth noting that most MCP clients currently do not support the latest MCP spec, so for our examples we might use a bridge client such as `npx mcp-remote`. We recommend you use it as well, and we'll show our examples using it.

## Basic Token Passthrough

If you just want to be able to pass a valid authorization header, without supporting a full authentication flow, you don't need to do anything special.

You just need to make sure your MCP client is sending it:

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

This is enough to pass the authorization header to your FastAPI endpoints.

Optionally, if you want your MCP server to reject requests without an authorization header, you can add a dependency:

```python {1-2, 7-9}
from fastapi import Depends
from fastapi_mcp import FastApiMCP, AuthConfig

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

For a complete working example of authorization header, check out the [Token Passthrough Example](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py) in the examples folder.

## OAuth Flow

FastAPI-MCP supports the full OAuth 2 flow, compliant with [MCP Spec 2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).

It would look something like this:

```python {7-16}
from fastapi import Depends
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="MCP With OAuth",
    auth_config=AuthConfig(
        issuer=f"https://auth.example.com/",
        authorize_url=f"https://auth.example.com/authorize",
        oauth_metadata_url=f"https://auth.example.com/.well-known/oauth-authorization-server",
        audience="my-audience",
        client_id="my-client-id",
        client_secret="my-client-secret",
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
    ),
)

mcp.mount_http()
```

And you can call it like:

```json
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "8080"  // Optional port number. Necessary if you want your OAuth to work and you don't have dynamic client registration.
      ]
    }
  }
}
```

You can use it with any OAuth provider that supports the OAuth 2 spec. See explanation on [AuthConfig](#authconfig-explained) for more details.

## Custom OAuth Metadata

If you already have a properly configured OAuth server that works with MCP clients, or if you want full control over the metadata, you can provide your own OAuth metadata directly:

```python {9, 22}
from fastapi import Depends
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="MCP With Custom OAuth",
    auth_config=AuthConfig(
        # Provide your own complete OAuth metadata
        custom_oauth_metadata={
            "issuer": "https://auth.example.com",
            "authorization_endpoint": "https://auth.example.com/authorize",
            "token_endpoint": "https://auth.example.com/token",
            "registration_endpoint": "https://auth.example.com/register",
            "scopes_supported": ["openid", "profile", "email"],
            "response_types_supported": ["code"],
            "grant_types_supported": ["authorization_code"],
            "token_endpoint_auth_methods_supported": ["none"],
            "code_challenge_methods_supported": ["S256"]
        },

        # Your auth checking dependency
        dependencies=[Depends(verify_auth)],
    ),
)

mcp.mount_http()
```

This approach gives you complete control over the OAuth metadata and is useful when:
- You have a fully MCP-compliant OAuth server already configured
- You need to customize the OAuth flow beyond what the proxy approach offers
- You're using a custom or specialized OAuth implementation

For this to work, you have to make sure mcp-remote is running [on a fixed port](#add-a-fixed-port-to-mcp-remote), for example `8080`, and then configure the callback URL to `http://127.0.0.1:8080/oauth/callback` in your OAuth provider.

## Working Example with Auth0

For a complete working example of OAuth integration with Auth0, check out the [Auth0 Example](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py) in the examples folder. This example demonstrates the simple case of using Auth0 as an OAuth provider, with a working example of the OAuth flow.

For it to work, you need an .env file in the root of the project with the following variables:

```
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
```

You also need to make sure to configure callback URLs properly in your Auth0 dashboard.

## AuthConfig Explained

### `setup_proxies=True`

Most OAuth providers need some adaptation to work with MCP clients. This is where `setup_proxies=True` comes in - it creates proxy endpoints that make your OAuth provider compatible with MCP clients:

```python
mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(
        # Your OAuth provider information
        issuer="https://auth.example.com",
        authorize_url="https://auth.example.com/authorize",
        oauth_metadata_url="https://auth.example.com/.well-known/oauth-authorization-server",

        # Credentials registered with your OAuth provider
        client_id="your-client-id",
        client_secret="your-client-secret",

        # Recommended, since some clients don't specify them
        audience="your-api-audience",
        default_scope="openid profile email",

        # Your auth checking dependency
        dependencies=[Depends(verify_auth)],

        # Create compatibility proxies - usually needed!
        setup_proxies=True,
    ),
)
```

You also need to make sure to configure callback URLs properly in your OAuth provider. With mcp-remote for example, you have to [use a fixed port](#add-a-fixed-port-to-mcp-remote).

### Why Use Proxies?

Proxies solve several problems:

1.  **Missing registration endpoints**:  
    The MCP spec expects OAuth providers to support [dynamic client registration (RFC 7591)](https://datatracker.ietf.org/doc/html/rfc7591), but many don't.
    Furthermore, dynamic client registration is probably overkill for most use cases.
    The `setup_fake_dynamic_registration` option (True by default) creates a compatible endpoint that just returns a static client ID and secret.

2.  **Scope handling**:  
    Some MCP clients don't properly request scopes, so our proxy adds the necessary scopes for you.

3.  **Audience requirements**:  
    Some OAuth providers require an audience parameter that MCP clients don't always provide. The proxy adds this automatically.

### Add a fixed port to mcp-remote

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

Normally, mcp-remote will start on a random port, making it impossible to configure the OAuth provider's callback URL properly.

You have to make sure mcp-remote is running on a fixed port, for example `8080`, and then configure the callback URL to `http://127.0.0.1:8080/oauth/callback` in your OAuth provider.


================================================
FILE: docs/advanced/deploy.mdx
================================================
---
title: Deploying the Server
icon: play
---

## Deploying separately from original FastAPI app

You are not limited to serving the MCP on the same FastAPI app from which it was created.

You can create an MCP server from one FastAPI app, and mount it to a different app:

```python {9, 15, }
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

# Your API app
api_app = FastAPI()
# ... define your API endpoints on api_app ...

# A separate app for the MCP server
mcp_app = FastAPI()

# Create MCP server from the API app
mcp = FastApiMCP(api_app)

# Mount the MCP server to the separate app
mcp.mount_http(mcp_app)
```

Then, you can run both apps separately:

```bash
uvicorn main:api_app --host api-host --port 8001
uvicorn main:mcp_app --host mcp-host --port 8000
```

================================================
FILE: docs/advanced/refresh.mdx
================================================
---
title: Refreshing the Server
description: Adding endpoints after MCP server creation
icon: arrows-rotate
---

If you add endpoints to your FastAPI app after creating the MCP server, you'll need to refresh the server to include them:

```python {9-12, 15}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(app)
mcp.mount_http()

# Add new endpoints after MCP server creation
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
    return {"message": "Hello, world!"}

# Refresh the MCP server to include the new endpoint
mcp.setup_server()
```

================================================
FILE: docs/advanced/transport.mdx
================================================
---
title: MCP Transport
description: Understanding MCP transport methods and how to choose between them
icon: car
---

FastAPI-MCP supports two MCP transport methods for client-server communication: **HTTP transport** (recommended) and **SSE transport** (backwards compatibility).

## HTTP Transport (Recommended)

HTTP transport is the **recommended** transport method as it implements the latest MCP Streamable HTTP specification. It provides better session management, more robust connection handling, and aligns with standard HTTP practices.

### Using HTTP Transport

```python {7}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app)

# Mount using HTTP transport (recommended)
mcp.mount_http()
```

## SSE Transport (Backwards Compatibility)

SSE (Server-Sent Events) transport is maintained for backwards compatibility with older MCP implementations.

### Using SSE Transport

```python {7}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app)

# Mount using SSE transport (backwards compatibility)
mcp.mount_sse()
```

## Advanced Configuration

Both transport methods support the same FastAPI integration features like custom routing and authentication:

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

app = FastAPI()
router = APIRouter(prefix="/api/v1")

mcp = FastApiMCP(app)

# Mount to custom path with HTTP transport
mcp.mount_http(router, mount_path="/my-http")

# Or with SSE transport
mcp.mount_sse(router, mount_path="/my-sse")
```

## Client Connection Examples

### HTTP Transport Client Connection

For HTTP transport, MCP clients connect directly to the HTTP endpoint:

```json
{
  "mcpServers": {
    "fastapi-mcp": {
      "url": "http://localhost:8000/mcp"
    }
  }
}
```

### SSE Transport Client Connection

For SSE transport, MCP clients use the same URL but communicate via Server-Sent Events:

```json
{
  "mcpServers": {
    "fastapi-mcp": {
      "url": "http://localhost:8000/sse"
    }
  }
}
```


================================================
FILE: docs/configurations/customization.mdx
================================================
---
title: Customization
icon: pen
---

## Server metadata

You can define the MCP server name and description by modifying:

```python {8-9}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,
    name="My API MCP",
    description="Very cool MCP server",
)
mcp.mount_http()
```

## Tool and schema descriptions

When creating the MCP server you can include all possible response schemas in tool descriptions by changing the flag `describe_all_responses`, or include full JSON schema in tool descriptions by changing `describe_full_response_schema`:

```python {10-11}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,
    name="My API MCP",
    description="Very cool MCP server",
    describe_all_responses=True,
    describe_full_response_schema=True
)

mcp.mount_http()
```

## Customizing Exposed Endpoints

You can control which FastAPI endpoints are exposed as MCP tools using Open API operation IDs or tags to:
- Only include specific operations
- Exclude specific operations
- Only include operations with specific tags
- Exclude operations with specific tags
- Combine operation IDs and tags

### Code samples

The relevant arguments for these configurations are `include_operations`, `exclude_operations`, `include_tags`, `exclude_tags` and can be used as follows:

<CodeGroup>
    ```python Include Operations {8}
    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP

    app = FastAPI()

    mcp = FastApiMCP(
        app,
        include_operations=["get_user", "create_user"]
    )
    mcp.mount_http()
    ```

    ```python Exclude Operations {8}
    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP

    app = FastAPI()

    mcp = FastApiMCP(
        app,
        exclude_operations=["delete_user"]
    )
    mcp.mount_http()
    ```

    ```python Include Tags {8}
    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP

    app = FastAPI()

    mcp = FastApiMCP(
        app,
        include_tags=["users", "public"]
    )
    mcp.mount_http()
    ```

    ```python Exclude Tags {8}
    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP

    app = FastAPI()

    mcp = FastApiMCP(
        app,
        exclude_tags=["admin", "internal"]
    )
    mcp.mount_http()
    ```

    ```python Combined (include mode) {8-9}
    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP

    app = FastAPI()

    mcp = FastApiMCP(
        app,
        include_operations=["user_login"],
        include_tags=["public"]
    )
    mcp.mount_http()
    ```
</CodeGroup>

### Notes on filtering

- You cannot use both `include_operations` and `exclude_operations` at the same time
- You cannot use both `include_tags` and `exclude_tags` at the same time
- You can combine operation filtering with tag filtering (e.g., use `include_operations` with `include_tags`)
- When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included

================================================
FILE: docs/configurations/tool-naming.mdx
================================================
---
title: Tool Naming
icon: input-text    
---

FastAPI-MCP uses the `operation_id` from your FastAPI routes as the MCP tool names. When you don't specify an `operation_id`, FastAPI auto-generates one, but these can be cryptic.

Compare these two endpoint definitions:

```python {2, 7}
# Auto-generated operation_id (something like "read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

# Explicit operation_id (tool will be named "get_user_info")
@app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
    return {"user_id": user_id}
```

For clearer, more intuitive tool names, we recommend adding explicit `operation_id` parameters to your FastAPI route definitions.

To find out more, read FastAPI's official docs about [advanced config of path operations.](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/)


================================================
FILE: docs/docs.json
================================================
{
  "$schema": "https://mintlify.com/docs.json",
  "name": "FastAPI MCP",
  "background": {
    "color": {
      "dark": "#222831",
      "light": "#EEEEEE"
    },
    "decoration": "windows"
  },
  "colors": {
    "primary": "#6d45dc",
    "light": "#9f8ded",
    "dark": "#6a42d7"
  },
  "description": "Convert your FastAPI app into a MCP server with zero configuration",
  "favicon": "media/favicon.png",
  "navigation": {
    "groups": [
      {
        "group": "Getting Started",
        "pages": [
          "getting-started/welcome",
          "getting-started/installation",
          "getting-started/quickstart",
          "getting-started/FAQ",
          "getting-started/best-practices"
        ]
      },
      {
        "group": "Configurations",
        "pages": ["configurations/tool-naming", "configurations/customization"]
      },
      {
        "group": "Advanced Usage",
        "pages": [
          "advanced/auth",
          "advanced/deploy",
          "advanced/refresh",
          "advanced/asgi",
          "advanced/transport"
        ]
      }
    ],
    "global": {
      "anchors": [
        {
          "anchor": "Documentation",
          "href": "https://fastapi-mcp.tadata.com/",
          "icon": "book-open-cover"
        },
        {
          "anchor": "Community",
          "href": "https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg",
          "icon": "slack"
        },
        {
          "anchor": "Blog",
          "href": "https://medium.com/@miki_45906",
          "icon": "newspaper"
        }
      ]
    }
  },
  "logo": {
    "light": "/media/dark_logo.png",
    "dark": "/media/light_logo.png",
    "href": "https://tadata.com/"
  },
  "navbar": {
    "primary": {
      "href": "https://github.com/tadata-org/fastapi_mcp",
      "type": "github"
    }
  },
  "footer": {
    "socials": {
      "x": "https://x.com/makhlevich",
      "github": "https://github.com/tadata-org/fastapi_mcp",
      "website": "https://tadata.com/"
    }
  },
  "theme": "mint"
}


================================================
FILE: docs/getting-started/FAQ.mdx
================================================
---
title: FAQ
description: Frequently Asked Questions
icon: question
---

## Usage
### How do I configure HTTP request timeouts?
By default, HTTP requests timeout after 5 seconds. If you have API endpoints that take longer to respond, you can configure a custom timeout by injecting your own httpx client. 

For a working example, see [Configure HTTP Timeout Example](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/07_configure_http_timeout_example.py).

### Why are my tools not showing up in the MCP inspector?
If you add endpoints after creating and mounting the MCP server, they won't be automatically registered as tools. You need to either:
1. Move the MCP creation after all your endpoint definitions
2. Call `mcp.setup_server()` after adding new endpoints to re-register all tools

For a working example, see [Reregister Tools Example](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py).

### Can I add custom tools other than FastAPI endpoints?
Currently, FastApiMCP only supports tools that are derived from FastAPI endpoints. If you need to add custom tools that don't correspond to API endpoints, you can:
1. Create a FastAPI endpoint that wraps your custom functionality
2. Contribute to the project by implementing custom tool support

Follow the discussion in [issue #75](https://github.com/tadata-org/fastapi_mcp/issues/75) for updates on this feature request.
If you have specific use cases for custom tools, please share them in the issue to help guide the implementation.

### How do I test my FastApiMCP server is working?
To verify your FastApiMCP server is working properly, you can use the MCP Inspector tool. Here's how:

1. Start your FastAPI application
2. Open a new terminal and run the MCP Inspector:
   ```bash
   npx @modelcontextprotocol/inspector
   ```
3. Connect to your MCP server by entering the mount path URL (default: `http://127.0.0.1:8000/mcp`)
4. Navigate to the `Tools` section and click `List Tools` to see all available endpoints
5. Test an endpoint by:
   - Selecting a tool from the list
   - Filling in any required parameters
   - Clicking `Run Tool` to execute
6. Check your server logs for additional debugging information if needed

This will help confirm that your MCP server is properly configured and your endpoints are accessible.

## Development

### Can I contribute to the project?
Yes! Please read our [CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md) file for detailed guidelines on how to contribute to the project and where to start.

## Support

### Where can I get help?
- Check the documentation
- Open an issue on GitHub
- Join our community chat [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg)


================================================
FILE: docs/getting-started/best-practices.mdx
================================================
---
title: Best Practices
icon: thumbs-up
---

This guide outlines best practices for converting standard APIs into Model Context Protocol (MCP) tools for use with AI agents. Proper tool design helps ensure LLMs can understand and safely use your APIs.
By following these best practices, you can build safer, more intuitive MCP tools that enhance the capabilities of LLM agents.


## Tool Selection

- **Be selective:**  
  Avoid exposing every endpoint as a tool. LLM clients perform better with a limited number of well-defined tools, and providers often impose tool limits.

- **Prioritize safety:**  
  Do **not** expose `PUT` or `DELETE` endpoints unless absolutely necessary. LLMs are non-deterministic and could unintentionally alter or damage systems or databases.

- **Focus on data retrieval:**  
  Prefer `GET` endpoints that return data safely and predictably.

- **Emphasize meaningful workflows:**  
  Expose endpoints that reflect clear, goal-oriented tasks. Tools with focused actions are easier for agents to understand and use effectively.

## Tool Naming

- **Use short, descriptive names:**  
  Helps LLMs select and use the right tool. Know that some MCP clients restrict tool name length. 

- **Follow naming constraints:**
  - Must start with a letter
  - Can include only letters, numbers, and underscores
  - Avoid hyphens (e.g., AWS Nova does **not** support them)
  - Use either `camelCase` or `snake_case` consistently across all tools

- **Ensure uniqueness:**  
  Each tool name should be unique and clearly indicate its function.

## Documentation

- **Describe every tool meaningfully:**  
  Provide a clear and concise summary of what each tool does.

- **Include usage examples and parameter descriptions:**  
  These help LLMs understand how to use the tool correctly.

- **Standardize documentation across tools:**  
  Keep formatting and structure consistent to maintain quality and readability.




================================================
FILE: docs/getting-started/installation.mdx
================================================
---
title: Installation
icon: arrow-down-to-line
---

## Install FastAPI-MCP

We recommend using [uv](https://docs.astral.sh/uv/), a fast Python package installer:

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

Alternatively, you can install with `pip` or `uv pip`:

<CodeGroup>
    ```bash uv
    uv pip install fastapi-mcp
    ```

    ```bash pip
    pip install fastapi-mcp
    ```
</CodeGroup>


================================================
FILE: docs/getting-started/quickstart.mdx
================================================
---
title: Quickstart
icon: rocket
---

This guide will help you quickly run your first MCP server using FastAPI-MCP.

If you haven't already installed FastAPI-MCP, follow the [installation instructions](/getting-started/installation).

## Creating a basic MCP server

To create a basic MCP server, import or create a FastAPI app, wrap it with the `FastApiMCP` class and mount the MCP to your existing application:

```python {2, 8, 11}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

# Create (or import) a FastAPI app
app = FastAPI()

# Create an MCP server based on this app
mcp = FastApiMCP(app)

# Mount the MCP server directly to your app
mcp.mount_http()
```

For more usage examples, see [Examples](https://github.com/tadata-org/fastapi_mcp/tree/main/examples) section in the project.

## Running the server

By running your FastAPI, your MCP will run at `https://app.base.url/mcp`.

For example, by using uvicorn, add to your code:
```python {9-11}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(app)
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```
and run the server using `python fastapi_mcp_server.py`, which will serve you the MCP at `http://localhost:8000/mcp`.

## Connecting a client to the MCP server

Once your FastAPI app with MCP integration is running, you would want to connect it to an MCP client.

### Connecting to the MCP Server using SSE

For any MCP client supporting SSE, you will simply need to provide the MCP url.

All the most popular MCP clients (Claude Desktop, Cursor & Windsurf) use the following config format:

```json
{
  "mcpServers": {
    "fastapi-mcp": {
      "url": "http://localhost:8000/mcp"
    }
  }
}
```

### Connecting to the MCP Server using [mcp-remote](https://www.npmjs.com/package/mcp-remote)

If you want to support authentication, or your MCP client does not support SSE, we recommend using `mcp-remote` as a bridge.

```json
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "8080"  // Optional port number. Necessary if you want your OAuth to work and you don't have dynamic client registration.
      ]
    }
  }
}
```





================================================
FILE: docs/getting-started/welcome.mdx
================================================
---
title: "Welcome to FastAPI-MCP!"
sidebarTitle: "Welcome!"
description: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!

icon: hand-wave
---

MCP (Model Context Protocol) is the emerging standard to define how AI agents communicate with applications. Using FastAPI-MCP, creating a secured  MCP server to your application takes only 3 lines of code:

```python {2, 6, 7}
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(app)
mcp.mount_http()
```
That's it! Your auto-generated MCP server is now available at `https://app.base.url/mcp`

## Features

- [**Authentication**](/advanced/auth) built in, using your existing FastAPI dependencies!

- **FastAPI-native:** Not just another OpenAPI -> MCP converter

- **Zero configuration** required - just point it at your FastAPI app and it works

- **Preserving schemas** of your request models and response models

- **Preserve documentation** of all your endpoints, just as it is in Swagger

- [**Flexible deployment**](/advanced/deploy) - Mount your MCP server to the same app, or deploy separately

- [**ASGI interface**](/advanced/asgi) - Uses FastAPI's ASGI interface directly for efficient internal communication

## Hosted Solution

If you prefer a managed hosted solution check out [tadata.com](https://tadata.com).


================================================
FILE: examples/01_basic_usage_example.py
================================================
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)


================================================
FILE: examples/02_full_schema_description_example.py
================================================
"""
This example shows how to describe the full response schema instead of just a response example.
"""

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,
    name="Item API MCP",
    description="MCP server for the Item API",
    describe_full_response_schema=True,  # Describe the full response JSON-schema instead of just a response example
    describe_all_responses=True,  # Describe all the possible responses instead of just the success (2XX) response
)

mcp.mount_http()

if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/03_custom_exposed_endpoints_example.py
================================================
"""
This example shows how to customize exposing endpoints by filtering operation IDs and tags.
Notes on filtering:
- You cannot use both `include_operations` and `exclude_operations` at the same time
- You cannot use both `include_tags` and `exclude_tags` at the same time
- You can combine operation filtering with tag filtering (e.g., use `include_operations` with `include_tags`)
- When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included
"""

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

from fastapi_mcp import FastApiMCP

setup_logging()

# Examples demonstrating how to filter MCP tools by operation IDs and tags

# 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"],
)

# Filter by excluding specific tags
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)

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

# 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")

if __name__ == "__main__":
    import uvicorn

    print("Server is running with multiple MCP endpoints:")
    print(" - /include-operations-mcp: Only get_item and list_items operations")
    print(" - /exclude-operations-mcp: All operations except create_item, update_item, and delete_item")
    print(" - /include-tags-mcp: Only operations with the 'items' tag")
    print(" - /exclude-tags-mcp: All operations except those with the 'search' tag")
    print(" - /combined-include-mcp: Operations with 'search' tag or delete_item operation")
    uvicorn.run(app, host="0.0.0.0", port=8000)


================================================
FILE: examples/04_separate_server_example.py
================================================
"""
This example shows how to run the MCP server and the FastAPI app separately.
You can create an MCP server from one FastAPI app, and mount it to a different app.
"""

from fastapi import FastAPI

from examples.shared.apps.items import app
from examples.shared.setup import setup_logging

from fastapi_mcp import FastApiMCP

setup_logging()

MCP_SERVER_HOST = "localhost"
MCP_SERVER_PORT = 8000
ITEMS_API_HOST = "localhost"
ITEMS_API_PORT = 8001


# Take the FastAPI app only as a source for MCP server generation
mcp = FastApiMCP(app)

# Mount the MCP server to a separate FastAPI app
mcp_app = FastAPI()
mcp.mount_http(mcp_app)

# Run the MCP server separately from the original FastAPI app.
# It still works 🚀
# Your original API is **not exposed**, only via the MCP server.
if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/05_reregister_tools_example.py
================================================
"""
This example shows how to re-register tools if you add endpoints after the MCP server was created.
"""

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

from fastapi_mcp import FastApiMCP

setup_logging()

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


# This endpoint will not be registered as a tool, since it was added after the MCP instance was created
@app.get("/new/endpoint/", operation_id="new_endpoint", response_model=dict[str, str])
async def new_endpoint():
    return {"message": "Hello, world!"}


# But if you re-run the setup, the new endpoints will now be exposed.
mcp.setup_server()


if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/06_custom_mcp_router_example.py
================================================
"""
This example shows how to mount the MCP server to a specific APIRouter, giving a custom mount path.
"""

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

from fastapi import APIRouter
from fastapi_mcp import FastApiMCP

setup_logging()

other_router = APIRouter(prefix="/other/route")
app.include_router(other_router)

mcp = FastApiMCP(app)

# Mount the MCP server to a specific router.
# It will now only be available at `/other/route/mcp`
mcp.mount_http(other_router)


if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/07_configure_http_timeout_example.py
================================================
"""
This example shows how to configure the HTTP client timeout for the MCP server.
In case you have API endpoints that take longer than 5 seconds to respond, you can increase the timeout.
"""

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

import httpx

from fastapi_mcp import FastApiMCP

setup_logging()


mcp = FastApiMCP(app, http_client=httpx.AsyncClient(timeout=20))
mcp.mount_http()


if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/08_auth_example_token_passthrough.py
================================================
"""
This example shows how to reject any request without a valid token passed in the Authorization header.

In order to configure the auth header, the config file for the MCP server should looks like this:
```json
{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}
```
"""

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

from fastapi import Depends
from fastapi.security import HTTPBearer

from fastapi_mcp import FastApiMCP, AuthConfig

setup_logging()

# Scheme for the Authorization header
token_auth_scheme = HTTPBearer()


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


# Create the MCP server with the token auth scheme
mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

# Mount the MCP server
mcp.mount_http()


if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/09_auth_example_auth0.py
================================================
from fastapi import FastAPI, Depends, HTTPException, Request, status
from pydantic_settings import BaseSettings
from typing import Any
import logging

from fastapi_mcp import FastApiMCP, AuthConfig

from examples.shared.auth import fetch_jwks_public_key
from examples.shared.setup import setup_logging


setup_logging()
logger = logging.getLogger(__name__)


class Settings(BaseSettings):
    """
    For this to work, you need an .env file in the root of the project with the following variables:
    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
    """

    auth0_domain: str  # Auth0 domain, e.g. "your-tenant.auth0.com"
    auth0_audience: str  # Audience, e.g. "https://your-tenant.auth0.com/api/v2/"
    auth0_client_id: str
    auth0_client_secret: str

    @property
    def auth0_jwks_url(self):
        return f"https://{self.auth0_domain}/.well-known/jwks.json"

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

    class Config:
        env_file = ".env"


settings = Settings()  # type: ignore


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 in settings: {settings.auth0_client_id}")
    logger.info(f"Auth0 domain in settings: {settings.auth0_domain}")
    logger.info(f"Auth0 audience in settings: {settings.auth0_audience}")
    yield


async def verify_auth(request: Request) -> dict[str, Any]:
    try:
        import jwt

        auth_header = request.headers.get("authorization", "")
        if not auth_header.startswith("Bearer "):
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authorization header")

        token = auth_header.split(" ")[1]

        header = jwt.get_unverified_header(token)

        # Check if this is a JWE token (encrypted token)
        if header.get("alg") == "dir" and header.get("enc") == "A256GCM":
            raise ValueError(
                "Token is encrypted, offline validation not possible. "
                "This is usually due to not specifying the audience when requesting the token."
            )

        # Otherwise, it's a JWT, we can validate it offline
        if header.get("alg") in ["RS256", "HS256"]:
            claims = jwt.decode(
                token,
                app.state.jwks_public_key,
                algorithms=["RS256", "HS256"],
                audience=settings.auth0_audience,
                issuer=f"https://{settings.auth0_domain}/",
                options={"verify_signature": True},
            )
            return claims

    except Exception as e:
        logger.error(f"Auth error: {str(e)}")

    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")


async def get_current_user_id(claims: dict = Depends(verify_auth)) -> str:
    user_id = claims.get("sub")

    if not user_id:
        logger.error("No user ID found in token")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")

    return user_id


app = FastAPI(lifespan=lifespan)


@app.get("/api/public", operation_id="public")
async def public():
    return {"message": "This is a public route"}


@app.get("/api/protected", operation_id="protected")
async def protected(user_id: str = Depends(get_current_user_id)):
    return {"message": f"Hello, {user_id}!", "user_id": user_id}


# Set up FastAPI-MCP with Auth0 auth
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,
    ),
)

# Mount the MCP server
mcp.mount_http()


if __name__ == "__main__":
    import uvicorn

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


================================================
FILE: examples/README.md
================================================
# FastAPI-MCP Examples

The following examples demonstrate various features and usage patterns of FastAPI-MCP:

1. [Basic Usage Example](01_basic_usage_example.py) - Basic FastAPI-MCP integration
2. [Full Schema Description](02_full_schema_description_example.py) - Customizing schema descriptions
3. [Custom Exposed Endpoints](03_custom_exposed_endpoints_example.py) - Controlling which endpoints are exposed
4. [Separate Server](04_separate_server_example.py) - Deploying MCP server separately
5. [Reregister Tools](05_reregister_tools_example.py) - Adding endpoints after MCP server creation
6. [Custom MCP Router](06_custom_mcp_router_example.py) - Advanced routing configuration
7. [Configure HTTP Timeout](07_configure_http_timeout_example.py) - Customizing timeout settings


================================================
FILE: examples/__init__.py
================================================


================================================
FILE: examples/shared/__init__.py
================================================


================================================
FILE: examples/shared/apps/__init__.py
================================================


================================================
FILE: examples/shared/apps/items.py
================================================
"""
Simple example of using FastAPI-MCP to add an MCP server to a FastAPI app.
"""

from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from typing import List, Optional


app = FastAPI()


class Item(BaseModel):
    id: int
    name: str
    description: Optional[str] = None
    price: float
    tags: List[str] = []


items_db: dict[int, Item] = {}


@app.get("/items/", response_model=List[Item], tags=["items"], operation_id="list_items")
async def list_items(skip: int = 0, limit: int = 10):
    """
    List all items in the database.

    Returns a list of items, with pagination support.
    """
    return list(items_db.values())[skip : skip + limit]


@app.get("/items/{item_id}", response_model=Item, tags=["items"], operation_id="get_item")
async def read_item(item_id: int):
    """
    Get a specific item by its ID.

    Raises a 404 error if the item does not exist.
    """
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return items_db[item_id]


@app.post("/items/", response_model=Item, tags=["items"], operation_id="create_item")
async def create_item(item: Item):
    """
    Create a new item in the database.

    Returns the created item with its assigned ID.
    """
    items_db[item.id] = item
    return item


@app.put("/items/{item_id}", response_model=Item, tags=["items"], operation_id="update_item")
async def update_item(item_id: int, item: Item):
    """
    Update an existing item.

    Raises a 404 error if the item does not exist.
    """
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")

    item.id = item_id
    items_db[item_id] = item
    return item


@app.delete("/items/{item_id}", tags=["items"], operation_id="delete_item")
async def delete_item(item_id: int):
    """
    Delete an item from the database.

    Raises a 404 error if the item does not exist.
    """
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")

    del items_db[item_id]
    return {"message": "Item deleted successfully"}


@app.get("/items/search/", response_model=List[Item], tags=["search"], operation_id="search_items")
async def search_items(
    q: Optional[str] = Query(None, description="Search query string"),
    min_price: Optional[float] = Query(None, description="Minimum price"),
    max_price: Optional[float] = Query(None, description="Maximum price"),
    tags: List[str] = Query([], description="Filter by tags"),
):
    """
    Search for items with various filters.

    Returns a list of items that match the search criteria.
    """
    results = list(items_db.values())

    if q:
        q = q.lower()
        results = [
            item for item in results if q in item.name.lower() or (item.description and q in item.description.lower())
        ]

    if min_price is not None:
        results = [item for item in results if item.price >= min_price]
    if max_price is not None:
        results = [item for item in results if item.price <= max_price]

    if tags:
        results = [item for item in results if all(tag in item.tags for tag in tags)]

    return results


sample_items = [
    Item(id=1, name="Hammer", description="A tool for hammering nails", price=9.99, tags=["tool", "hardware"]),
    Item(id=2, name="Screwdriver", description="A tool for driving screws", price=7.99, tags=["tool", "hardware"]),
    Item(id=3, name="Wrench", description="A tool for tightening bolts", price=12.99, tags=["tool", "hardware"]),
    Item(id=4, name="Saw", description="A tool for cutting wood", price=19.99, tags=["tool", "hardware", "cutting"]),
    Item(id=5, name="Drill", description="A tool for drilling holes", price=49.99, tags=["tool", "hardware", "power"]),
]
for item in sample_items:
    items_db[item.id] = item


================================================
FILE: examples/shared/auth.py
================================================
from jwt.algorithms import RSAAlgorithm
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey

import logging
import httpx

from examples.shared.setup import setup_logging

setup_logging()

logger = logging.getLogger(__name__)


async def fetch_jwks_public_key(url: str) -> str:
    """
    Fetch JWKS from a given URL and extract the primary public key in PEM format.

    Args:
        url: The JWKS URL to fetch from

    Returns:
        PEM-formatted public key as a string
    """
    logger.info(f"Fetching JWKS from: {url}")
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        response.raise_for_status()
        jwks_data = response.json()

        if not jwks_data or "keys" not in jwks_data or not jwks_data["keys"]:
            logger.error("Invalid JWKS data format: missing or empty 'keys' array")
            raise ValueError("Invalid JWKS data format: missing or empty 'keys' array")

        # Just use the first key in the set
        jwk = jwks_data["keys"][0]

        # Convert JWK to PEM format
        public_key = RSAAlgorithm.from_jwk(jwk)
        if isinstance(public_key, RSAPublicKey):
            pem = public_key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo,
            )
            pem_str = pem.decode("utf-8")
            logger.info("Successfully extracted public key from JWKS")
            return pem_str
        else:
            logger.error("Invalid JWKS data format: expected RSA public key")
            raise ValueError("Invalid JWKS data format: expected RSA public key")


================================================
FILE: examples/shared/setup.py
================================================
import logging

from pydantic import BaseModel


class LoggingConfig(BaseModel):
    LOGGER_NAME: str = "fastapi_mcp"
    LOG_FORMAT: str = "%(levelprefix)s %(asctime)s\t[%(name)s] %(message)s"
    LOG_LEVEL: str = logging.getLevelName(logging.DEBUG)

    version: int = 1
    disable_existing_loggers: bool = False
    formatters: dict = {
        "default": {
            "()": "uvicorn.logging.DefaultFormatter",
            "fmt": LOG_FORMAT,
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    }
    handlers: dict = {
        "default": {
            "formatter": "default",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stdout",
        },
    }
    loggers: dict = {
        "": {"handlers": ["default"], "level": LOG_LEVEL},  # Root logger
        "uvicorn": {"handlers": ["default"], "level": LOG_LEVEL},
        LOGGER_NAME: {"handlers": ["default"], "level": LOG_LEVEL},
    }


def setup_logging():
    from logging.config import dictConfig

    logging_config = LoggingConfig()
    dictConfig(logging_config.model_dump())


================================================
FILE: fastapi_mcp/__init__.py
================================================
"""
FastAPI-MCP: Automatic MCP server generator for FastAPI applications.

Created by Tadata Inc. (https://github.com/tadata-org)
"""

try:
    from importlib.metadata import version

    __version__ = version("fastapi-mcp")
except Exception:  # pragma: no cover
    # Fallback for local development
    __version__ = "0.0.0.dev0"  # pragma: no cover

from .server import FastApiMCP
from .types import AuthConfig, OAuthMetadata


__all__ = [
    "FastApiMCP",
    "AuthConfig",
    "OAuthMetadata",
]


================================================
FILE: fastapi_mcp/auth/__init__.py
================================================


================================================
FILE: fastapi_mcp/auth/proxy.py
================================================
from typing_extensions import Annotated, Doc
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.responses import RedirectResponse
import httpx
from typing import Optional
import logging
from urllib.parse import urlencode

from fastapi_mcp.types import (
    ClientRegistrationRequest,
    ClientRegistrationResponse,
    AuthConfig,
    OAuthMetadata,
    OAuthMetadataDict,
    StrHttpUrl,
)


logger = logging.getLogger(__name__)


def setup_oauth_custom_metadata(
    app: Annotated[FastAPI, Doc("The FastAPI app instance")],
    auth_config: Annotated[AuthConfig, Doc("The AuthConfig used")],
    metadata: Annotated[OAuthMetadataDict, Doc("The custom metadata specified in AuthConfig")],
    include_in_schema: Annotated[bool, Doc("Whether to include the metadata endpoint in your OpenAPI docs")] = False,
):
    """
    Just serve the custom metadata provided to AuthConfig under the path specified in `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


def setup_oauth_metadata_proxy(
    app: Annotated[FastAPI, Doc("The FastAPI app instance")],
    metadata_url: Annotated[
        str,
        Doc(
            """
            The URL of the OAuth provider's metadata endpoint that you want to proxy.
            """
        ),
    ],
    path: Annotated[
        str,
        Doc(
            """
            The path to mount the OAuth metadata endpoint at.

            Clients will usually expect this to be /.well-known/oauth-authorization-server
            """
        ),
    ] = "/.well-known/oauth-authorization-server",
    authorize_path: Annotated[
        str,
        Doc(
            """
            The path to mount the authorize endpoint at.

            Clients will usually expect this to be /oauth/authorize
            """
        ),
    ] = "/oauth/authorize",
    register_path: Annotated[
        Optional[str],
        Doc(
            """
            The path to mount the register endpoint at.

            Clients will usually expect this to be /oauth/register
            """
        ),
    ] = None,
    include_in_schema: Annotated[bool, Doc("Whether to include the metadata endpoint in your OpenAPI docs")] = False,
):
    """
    Proxy for your OAuth provider's Metadata endpoint, just adding our (fake) registration endpoint.
    """

    @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("/")

        # Fetch your OAuth provider's OpenID Connect metadata
        async with httpx.AsyncClient() as client:
            response = await client.get(metadata_url)
            if response.status_code != 200:
                logger.error(
                    f"Failed to fetch OAuth metadata from {metadata_url}: {response.status_code}. Response: {response.text}"
                )
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail="Failed to fetch OAuth metadata",
                )

            oauth_metadata = response.json()

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

        # Replace your OAuth provider's authorize endpoint with our proxy
        oauth_metadata["authorization_endpoint"] = f"{base_url}{authorize_path}"

        return OAuthMetadata.model_validate(oauth_metadata)


def setup_oauth_authorize_proxy(
    app: Annotated[FastAPI, Doc("The FastAPI app instance")],
    client_id: Annotated[
        str,
        Doc(
            """
            In case the client doesn't specify a client ID, this will be used as the default client ID on the
            request to your OAuth provider.
            """
        ),
    ],
    authorize_url: Annotated[
        Optional[StrHttpUrl],
        Doc(
            """
            The URL of your OAuth provider's authorization endpoint.

            Usually this is something like `https://app.example.com/oauth/authorize`.
            """
        ),
    ],
    audience: Annotated[
        Optional[str],
        Doc(
            """
            Currently (2025-04-21), some Auth-supporting MCP clients (like `npx mcp-remote`) might not specify the
            audience when sending a request to your server.

            This may cause unexpected behavior from your OAuth provider, so this is a workaround.

            In case the client doesn't specify an audience, this will be used as the default audience on the
            request to your OAuth provider.
            """
        ),
    ] = None,
    default_scope: Annotated[
        str,
        Doc(
            """
            Currently (2025-04-21), some Auth-supporting MCP clients (like `npx mcp-remote`) might not specify the
            scope when sending a request to your server.

            This may cause unexpected behavior from your OAuth provider, so this is a workaround.

            Here is where you can optionally specify a default scope that will be sent to your OAuth provider in case
            the client doesn't specify it.
            """
        ),
    ] = "openid profile email",
    path: Annotated[str, Doc("The path to mount the authorize endpoint at")] = "/oauth/authorize",
    include_in_schema: Annotated[bool, Doc("Whether to include the authorize endpoint in your OpenAPI docs")] = False,
):
    """
    Proxy for your OAuth provider's authorize endpoint that logs the requested scopes and adds
    default scopes and the audience parameter if not provided.
    """

    @app.get(
        path,
        include_in_schema=include_in_schema,
    )
    async def oauth_authorize_proxy(
        response_type: str = "code",
        client_id: Optional[str] = client_id,
        redirect_uri: Optional[str] = None,
        scope: str = "",
        state: Optional[str] = None,
        code_challenge: Optional[str] = None,
        code_challenge_method: Optional[str] = None,
        audience: Optional[str] = audience,
    ):
        if not scope:
            logger.warning("Client didn't provide any scopes! Using default scopes.")
            scope = default_scope
            logger.debug(f"Default scope: {scope}")

        scopes = scope.split()
        logger.debug(f"Scopes passed: {scopes}")
        for required_scope in default_scope.split():
            if required_scope not in scopes:
                scopes.append(required_scope)

        params = {
            "response_type": response_type,
            "client_id": client_id,
            "redirect_uri": redirect_uri,
            "scope": " ".join(scopes),
            "audience": audience,
        }

        if state:
            params["state"] = state
        if code_challenge:
            params["code_challenge"] = code_challenge
        if code_challenge_method:
            params["code_challenge_method"] = code_challenge_method

        auth_url = f"{authorize_url}?{urlencode(params)}"

        return RedirectResponse(url=auth_url)


def setup_oauth_fake_dynamic_register_endpoint(
    app: Annotated[FastAPI, Doc("The FastAPI app instance")],
    client_id: Annotated[str, Doc("The client ID of the pre-registered client")],
    client_secret: Annotated[str, Doc("The client secret of the pre-registered client")],
    path: Annotated[str, Doc("The path to mount the register endpoint at")] = "/oauth/register",
    include_in_schema: Annotated[bool, Doc("Whether to include the register endpoint in your OpenAPI docs")] = False,
):
    """
    A proxy for dynamic client registration endpoint.

    In MCP 2025-03-26 Spec, it is recommended to support OAuth Dynamic Client Registration (RFC 7591).
    Furthermore, `npx mcp-remote` which is the current de-facto client that supports MCP's up-to-date spec,
    requires this endpoint to be present.

    But, this is an overcomplication for most use cases.

    So instead of actually implementing dynamic client registration, we just echo back the pre-registered
    client ID and secret.

    Use this if you don't need dynamic client registration, or if your OAuth provider doesn't support it.
    """

    @app.post(
        path,
        response_model=ClientRegistrationResponse,
        include_in_schema=include_in_schema,
    )
    async def oauth_register_proxy(request: ClientRegistrationRequest) -> ClientRegistrationResponse:
        client_response = ClientRegistrationResponse(
            client_name=request.client_name or "MCP Server",  # Name doesn't really affect functionality
            client_id=client_id,
            client_secret=client_secret,
            redirect_uris=request.redirect_uris,  # Just echo back their requested URIs
            grant_types=request.grant_types or ["authorization_code"],
            token_endpoint_auth_method=request.token_endpoint_auth_method or "none",
        )
        return client_response


================================================
FILE: fastapi_mcp/openapi/__init__.py
================================================


================================================
FILE: fastapi_mcp/openapi/convert.py
================================================
import json
import logging
from typing import Any, Dict, List, Tuple

import mcp.types as types

from .utils import (
    clean_schema_for_display,
    generate_example_from_schema,
    resolve_schema_references,
    get_single_param_type_from_schema,
)

logger = logging.getLogger(__name__)


def convert_openapi_to_mcp_tools(
    openapi_schema: Dict[str, Any],
    describe_all_responses: bool = False,
    describe_full_response_schema: bool = False,
) -> Tuple[List[types.Tool], Dict[str, Dict[str, Any]]]:
    """
    Convert OpenAPI operations to MCP tools.

    Args:
        openapi_schema: The OpenAPI schema
        describe_all_responses: Whether to include all possible response schemas in tool descriptions
        describe_full_response_schema: Whether to include full response schema in tool descriptions

    Returns:
        A tuple containing:
        - A list of MCP tools
        - A mapping of operation IDs to operation details for HTTP execution
    """
    # Resolve all references in the schema at once
    resolved_openapi_schema = resolve_schema_references(openapi_schema, openapi_schema)

    tools = []
    operation_map = {}

    # Process each path in the OpenAPI schema
    for path, path_item in resolved_openapi_schema.get("paths", {}).items():
        for method, operation in path_item.items():
            # Skip non-HTTP methods
            if method not in ["get", "post", "put", "delete", "patch"]:
                logger.warning(f"Skipping non-HTTP method: {method}")
                continue

            # Get operation metadata
            operation_id = operation.get("operationId")
            if not operation_id:
                logger.warning(f"Skipping operation with no operationId: {operation}")
                continue

            # Save operation details for later HTTP calls
            operation_map[operation_id] = {
                "path": path,
                "method": method,
                "parameters": operation.get("parameters", []),
                "request_body": operation.get("requestBody", {}),
            }

            summary = operation.get("summary", "")
            description = operation.get("description", "")

            # Build tool description
            tool_description = f"{summary}" if summary else f"{method.upper()} {path}"
            if description:
                tool_description += f"\n\n{description}"

            # Add response information to the description
            responses = operation.get("responses", {})
            if responses:
                response_info = "\n\n### Responses:\n"

                # Find the success response
                success_codes = range(200, 300)
                success_response = None
                for status_code in success_codes:
                    if str(status_code) in responses:
                        success_response = responses[str(status_code)]
                        break

                # Get the list of responses to include
                responses_to_include = responses
                if not describe_all_responses and success_response:
                    # If we're not describing all responses, only include the success response
                    success_code = next((code for code in success_codes if str(code) in responses), None)
                    if success_code:
                        responses_to_include = {str(success_code): success_response}

                # Process all selected responses
                for status_code, response_data in responses_to_include.items():
                    response_desc = response_data.get("description", "")
                    response_info += f"\n**{status_code}**: {response_desc}"

                    # Highlight if this is the main success response
                    if response_data == success_response:
                        response_info += " (Success Response)"

                    # Add schema information if available
                    if "content" in response_data:
                        for content_type, content_data in response_data["content"].items():
                            if "schema" in content_data:
                                schema = content_data["schema"]
                                response_info += f"\nContent-Type: {content_type}"

                                # Clean the schema for display
                                display_schema = clean_schema_for_display(schema)

                                # Try to get example response
                                example_response = None

                                # Check if content has examples
                                if "examples" in content_data:
                                    for example_key, example_data in content_data["examples"].items():
                                        if "value" in example_data:
                                            example_response = example_data["value"]
                                            break
                                # If content has example
                                elif "example" in content_data:
                                    example_response = content_data["example"]

                                # If we have an example response, add it to the docs
                                if example_response:
                                    response_info += "\n\n**Example Response:**\n```json\n"
                                    response_info += json.dumps(example_response, indent=2)
                                    response_info += "\n```"
                                # Otherwise generate an example from the schema
                                else:
                                    generated_example = generate_example_from_schema(display_schema)
                                    if generated_example:
                                        response_info += "\n\n**Example Response:**\n```json\n"
                                        response_info += json.dumps(generated_example, indent=2)
                                        response_info += "\n```"

                                # Only include full schema information if requested
                                if describe_full_response_schema:
                                    # Format schema information based on its type
                                    if display_schema.get("type") == "array" and "items" in display_schema:
                                        items_schema = display_schema["items"]

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

                tool_description += response_info

            # Organize parameters by type
            path_params = []
            query_params = []
            header_params = []
            body_params = []

            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))

            # Process request body if present
            request_body = operation.get("requestBody", {})
            if request_body and "content" in request_body:
                content_type = next(iter(request_body["content"]), None)
                if content_type and "schema" in request_body["content"][content_type]:
                    schema = request_body["content"][content_type]["schema"]
                    if "properties" in schema:
                        for prop_name, prop_schema in schema["properties"].items():
                            required = prop_name in schema.get("required", [])
                            body_params.append(
                                (
                                    prop_name,
                                    {
                                        "name": prop_name,
                                        "schema": prop_schema,
                                        "required": required,
                                    },
                                )
                            )

            # Create input schema properties for all parameters
            properties = {}
            required_props = []

            # Add path parameters to properties
            for param_name, param in path_params:
                param_schema = param.get("schema", {})
                param_desc = param.get("description", "")
                param_required = param.get("required", True)  # Path params are usually required

                properties[param_name] = param_schema.copy()
                properties[param_name]["title"] = param_name
                if param_desc:
                    properties[param_name]["description"] = param_desc

                if "type" not in properties[param_name]:
                    properties[param_name]["type"] = param_schema.get("type", "string")

                if param_required:
                    required_props.append(param_name)

            # Add query parameters to properties
            for param_name, param in query_params:
                param_schema = param.get("schema", {})
                param_desc = param.get("description", "")
                param_required = param.get("required", False)

                properties[param_name] = param_schema.copy()
                properties[param_name]["title"] = param_name
                if param_desc:
                    properties[param_name]["description"] = param_desc

                if "type" not in properties[param_name]:
                    properties[param_name]["type"] = get_single_param_type_from_schema(param_schema)

                if "default" in param_schema:
                    properties[param_name]["default"] = param_schema["default"]

                if param_required:
                    required_props.append(param_name)

            # Add body parameters to properties
            for param_name, param in body_params:
                param_schema = param.get("schema", {})
                param_desc = param.get("description", "")
                param_required = param.get("required", False)

                properties[param_name] = param_schema.copy()
                properties[param_name]["title"] = param_name
                if param_desc:
                    properties[param_name]["description"] = param_desc

                if "type" not in properties[param_name]:
                    properties[param_name]["type"] = get_single_param_type_from_schema(param_schema)

                if "default" in param_schema:
                    properties[param_name]["default"] = param_schema["default"]

                if param_required:
                    required_props.append(param_name)

            # Create a proper input schema for the tool
            input_schema = {"type": "object", "properties": properties, "title": f"{operation_id}Arguments"}

            if required_props:
                input_schema["required"] = required_props

            # Create the MCP tool definition
            tool = types.Tool(name=operation_id, description=tool_description, inputSchema=input_schema)

            tools.append(tool)

    return tools, operation_map


================================================
FILE: fastapi_mcp/openapi/utils.py
================================================
from typing import Any, Dict


def get_single_param_type_from_schema(param_schema: Dict[str, Any]) -> str:
    """
    Get the type of a parameter from the schema.
    If the schema is a union type, return the first type.
    """
    if "anyOf" in param_schema:
        types = {schema.get("type") for schema in param_schema["anyOf"] if schema.get("type")}
        if "null" in types:
            types.remove("null")
        if types:
            return next(iter(types))
        return "string"
    return param_schema.get("type", "string")


def resolve_schema_references(schema_part: Dict[str, Any], reference_schema: Dict[str, Any]) -> Dict[str, Any]:
    """
    Resolve schema references in OpenAPI schemas.

    Args:
        schema_part: The part of the schema being processed that may contain references
        reference_schema: The complete schema used to resolve references from

    Returns:
        The schema with references resolved
    """
    # Make a copy to avoid modifying the input schema
    schema_part = schema_part.copy()

    # Handle $ref directly in the schema
    if "$ref" in schema_part:
        ref_path = schema_part["$ref"]
        # Standard OpenAPI references are in the format "#/components/schemas/ModelName"
        if ref_path.startswith("#/components/schemas/"):
            model_name = ref_path.split("/")[-1]
            if "components" in reference_schema and "schemas" in reference_schema["components"]:
                if model_name in reference_schema["components"]["schemas"]:
                    # Replace with the resolved schema
                    ref_schema = reference_schema["components"]["schemas"][model_name].copy()
                    # Remove the $ref key and merge with the original schema
                    schema_part.pop("$ref")
                    schema_part.update(ref_schema)

    # Recursively resolve references in all dictionary values
    for key, value in schema_part.items():
        if isinstance(value, dict):
            schema_part[key] = resolve_schema_references(value, reference_schema)
        elif isinstance(value, list):
            # Only process list items that are dictionaries since only they can contain refs
            schema_part[key] = [
                resolve_schema_references(item, reference_schema) if isinstance(item, dict) else item for item in value
            ]

    return schema_part


def clean_schema_for_display(schema: Dict[str, Any]) -> Dict[str, Any]:
    """
    Clean up a schema for display by removing internal fields.

    Args:
        schema: The schema to clean

    Returns:
        The cleaned schema
    """
    # Make a copy to avoid modifying the input schema
    schema = schema.copy()

    # Remove common internal fields that are not helpful for LLMs
    fields_to_remove = [
        "allOf",
        "anyOf",
        "oneOf",
        "nullable",
        "discriminator",
        "readOnly",
        "writeOnly",
        "xml",
        "externalDocs",
    ]
    for field in fields_to_remove:
        if field in schema:
            schema.pop(field)

    # Process nested properties
    if "properties" in schema:
        for prop_name, prop_schema in schema["properties"].items():
            if isinstance(prop_schema, dict):
                schema["properties"][prop_name] = clean_schema_for_display(prop_schema)

    # Process array items
    if "type" in schema and schema["type"] == "array" and "items" in schema:
        if isinstance(schema["items"], dict):
            schema["items"] = clean_schema_for_display(schema["items"])

    return schema


def generate_example_from_schema(schema: Dict[str, Any]) -> Any:
    """
    Generate a simple example response from a JSON schema.

    Args:
        schema: The JSON schema to generate an example from

    Returns:
        An example object based on the schema
    """
    if not schema or not isinstance(schema, dict):
        return None

    # Handle different types
    schema_type = schema.get("type")

    if schema_type == "object":
        result = {}
        if "properties" in schema:
            for prop_name, prop_schema in schema["properties"].items():
                # Generate an example for each property
                prop_example = generate_example_from_schema(prop_schema)
                if prop_example is not None:
                    result[prop_name] = prop_example
        return result

    elif schema_type == "array":
        if "items" in schema:
            # Generate a single example item
            item_example = generate_example_from_schema(schema["items"])
            if item_example is not None:
                return [item_example]
        return []

    elif schema_type == "string":
        # Check if there's a format
        format_type = schema.get("format")
        if format_type == "date-time":
            return "2023-01-01T00:00:00Z"
        elif format_type == "date":
            return "2023-01-01"
        elif format_type == "email":
            return "user@example.com"
        elif format_type == "uri":
            return "https://example.com"
        # Use title or property name if available
        return schema.get("title", "string")

    elif schema_type == "integer":
        return 1

    elif schema_type == "number":
        return 1.0

    elif schema_type == "boolean":
        return True

    elif schema_type == "null":
        return None

    # Default case
    return None


================================================
FILE: fastapi_mcp/server.py
================================================
import json
import httpx
from typing import Dict, Optional, Any, List, Union, Literal, Sequence
from typing_extensions import Annotated, Doc

from fastapi import FastAPI, Request, APIRouter, params
from fastapi.openapi.utils import get_openapi
from mcp.server.lowlevel.server import Server
import mcp.types as types

from fastapi_mcp.openapi.convert import convert_openapi_to_mcp_tools
from fastapi_mcp.transport.sse import FastApiSseTransport
from fastapi_mcp.transport.http import FastApiHttpSessionManager
from fastapi_mcp.types import HTTPRequestInfo, AuthConfig

import logging


logger = logging.getLogger(__name__)


class FastApiMCP:
    """
    Create an MCP server from a FastAPI app.
    """

    def __init__(
        self,
        fastapi: Annotated[
            FastAPI,
            Doc("The FastAPI application to create an MCP server from"),
        ],
        name: Annotated[
            Optional[str],
            Doc("Name for the MCP server (defaults to app.title)"),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc("Description for the MCP server (defaults to app.description)"),
        ] = None,
        describe_all_responses: Annotated[
            bool,
            Doc("Whether to include all possible response schemas in tool descriptions"),
        ] = False,
        describe_full_response_schema: Annotated[
            bool,
            Doc("Whether to include full json schema for responses in tool descriptions"),
        ] = False,
        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,
        include_operations: Annotated[
            Optional[List[str]],
            Doc("List of operation IDs to include as MCP tools. Cannot be used with exclude_operations."),
        ] = None,
        exclude_operations: Annotated[
            Optional[List[str]],
            Doc("List of operation IDs to exclude from MCP tools. Cannot be used with include_operations."),
        ] = None,
        include_tags: Annotated[
            Optional[List[str]],
            Doc("List of tags to include as MCP tools. Cannot be used with exclude_tags."),
        ] = None,
        exclude_tags: Annotated[
            Optional[List[str]],
            Doc("List of tags to exclude from MCP tools. Cannot be used with include_tags."),
        ] = None,
        auth_config: Annotated[
            Optional[AuthConfig],
            Doc("Configuration for MCP authentication"),
        ] = None,
        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"],
    ):
        # Validate operation and tag filtering options
        if include_operations is not None and exclude_operations is not None:
            raise ValueError("Cannot specify both include_operations and exclude_operations")

        if include_tags is not None and exclude_tags is not None:
            raise ValueError("Cannot specify both include_tags and exclude_tags")

        self.operation_map: Dict[str, Dict[str, Any]]
        self.tools: List[types.Tool]
        self.server: Server

        self.fastapi = fastapi
        self.name = name or self.fastapi.title or "FastAPI MCP"
        self.description = description or self.fastapi.description

        self._base_url = "http://apiserver"
        self._describe_all_responses = describe_all_responses
        self._describe_full_response_schema = describe_full_response_schema
        self._include_operations = include_operations
        self._exclude_operations = exclude_operations
        self._include_tags = include_tags
        self._exclude_tags = exclude_tags
        self._auth_config = auth_config

        if self._auth_config:
            self._auth_config = self._auth_config.model_validate(self._auth_config)

        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,
        )

        self._forward_headers = {h.lower() for h in headers}
        self._http_transport: FastApiHttpSessionManager | None = None  # Store reference to HTTP transport for cleanup

        self.setup_server()

    def setup_server(self) -> None:
        openapi_schema = get_openapi(
            title=self.fastapi.title,
            version=self.fastapi.version,
            openapi_version=self.fastapi.openapi_version,
            description=self.fastapi.description,
            routes=self.fastapi.routes,
        )

        all_tools, self.operation_map = convert_openapi_to_mcp_tools(
            openapi_schema,
            describe_all_responses=self._describe_all_responses,
            describe_full_response_schema=self._describe_full_response_schema,
        )

        # Filter tools based on operation IDs and tags
        self.tools = self._filter_tools(all_tools, openapi_schema)

        mcp_server: Server = Server(self.name, self.description)

        @mcp_server.list_tools()
        async def handle_list_tools() -> List[types.Tool]:
            return self.tools

        @mcp_server.call_tool()
        async def handle_call_tool(
            name: str, arguments: Dict[str, Any]
        ) -> List[Union[types.TextContent, types.ImageContent, types.EmbeddedResource]]:
            # Extract HTTP request info from MCP context
            http_request_info = None
            try:
                # Access the MCP server's request context to get the original HTTP Request
                request_context = mcp_server.request_context

                if request_context and hasattr(request_context, "request"):
                    http_request = request_context.request

                    if http_request and hasattr(http_request, "method"):
                        http_request_info = HTTPRequestInfo(
                            method=http_request.method,
                            path=http_request.url.path,
                            headers=dict(http_request.headers),
                            cookies=http_request.cookies,
                            query_params=dict(http_request.query_params),
                            body=None,
                        )
                        logger.debug(
                            f"Extracted HTTP request info from context: {http_request_info.method} {http_request_info.path}"
                        )
            except (LookupError, AttributeError) as e:
                logger.error(f"Could not extract HTTP request info from context: {e}")

            return await self._execute_api_tool(
                client=self._http_client,
                tool_name=name,
                arguments=arguments,
                operation_map=self.operation_map,
                http_request_info=http_request_info,
            )

        self.server = mcp_server

    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,
                )

    def _register_mcp_messages_endpoint_sse(
        self,
        router: FastAPI | APIRouter,
        transport: FastApiSseTransport,
        mount_path: str,
        dependencies: Optional[Sequence[params.Depends]],
    ):
        @router.post(
            f"{mount_path}/messages/",
            include_in_schema=False,
            operation_id="mcp_messages",
            dependencies=dependencies,
        )
        async def handle_post_message(request: Request):
            return await transport.handle_fastapi_post_message(request)

    def _register_mcp_endpoints_sse(
        self,
        router: FastAPI | APIRouter,
        transport: FastApiSseTransport,
        mount_path: str,
        dependencies: Optional[Sequence[params.Depends]],
    ):
        self._register_mcp_connection_endpoint_sse(router, transport, mount_path, dependencies)
        self._register_mcp_messages_endpoint_sse(router, transport, mount_path, dependencies)

    def _register_mcp_http_endpoint(
        self,
        router: FastAPI | APIRouter,
        transport: FastApiHttpSessionManager,
        mount_path: str,
        dependencies: Optional[Sequence[params.Depends]],
    ):
        @router.api_route(
            mount_path,
            methods=["GET", "POST", "DELETE"],
            include_in_schema=False,
            operation_id="mcp_http",
            dependencies=dependencies,
        )
        async def handle_mcp_streamable_http(request: Request):
            return await transport.handle_fastapi_request(request)

    def _register_mcp_endpoints_http(
        self,
        router: FastAPI | APIRouter,
        transport: FastApiHttpSessionManager,
        mount_path: str,
        dependencies: Optional[Sequence[params.Depends]],
    ):
        self._register_mcp_http_endpoint(router, transport, mount_path, dependencies)

    def _setup_auth_2025_03_26(self):
        from fastapi_mcp.auth.proxy import (
            setup_oauth_custom_metadata,
            setup_oauth_metadata_proxy,
            setup_oauth_authorize_proxy,
            setup_oauth_fake_dynamic_register_endpoint,
        )

        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:
                assert self._auth_config.client_id is not None

                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:
                    assert self._auth_config.client_secret is not None
                    setup_oauth_fake_dynamic_register_endpoint(
                        app=self.fastapi,
                        client_id=self._auth_config.client_id,
                        client_secret=self._auth_config.client_secret,
                    )

    def _setup_auth(self):
        if self._auth_config:
            if self._auth_config.version == "2025-03-26":
                self._setup_auth_2025_03_26()
            else:
                raise ValueError(
                    f"Unsupported MCP spec version: {self._auth_config.version}. Please check your AuthConfig."
                )
        else:
            logger.info("No auth config provided, skipping auth setup")

    def mount_http(
        self,
        router: Annotated[
            Optional[FastAPI | APIRouter],
            Doc(
                """
                The FastAPI app or APIRouter to mount the MCP server to. If not provided, the MCP
                server will be mounted to the FastAPI app.
                """
            ),
        ] = None,
        mount_path: Annotated[
            str,
            Doc(
                """
                Path where the MCP server will be mounted.
                Mount path is appended to the root path of FastAPI router, or to the prefix of APIRouter.
                Defaults to '/mcp'.
                """
            ),
        ] = "/mcp",
    ) -> None:
        """
        Mount the MCP server with HTTP transport to **any** FastAPI app or APIRouter.

        There is no requirement that the FastAPI app or APIRouter is the same as the one that the MCP
        server was created from.
        """
        # Normalize mount path
        if not mount_path.startswith("/"):
            mount_path = f"/{mount_path}"
        if mount_path.endswith("/"):
            mount_path = mount_path[:-1]

        if not router:
            router = self.fastapi

        assert isinstance(router, (FastAPI, APIRouter)), f"Invalid router type: {type(router)}"

        http_transport = FastApiHttpSessionManager(mcp_server=self.server)
        dependencies = self._auth_config.dependencies if self._auth_config else None

        self._register_mcp_endpoints_http(router, http_transport, mount_path, dependencies)
        self._setup_auth()
        self._http_transport = http_transport  # Store reference

        # HACK: If we got a router and not a FastAPI instance, we need to re-include the router so that
        # FastAPI will pick up the new routes we added. The problem with this approach is that we assume
        # that the router is a sub-router of self.fastapi, which may not always be the case.
        #
        # TODO: Find a better way to do this.
        if isinstance(router, APIRouter):
            self.fastapi.include_router(router)

        logger.info(f"MCP HTTP server listening at {mount_path}")

    def mount_sse(
        self,
        router: Annotated[
            Optional[FastAPI | APIRouter],
            Doc(
                """
                The FastAPI app or APIRouter to mount the MCP server to. If not provided, the MCP
                server will be mounted to the FastAPI app.
                """
            ),
        ] = None,
        mount_path: Annotated[
            str,
            Doc(
                """
                Path where the MCP server will be mounted.
                Mount path is appended to the root path of FastAPI router, or to the prefix of APIRouter.
                Defaults to '/sse'.
                """
            ),
        ] = "/sse",
    ) -> None:
        """
        Mount the MCP server with SSE transport to **any** FastAPI app or APIRouter.

        There is no requirement that the FastAPI app or APIRouter is the same as the one that the MCP
        server was created from.
        """
        # Normalize mount path
        if not mount_path.startswith("/"):
            mount_path = f"/{mount_path}"
        if mount_path.endswith("/"):
            mount_path = mount_path[:-1]

        if not router:
            router = self.fastapi

        # Build the base path correctly for the SSE transport
        assert isinstance(router, (FastAPI, APIRouter)), f"Invalid router type: {type(router)}"
        base_path = mount_path if isinstance(router, FastAPI) else router.prefix + mount_path
        messages_path = f"{base_path}/messages/"

        sse_transport = FastApiSseTransport(messages_path)
        dependencies = self._auth_config.dependencies if self._auth_config else None

        self._register_mcp_endpoints_sse(router, sse_transport, mount_path, dependencies)
        self._setup_auth()

        # HACK: If we got a router and not a FastAPI instance, we need to re-include the router so that
        # FastAPI will pick up the new routes we added. The problem with this approach is that we assume
        # that the router is a sub-router of self.fastapi, which may not always be the case.
        #
        # TODO: Find a better way to do this.
        if isinstance(router, APIRouter):
            self.fastapi.include_router(router)

        logger.info(f"MCP SSE server listening at {mount_path}")

    def mount(
        self,
        router: Annotated[
            Optional[FastAPI | APIRouter],
            Doc(
                """
                The FastAPI app or APIRouter to mount the MCP server to. If not provided, the MCP
                server will be mounted to the FastAPI app.
                """
            ),
        ] = None,
        mount_path: Annotated[
            str,
            Doc(
                """
                Path where the MCP server will be mounted.
                Mount path is appended to the root path of FastAPI router, or to the prefix of APIRouter.
                Defaults to '/mcp'.
                """
            ),
        ] = "/mcp",
        transport: Annotated[
            Literal["sse"],
            Doc(
                """
                The transport type for the MCP server. Currently only 'sse' is supported.
                This parameter is deprecated.
                """
            ),
        ] = "sse",
    ) -> None:
        """
        [DEPRECATED] Mount the MCP server to **any** FastAPI app or APIRouter.

        This method is deprecated and will be removed in a future version.
        Use mount_http() for HTTP transport (recommended) or mount_sse() for SSE transport instead.

        For backwards compatibility, this method defaults to SSE transport.

        There is no requirement that the FastAPI app or APIRouter is the same as the one that the MCP
        server was created from.
        """
        import warnings

        warnings.warn(
            "mount() is deprecated and will be removed in a future version. "
            "Use mount_http() for HTTP transport (recommended) or mount_sse() for SSE transport instead.",
            DeprecationWarning,
            stacklevel=2,
        )

        if transport == "sse":
            self.mount_sse(router, mount_path)
        else:  # pragma: no cover
            raise ValueError(  # pragma: no cover
                f"Unsupported transport: {transport}. Use mount_sse() or mount_http() instead."
            )

    async def _execute_api_tool(
        self,
        client: Annotated[httpx.AsyncClient, Doc("httpx client to use in API calls")],
        tool_name: Annotated[str, Doc("The name of the tool to execute")],
        arguments: Annotated[Dict[str, Any], Doc("The arguments for the tool")],
        operation_map: Annotated[Dict[str, Dict[str, Any]], Doc("A mapping from tool names to operation details")],
        http_request_info: Annotated[
            Optional[HTTPRequestInfo],
            Doc("HTTP request info to forward to the actual API call"),
        ] = None,
    ) -> List[Union[types.TextContent, types.ImageContent, types.EmbeddedResource]]:
        """
        Execute an MCP tool by making an HTTP request to the corresponding API endpoint.

        Returns:
            The result as MCP content types
        """
        if tool_name not in operation_map:
            raise Exception(f"Unknown tool: {tool_name}")

        operation = operation_map[tool_name]
        path: str = operation["path"]
        method: str = operation["method"]
        parameters: List[Dict[str, Any]] = operation.get("parameters", [])
        arguments = arguments.copy() if arguments else {}  # Deep copy arguments to avoid mutating the original

        for param in parameters:
            if param.get("in") == "path" and param.get("name") in arguments:
                param_name = param.get("name", None)
                if param_name is None:
                    raise ValueError(f"Parameter name is None for parameter: {param}")
                path = path.replace(f"{{{param_name}}}", str(arguments.pop(param_name)))

        query = {}
        for param in parameters:
            if param.get("in") == "query" and param.get("name") in arguments:
                param_name = param.get("name", None)
                if param_name is None:
                    raise ValueError(f"Parameter name is None for parameter: {param}")
                query[param_name] = arguments.pop(param_name)

        headers = {}
        for param in parameters:
            if param.get("in") == "header" and param.get("name") in arguments:
                param_name = param.get("name", None)
                if param_name is None:
                    raise ValueError(f"Parameter name is None for parameter: {param}")
                headers[param_name] = arguments.pop(param_name)

        # Forward headers that are in the allowlist
        if http_request_info and http_request_info.headers:
            for name, value in http_request_info.headers.items():
                # case-insensitive check for allowed headers
                if name.lower() in self._forward_headers:
                    headers[name] = value

        body = arguments if arguments else None

        try:
            logger.debug(f"Making {method.upper()} request to {path}")
            response = await self._request(client, method, path, query, headers, body)

            # TODO: Better typing for the AsyncClientProtocol. It should return a ResponseProtocol that has a json() method that returns a dict/list/etc.
            try:
                result = response.json()
                result_text = json.dumps(result, indent=2, ensure_ascii=False)
            except json.JSONDecodeError:
                if hasattr(response, "text"):
                    result_text = response.text
                else:
                    result_text = response.content

            # If not raising an exception, the MCP server will return the result as a regular text response, without marking it as an error.
            # TODO: Use a raise_for_status() method on the response (it needs to also be implemented in the AsyncClientProtocol)
            if 400 <= response.status_code < 600:
                raise Exception(
                    f"Error calling {tool_name}. Status code: {response.status_code}. Response: {response.text}"
                )

            try:
                return [types.TextContent(type="text", text=result_text)]
            except ValueError:
                return [types.TextContent(type="text", text=result_text)]

        except Exception as e:
            logger.exception(f"Error calling {tool_name}")
            raise e

    async def _request(
        self,
        client: httpx.AsyncClient,
        method: str,
        path: str,
        query: Dict[str, Any],
        headers: Dict[str, str],
        body: Optional[Any],
    ) -> Any:
        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)
        elif method.lower() == "put":
            return await client.put(path, params=query, headers=headers, json=body)
        elif method.lower() == "delete":
            return await client.delete(path, params=query, headers=headers)
        elif method.lower() == "patch":
            return await client.patch(path, params=query, headers=headers, json=body)
        else:
            raise ValueError(f"Unsupported HTTP method: {method}")

    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

        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)

        operations_to_include = set()

        if self._include_operations is not None:
            operations_to_include.update(self._include_operations)
        elif self._exclude_operations is not None:
            all_operations = {tool.name for tool in tools}
            operations_to_include.update(all_operations - set(self._exclude_operations))

        if self._include_tags is not None:
            for tag in self._include_tags:
                operations_to_include.update(operations_by_tag.get(tag, []))
        elif self._exclude_tags is not None:
            excluded_operations = set()
            for tag in self._exclude_tags:
                excluded_operations.update(operations_by_tag.get(tag, []))

            all_operations = {tool.name for tool in tools}
            operations_to_include.update(all_operations - excluded_operations)

        filtered_tools = [tool for tool in tools if tool.name in operations_to_include]

        if filtered_tools:
            filtered_operation_ids = {tool.name for tool in filtered_tools}
            self.operation_map = {
                op_id: details for op_id, details in self.operation_map.items() if op_id in filtered_operation_ids
            }

        return filtered_tools


================================================
FILE: fastapi_mcp/transport/__init__.py
================================================


================================================
FILE: fastapi_mcp/transport/http.py
================================================
import logging
import asyncio

from fastapi import Request, Response, HTTPException
from mcp.server.lowlevel.server import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager, EventStore
from mcp.server.transport_security import TransportSecuritySettings

logger = logging.getLogger(__name__)


class FastApiHttpSessionManager:
    """
    FastAPI-native wrapper around StreamableHTTPSessionManager
    """

    def __init__(
        self,
        mcp_server: Server,
        event_store: EventStore | None = None,
        json_response: bool = True,  # Default to JSON for HTTP transport
        security_settings: TransportSecuritySettings | None = None,
    ):
        self.mcp_server = mcp_server
        self.event_store = event_store
        self.json_response = json_response
        self.security_settings = security_settings
        self._session_manager: StreamableHTTPSessionManager | None = None
        self._manager_task: asyncio.Task | None = None
        self._manager_started = False
        self._startup_lock = asyncio.Lock()

    async def _ensure_session_manager_started(self) -> None:
        """
        Ensure the session manager is started.

        This is called lazily on the first request to start the session manager
        if it hasn't been started yet.
        """
        if self._manager_started:
            return

        async with self._startup_lock:
            if self._manager_started:
                return

            logger.debug("Starting StreamableHTTP session manager")

            # Create the session manager
            # Note: We don't use stateless=True because we want to support sessions
            # but sessions are optional as per the MCP spec
            self._session_manager = StreamableHTTPSessionManager(
                app=self.mcp_server,
                event_store=self.event_store,
                json_response=self.json_response,
                stateless=False,  # Always support sessions, but they're optional
                security_settings=self.security_settings,
            )

            # Start the session manager in a background task
            async def run_session_manager():
                try:
                    async with self._session_manager.run():
                        logger.info("StreamableHTTP session manager is running")
                        # Keep running until cancelled
                        await asyncio.Event().wait()
                except asyncio.CancelledError:
                    logger.info("StreamableHTTP session manager is shutting down")
                    raise
                except Exception:
                    logger.exception("Error in StreamableHTTP session manager")
                    raise

            self._manager_task = asyncio.create_task(run_session_manager())
            self._manager_started = True

            # Give the session manager a moment to initialize
            await asyncio.sleep(0.1)

    async def handle_fastapi_request(self, request: Request) -> Response:
        """
        Handle a FastAPI request by delegating to the session manager.

        This converts FastAPI's Request/Response to ASGI scope/receive/send
        and then converts the result back to a FastAPI Response.
        """
        # Ensure session manager is started
        await self._ensure_session_manager_started()

        if not self._session_manager:
            raise HTTPException(status_code=500, detail="Session manager not initialized")

        logger.debug(f"Handling FastAPI request: {request.method} {request.url.path}")

        # Capture the response from the session manager
        response_started = False
        response_status = 200
        response_headers = []
        response_body = b""

        async def send_callback(message):
            nonlocal response_started, response_status, response_headers, response_body

            if message["type"] == "http.response.start":
                response_started = True
                response_status = message["status"]
                response_headers = message.get("headers", [])
            elif message["type"] == "http.response.body":
                response_body += message.get("body", b"")

        try:
            # Delegate to the session manager's handle_request method
            await self._session_manager.handle_request(request.scope, request.receive, send_callback)

            # Convert the captured ASGI response to a FastAPI Response
            headers_dict = {name.decode(): value.decode() for name, value in response_headers}

            return Response(
                content=response_body,
                status_code=response_status,
                headers=headers_dict,
            )

        except Exception:
            logger.exception("Error in StreamableHTTPSessionManager")
            raise HTTPException(status_code=500, detail="Internal server error")

    async def shutdown(self) -> None:
        """Clean up the session manager and background task."""
        if self._manager_task and not self._manager_task.done():
            self._manager_task.cancel()
            try:
                await self._manager_task
            except asyncio.CancelledError:
                pass
        self._manager_started = False


================================================
FILE: fastapi_mcp/transport/sse.py
================================================
from uuid import UUID
import logging
from typing import Union

from anyio.streams.memory import MemoryObjectSendStream
from fastapi import Request, Response, BackgroundTasks, HTTPException
from fastapi.responses import JSONResponse
from mcp.shared.message import SessionMessage, ServerMessageMetadata
from pydantic import ValidationError
from mcp.server.sse import SseServerTransport
from mcp.types import JSONRPCMessage, JSONRPCError, ErrorData


logger = logging.getLogger(__name__)


class FastApiSseTransport(SseServerTransport):
    async def handle_fastapi_post_message(self, request: Request) -> Response:
        """
        A reimplementation of the handle_post_message method of SseServerTransport
        that integrates better with FastAPI.

        A few good reasons for doing this:
        1. Avoid mounting a whole Starlette app and instead use a more FastAPI-native
           approach. Mounting has some known issues and limitations.
        2. Avoid re-constructing the scope, receive, and send from the request, as done
           in the original implementation.
        3. Use FastAPI's native response handling mechanisms and exception patterns to
           avoid unexpected rabbit holes.

        The combination of mounting a whole Starlette app and reconstructing the scope
        and send from the request proved to be especially error-prone for us when using
        tracing tools like Sentry, which had destructive effects on the request object
        when using the original implementation.
        """

        logger.debug("Handling POST message SSE")

        session_id_param = request.query_params.get("session_id")
        if session_id_param is None:
            logger.warning("Received request without session_id")
            raise HTTPException(status_code=400, detail="session_id is required")

        try:
            session_id = UUID(hex=session_id_param)
            logger.debug(f"Parsed session ID: {session_id}")
        except ValueError:
            logger.warning(f"Received invalid session ID: {session_id_param}")
            raise HTTPException(status_code=400, detail="Invalid session ID")

        writer = self._read_stream_writers.get(session_id)
        if not writer:
            logger.warning(f"Could not find session for ID: {session_id}")
            raise HTTPException(status_code=404, detail="Could not find session")

        body = await request.body()
        logger.debug(f"Received JSON: {body.decode()}")

        try:
            message = JSONRPCMessage.model_validate_json(body)

            logger.debug(f"Validated client message: {message}")
        except ValidationError as err:
            logger.error(f"Failed to parse message: {err}")
            # Create background task to send error
            background_tasks = BackgroundTasks()
            background_tasks.add_task(self._send_message_safely, writer, err)
            response = JSONResponse(content={"error": "Could not parse message"}, status_code=400)
            response.background = background_tasks
            return response
        except Exception as e:
            logger.error(f"Error processing request body: {e}")
            raise HTTPException(status_code=400, detail="Invalid request body")

        # Create background task to send message with proper request context metadata
        background_tasks = BackgroundTasks()
        metadata = ServerMessageMetadata(request_context=request)
        session_message = SessionMessage(message, metadata=metadata)
        background_tasks.add_task(self._send_message_safely, writer, session_message)
        logger.debug("Accepting message, will send in background")

        # Return response with background task
        response = JSONResponse(content={"message": "Accepted"}, status_code=202)
        response.background = background_tasks
        return response

    async def _send_message_safely(
        self, writer: MemoryObjectSendStream[SessionMessage], message: Union[SessionMessage, ValidationError]
    ):
        """Send a message to the writer, avoiding ASGI race conditions"""

        try:
            logger.debug(f"Sending message to writer from background task: {message}")

            if isinstance(message, ValidationError):
                # Convert ValidationError to JSONRPCError
                error_data = ErrorData(
                    code=-32700,  # Parse error code in JSON-RPC
                    message="Parse error",
                    data={"validation_error": str(message)},
                )
                json_rpc_error = JSONRPCError(
                    jsonrpc="2.0",
                    id="unknown",  # We don't know the ID from the invalid request
                    error=error_data,
                )
                error_message = SessionMessage(JSONRPCMessage(root=json_rpc_error))
                await writer.send(error_message)
            else:
                await writer.send(message)
        except Exception as e:
            logger.error(f"Error sending message to writer: {e}")


================================================
FILE: fastapi_mcp/types.py
================================================
import time
from typing import Any, Dict, Annotated, Union, Optional, Sequence, Literal, List
from typing_extensions import Doc
from pydantic import (
    BaseModel,
    ConfigDict,
    HttpUrl,
    field_validator,
    model_validator,
)
from pydantic.main import IncEx
from fastapi import params


StrHttpUrl = Annotated[Union[str, HttpUrl], HttpUrl]


class BaseType(BaseModel):
    model_config = ConfigDict(extra="ignore", arbitrary_types_allowed=True)


class HTTPRequestInfo(BaseType):
    method: str
    path: str
    headers: Dict[str, str]
    cookies: Dict[str, str]
    query_params: Dict[str, str]
    body: Any


class OAuthMetadata(BaseType):
    """OAuth 2.0 Server Metadata according to RFC 8414"""

    issuer: Annotated[
        StrHttpUrl,
        Doc(
            """
            The authorization server's issuer identifier, which is a URL that uses the https scheme.
            """
        ),
    ]

    authorization_endpoint: Annotated[
        Optional[StrHttpUrl],
        Doc(
            """
            URL of the authorization server's authorization endpoint.
            """
        ),
    ] = None

    token_endpoint: Annotated[
        StrHttpUrl,
        Doc(
            """
            URL of the authorization server's token endpoint.
            """
        ),
    ]

    scopes_supported: Annotated[
        List[str],
        Doc(
            """
            List of OAuth 2.0 scopes that the authorization server supports.
            """
        ),
    ] = ["openid", "profile", "email"]

    response_types_supported: Annotated[
        List[str],
        Doc(
            """
            List of the OAuth 2.0 response_type values that the authorization server supports.
            """
        ),
    ] = ["code"]

    grant_types_supported: Annotated[
        List[str],
        Doc(
            """
            List of the OAuth 2.0 grant type values that the authorization server supports.
            """
        ),
    ] = ["authorization_code", "client_credentials"]

    token_endpoint_auth_methods_supported: Annotated[
        List[str],
        Doc(
            """
            List of client authentication methods supported by the token endpoint.
            """
        ),
    ] = ["none"]

    code_challenge_methods_supported: Annotated[
        List[str],
        Doc(
            """
            List of PKCE code challenge methods supported by the authorization server.
            """
        ),
    ] = ["S256"]

    registration_endpoint: Annotated[
        Optional[StrHttpUrl],
        Doc(
            """
            URL of the authorization server's client registration endpoint.
            """
        ),
    ] = None

    @field_validator(
        "scopes_supported",
        "response_types_supported",
        "grant_types_supported",
        "token_endpoint_auth_methods_supported",
        "code_challenge_methods_supported",
    )
    @classmethod
    def validate_non_empty_lists(cls, v, info):
        if not v:
            raise ValueError(f"{info.field_name} cannot be empty")

        return v

    @model_validator(mode="after")
    def validate_endpoints_for_grant_types(self):
        if "authorization_code" in self.grant_types_supported and not self.authorization_endpoint:
            raise ValueError("authorization_endpoint is required when authorization_code grant type is supported")
        return self

    def model_dump(
        self,
        *,
        mode: Literal["json", "python"] | str = "python",
        include: IncEx | None = None,
        exclude: IncEx | None = None,
        context: Any | None = None,
        by_alias: bool = False,
        exclude_unset: bool = True,
        exclude_defaults: bool = False,
        exclude_none: bool = True,
        round_trip: bool = False,
        warnings: bool | Literal["none", "warn", "error"] = True,
        serialize_as_any: bool = False,
    ) -> dict[str, Any]:
        # Always exclude unset and None fields, since clients don't take it well when
        # OAuth metadata fields are present but empty.
        exclude_unset = True
        exclude_none = True
        return super().model_dump(
            mode=mode,
            include=include,
            exclude=exclude,
            context=context,
            by_alias=by_alias,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=exclude_none,
            round_trip=round_trip,
            warnings=warnings,
            serialize_as_any=serialize_as_any,
        )


OAuthMetadataDict = Annotated[Union[Dict[str, Any], OAuthMetadata], OAuthMetadata]


class AuthConfig(BaseType):
    version: Annotated[
        Literal["2025-03-26"],
        Doc(
            """
            The MCP spec version to use for setting up authorization.
            Currently only "2025-03-26" is supported.
            """
        ),
    ] = "2025-03-26"

    dependencies: Annotated[
        Optional[Sequence[params.Depends]],
        Doc(
            """
            FastAPI dependencies (using `Depends()`) that check for authentication or authorization
            and raise 401 or 403 errors if the request is not authenticated or authorized.

            This is necessary to trigger the client to start an OAuth flow.

            Example:
            ```python
            # Your authentication dependency
            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

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

    issuer: Annotated[
        Optional[str],
        Doc(
            """
            The issuer of the OAuth 2.0 server.
            Required if you don't provide `custom_oauth_metadata`.
            Usually it's either the base URL of your app, or the URL of the OAuth provider.
            For example, for Auth0, this would be `https://your-tenant.auth0.com`.
            """
        ),
    ] = None

    oauth_metadata_url: Annotated[
        Optional[StrHttpUrl],
        Doc(
            """
            The full URL of the OAuth provider's metadata endpoint.

            If not provided, FastAPI-MCP will attempt to guess based on the `issuer` and `metadata_path`.

            Only relevant if `setup_proxies` is `True`.

            If this URL is wrong, the metadata proxy will not work.
            """
        ),
    ] = None

    authorize_url: Annotated[
        Optional[StrHttpUrl],
        Doc(
            """
            The URL of your OAuth provider's authorization endpoint.

            Usually this is something like `https://app.example.com/oauth/authorize`.
            """
        ),
    ] = None

    audience: Annotated[
        Optional[str],
        Doc(
            """
            Currently (2025-04-21), some Auth-supporting MCP clients (like `npx mcp-remote`) might not specify the
            audience when sending a request to your server.

            This may cause unexpected behavior from your OAuth provider, so this is a workaround.

            In case the client doesn't specify an audience, this will be used as the default audience on the
            request to your OAuth provider.
            """
        ),
    ] = None

    default_scope: Annotated[
        str,
        Doc(
            """
            Currently (2025-04-21), some Auth-supporting MCP clients (like `npx mcp-remote`) might not specify the
            scope when sending a request to your server.

            This may cause unexpected behavior from your OAuth provider, so this is a workaround.

            Here is where you can optionally specify a default scope that will be sent to your OAuth provider in case
            the client doesn't specify it.
            """
        ),
    ] = "openid profile email"

    client_id: Annotated[
        Optional[str],
        Doc(
            """
            In case the client doesn't specify a client ID, this will be used as the default client ID on the
            request to your OAuth provider.

            This is mandatory only if you set `setup_proxies` to `True`.
            """
        ),
    ] = None

    client_secret: Annotated[
        Optional[str],
        Doc(
            """
            The client secret to use for the client ID.

            This is mandatory only if you set `setup_proxies` to `True` and `setup_fake_dynamic_registration` to `True`.
            """
        ),
    ] = None

    custom_oauth_metadata: Annotated[
        Optional[OAuthMetadataDict],
        Doc(
            """
            Custom OAuth metadata to register.

            If your OAuth flow works with MCP out-of-the-box, you should just use this option to provide the
            metadata yourself.

            Otherwise, set `setup_proxies` to `True` to automatically setup MCP-compliant proxies around your
            OAuth provider's endpoints.
            """
        ),
    ] = None

    setup_proxies: Annotated[
        bool,
        Doc(
            """
            Whether to automatically setup MCP-compliant proxies around your original OAuth provider's endpoints.
            """
        ),
    ] = False

    setup_fake_dynamic_registration: Annotated[
        bool,
        Doc(
            """
            Whether to automatically setup a fake dynamic client registration endpoint.

            In MCP 2025-03-26 Spec, it is recommended to support OAuth Dynamic Client Registration (RFC 7591).
            Furthermore, `npx mcp-remote` which is the current de-facto client that supports MCP's up-to-date spec,
            requires this endpoint to be present.

            For most cases, a fake dynamic registration endpoint is enough, thus you should set this to `True`.

            This is only used if `setup_proxies` is also `True`.
            """
        ),
    ] = True

    metadata_path: Annotated[
        str,
        Doc(
            """
            The path to mount the OAuth metadata endpoint at.

            Clients will usually expect this to be /.well-known/oauth-authorization-server
            """
        ),
    ] = "/.well-known/oauth-authorization-server"

    @model_validator(mode="after")
    def validate_required_fields(self):
        if self.custom_oauth_metadata is None and self.issuer is None and not self.dependencies:
            raise ValueError("at least one of 'issuer', 'custom_oauth_metadata' or 'dependencies' is required")

        if self.setup_proxies:
            if self.client_id is None:
                raise ValueError("'client_id' is required when 'setup_proxies' is True")

            if self.setup_fake_dynamic_registration and not self.client_secret:
                raise ValueError("'client_secret' is required when 'setup_fake_dynamic_registration' is True")

        return self


class ClientRegistrationRequest(BaseType):
    redirect_uris: List[str]
    client_name: Optional[str] = None
    grant_types: Optional[List[str]] = ["authorization_code"]
    token_endpoint_auth_method: Optional[str] = "none"


class ClientRegistrationResponse(BaseType):
    client_id: str
    client_id_issued_at: int = int(time.time())
    client_secret: Optional[str] = None
    client_secret_expires_at: int = 0
    redirect_uris: List[str]
    grant_types: List[str]
    token_endpoint_auth_method: str
    client_name: str


================================================
FILE: fastapi_mcp/utils/__init__.py
================================================


================================================
FILE: mypy.ini
================================================
[mypy]


================================================
FILE: pyproject.toml
================================================
[build-system]
requires = ["hatchling", "tomli"]
build-backend = "hatchling.build"

[project]
name = "fastapi-mcp"
version = "0.4.0"
description = "Automatic MCP server generator for FastAPI applications - converts FastAPI endpoints to MCP tools for LLM integration"
readme = "README.md"
requires-python = ">=3.10"
license = {file = "LICENSE"}
authors = [
    {name = "Tadata Inc.", email = "itay@tadata.com"},
]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Topic :: Internet :: WWW/HTTP",
    "Framework :: FastAPI",
]
keywords = ["fastapi", "openapi", "mcp", "llm", "claude", "ai", "tools", "api", "conversion", "modelcontextprotocol"]
dependencies = [
    "fastapi>=0.100.0",
    "typer>=0.9.0",
    "rich>=13.0.0",
    "mcp>=1.12.0",
    "pydantic>=2.0.0",
    "pydantic-settings>=2.5.2",
    "uvicorn>=0.20.0",
    "httpx>=0.24.0",
    "requests>=2.25.0",
    "tomli>=2.2.1",
]

[dependency-groups]
dev = [
    "mypy>=1.15.0",
    "ruff>=0.9.10",
    "types-setuptools>=75.8.2.20250305",
    "pytest>=8.3.5",
    "pytest-asyncio>=0.26.0",
    "pytest-cov>=6.1.1",
    "pre-commit>=4.2.0",
    "pyjwt>=2.10.1",
    "cryptography>=44.0.2",
    "types-jsonschema>=4.25.0.20250720",
]

[project.urls]
Homepage = "https://github.com/tadata-org/fastapi_mcp"
Documentation = "https://github.com/tadata-org/fastapi_mcp#readme"
"Bug Tracker" = "https://github.com/tadata-org/fastapi_mcp/issues"
"PyPI" = "https://pypi.org/project/fastapi-mcp/"
"Source Code" = "https://github.com/tadata-org/fastapi_mcp"
"Changelog" = "https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md"

[tool.hatch.build.targets.wheel]
packages = ["fastapi_mcp"]

[tool.ruff]
line-length = 120
target-version = "py312"

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
python_files = "test_*.py"


================================================
FILE: pytest.ini
================================================
[pytest]
addopts = -vvv --cov=. --cov-report xml --cov-report term-missing --cov-fail-under=80 --cov-config=.coveragerc
asyncio_mode = auto
log_cli = true
log_cli_level = DEBUG
log_cli_format = %(asctime)s - %(name)s - %(levelname)s - %(message)s


================================================
FILE: tests/__init__.py
================================================


================================================
FILE: tests/conftest.py
================================================
import sys
import os
import pytest
import coverage

# Add the parent directory to the path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from .fixtures.types import *  # noqa: F403
from .fixtures.example_data import *  # noqa: F403
from .fixtures.simple_app import *  # noqa: F403
from .fixtures.complex_app import *  # noqa: F403


@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    """Configure pytest-cov for proper subprocess coverage."""
    if config.pluginmanager.hasplugin("pytest_cov"):
        # Ensure environment variables are set for subprocess coverage
        os.environ["COVERAGE_PROCESS_START"] = os.path.abspath(".coveragerc")

        # Set up environment for combinining coverage data from subprocesses
        os.environ["PYTHONPATH"] = os.path.abspath(".")

        # Make sure the pytest-cov plugin is active for subprocesses
        config.option.cov_fail_under = 0  # Disable fail under in the primary process


@pytest.hookimpl(trylast=True)
def pytest_sessionfinish(session, exitstatus):
    """Combine coverage data from subprocesses at the end of the test session."""
    cov_dir = os.path.abspath(".")
    if exitstatus == 0 and os.environ.get("COVERAGE_PROCESS_START"):
        try:
            cov = coverage.Coverage()
            cov.combine(data_paths=[cov_dir], strict=True)
            cov.save()
        except Exception as e:
            print(f"Error combining coverage data: {e}", file=sys.stderr)


================================================
FILE: tests/fixtures/complex_app.py
================================================
from typing import Optional, List, Dict, Any, Union
from uuid import UUID

from fastapi import FastAPI, Query, Path, Body, Header, Cookie
import pytest

from tests.fixtures.conftest import make_fastapi_app_base

from .types import (
    Product,
    Customer,
    OrderResponse,
    PaginatedResponse,
    ProductCategory,
    OrderRequest,
    ErrorResponse,
)


def make_complex_fastapi_app(
    example_product: Product,
    example_customer: Customer,
    example_order_response: OrderResponse,
    parametrized_config: dict[str, Any] | None = None,
) -> FastAPI:
    app = make_fastapi_app_base(parametrized_config=parametrized_config)

    @app.get(
        "/products",
        response_model=PaginatedResponse,
        tags=["products"],
        operation_id="list_products",
        response_model_exclude_none=True,
    )
    async def list_products(
        category: Optional[ProductCategory] = Query(None, description="Filter by product category"),
        min_price: Optional[float] = Query(None, description="Minimum price filter", gt=0),
        max_price: Optional[float] = Query(None, description="Maximum price filter", gt=0),
        tag: Optional[List[str]] = Query(None, description="Filter by tags"),
        sort_by: str = Query("created_at", description="Field to sort by"),
        sort_direction: str = Query("desc", description="Sort direction (asc or desc)"),
        in_stock_only: bool = Query(False, description="Show only in-stock products"),
        page: int = Query(1, description="Page number", ge=1),
        size: int = Query(20, description="Page size", ge=1, le=100),
        user_agent: Optional[str] = Header(None, description="User agent header"),
    ):
        """
        List products with various filtering, sorting and pagination options.
        Returns a paginated response of products.
        """
        return PaginatedResponse(items=[example_product], total=1, page=page, size=size, pages=1)

    @app.get(
        "/products/{product_id}",
        response_model=Product,
        tags=["products"],
        operation_id="get_product",
        responses={
            404: {"model": ErrorResponse, "description": "Product not found"},
        },
    )
    async def get_product(
        product_id: UUID = Path(..., description="The ID of the product to retrieve"),
        include_unavailable: bool = Query(False, description="Include product even if not available"),
    ):
        """
        Get detailed information about a specific product by its ID.
        Includes all variants, images, and metadata.
        """
        # Just returning the example product with the requested ID
        product_copy = example_product.model_copy()
        product_copy.id = product_id
        return product_copy

    @app.post(
        "/orders",
        response_model=OrderResponse,
        tags=["orders"],
        operation_id="create_order",
        status_code=201,
        responses={
            400: {"model": ErrorResponse, "description": "Invalid order data"},
            404: {"model": ErrorResponse, "description": "Customer or product not found"},
            422: {"model": ErrorResponse, "description": "Validation error"},
        },
    )
    async def create_order(
        order: OrderRequest = Body(..., description="Order details"),
        user_id: Optional[UUID] = Cookie(None, description="User ID from cookie"),
        authorization: Optional[str] = Header(None, description="Authorization header"),
    ):
        """
        Create a new order with multiple items, shipping details, and payment information.
        Returns the created order with full details including status and tracking information.
        """
        # Return a copy of the example order response with the customer ID from the request
        order_copy = example_order_response.model_copy()
        order_copy.customer_id = order.customer_id
        order_copy.items = order.items
        return order_copy

    @app.get(
        "/customers/{customer_id}",
        response_model=Union[Customer, Dict[str, Any]],
        tags=["customers"],
        operation_id="get_customer",
        responses={
            404: {"model": ErrorResponse, "description": "Customer not found"},
            403: {"model": ErrorResponse, "description": "Forbidden access"},
        },
    )
    async def get_customer(
        customer_id: UUID = Path(..., description="The ID of the customer to retrieve"),
        include_orders: bool = Query(False, description="Include customer's order history"),
        include_payment_methods: bool = Query(False, description="Include customer's saved payment methods"),
        fields: List[str] = Query(None, description="Specific fields to include in response"),
    ):
        """
        Get detailed information about a specific customer by ID.
        Can include additional related information like order history.
        """
        # Return a copy of the example customer with the requested ID
        customer_copy = example_customer.model_copy()
        customer_copy.id = customer_id
        return customer_copy

    return app


@pytest.fixture
def complex_fastapi_app(
    example_product: Product,
    example_customer: Customer,
    example_order_response: OrderResponse,
) -> FastAPI:
    return make_complex_fastapi_app(
        example_product=example_product,
        example_customer=example_customer,
        example_order_response=example_order_response,
    )


================================================
FILE: tests/fixtures/conftest.py
================================================
from typing import Any
from fastapi import FastAPI


def make_fastapi_app_base(parametrized_config: dict[str, Any] | None = None) -> FastAPI:
    fastapi_config: dict[str, Any] = {
        "title": "Test API",
        "description": "A test API app for unit testing",
        "version": "0.1.0",
    }
    app = FastAPI(**fastapi_config | parametrized_config if parametrized_config is not None else {})
    return app


================================================
FILE: tests/fixtures/example_data.py
================================================
from datetime import datetime, date
from uuid import UUID

import pytest

from .types import (
    Address,
    ProductVariant,
    Product,
    ProductCategory,
    Customer,
    CustomerTier,
    OrderItem,
    PaymentDetails,
    OrderRequest,
    OrderResponse,
    PaginatedResponse,
    OrderStatus,
    PaymentMethod,
)


@pytest.fixture
def example_address() -> Address:
    return Address(street="123 Main St", city="Anytown", state="CA", postal_code="12345", country="US", is_primary=True)


@pytest.fixture
def example_product_variant() -> ProductVariant:
    return ProductVariant(
        sku="EP-001-BLK", color="Black", stock_count=10, size=None, weight=None, dimensions=None, in_stock=True
    )


@pytest.fixture
def example_product(example_product_variant) -> Product:
    return Product(
        id=UUID("550e8400-e29b-41d4-a716-446655440000"),
        name="Example Product",
        description="This is an example product",
        category=ProductCategory.ELECTRONICS,
        price=199.99,
        discount_percent=None,
        tax_rate=None,
        rating=None,
        review_count=0,
        tags=["example", "new"],
        image_urls=["https://example.com/image.jpg"],
        created_at=datetime.now(),
        variants=[example_product_variant],
    )


@pytest.fixture
def example_customer(example_address) -> Customer:
    return Customer(
        id=UUID("770f9511-f39c-42d5-a860-557654551222"),
        email="customer@example.com",
        full_name="John Doe",
        phone="1234567890",
        tier=CustomerTier.STANDARD,
        addresses=[example_address],
        created_at=datetime.now(),
        preferences={"theme": "dark", "notifications": True},
        consent={"marketing": True, "analytics": True},
    )


@pytest.fixture
def example_order_item() -> OrderItem:
    return OrderItem(
        product_id=UUID("550e8400-e29b-41d4-a716-446655440000"),
        variant_sku="EP-001-BLK",
        quantity=2,
        unit_price=199.99,
        discount_amount=10.00,
        total=389.98,
    )


@pytest.fixture
def example_payment_details() -> PaymentDetails:
    return PaymentDetails(
        method=PaymentMethod.CREDIT_CARD,
        transaction_id="txn_12345",
        status="completed",
        amount=389.98,
        currency="USD",
        paid_at=datetime.now(),
    )


@pytest.fixture
def example_order_request(example_order_item) -> OrderRequest:
    return OrderRequest(
        customer_id=UUID("770f9511-f39c-42d5-a860-557654551222"),
        items=[example_order_item],
        shipping_address_id=UUID("880f9511-f39c-42d5-a860-557654551333"),
        billing_address_id=None,
        payment_method=PaymentMethod.CREDIT_CARD,
        notes="Please deliver before 6pm",
        use_loyalty_points=False,
    )


@pytest.fixture
def example_order_response(example_order_item, example_address, example_payment_details) -> OrderResponse:
    return OrderResponse(
        id=UUID("660f9511-f39c-42d5-a860-557654551111"),
        customer_id=UUID("770f9511-f39c-42d5-a860-557654551222"),
        status=OrderStatus.PENDING,
        items=[example_order_item],
        shipping_address=example_address,
        billing_address=example_address,
        payment=example_payment_details,
        subtotal=389.98,
        shipping_cost=10.0,
        tax_amount=20.0,
        discount_amount=10.0,
        total_amount=409.98,
        tracking_number="TRK123456789",
        estimated_delivery=date.today(),
        created_at=datetime.now(),
        notes="Please deliver before 6pm",
        metadata={},
    )


@pytest.fixture
def example_paginated_products(example_product) -> PaginatedResponse:
    return PaginatedResponse(items=[example_product], total=1, page=1, size=20, pages=1)


================================================
FILE: tests/fixtures/simple_app.py
================================================
from typing import Optional, List, Any

from fastapi import FastAPI, Query, Path, Body, HTTPException
import pytest

from tests.fixtures.conftest import make_fastapi_app_base

from .types import Item


def make_simple_fastapi_app(parametrized_config: dict[str, Any] | None = None) -> FastAPI:
    app = make_fastapi_app_base(parametrized_config=parametrized_config)
    items = [
        Item(id=1, name="Item 1", price=10.0, tags=["tag1", "tag2"], description="Item 1 description"),
        Item(id=2, name="Item 2", price=20.0, tags=["tag2", "tag3"]),
        Item(id=3, name="Item 3", price=30.0, tags=["tag3", "tag4"], description="Item 3 description"),
    ]

    @app.get("/items/", response_model=List[Item], tags=["items"], operation_id="list_items")
    async def list_items(
        skip: int = Query(0, description="Number of items to skip"),
        limit: int = Query(10, description="Max number of items to return"),
        sort_by: Optional[str] = Query(None, description="Field to sort by"),
    ) -> List[Item]:
        """List all items with pagination and sorting options."""
        return items[skip : skip + limit]

    @app.get("/items/{item_id}", response_model=Item, tags=["items"], operation_id="get_item")
    async def read_item(
        item_id: int = Path(..., description="The ID of the item to retrieve"),
        include_details: bool = Query(False, description="Include additional details"),
    ) -> Item:
        """Get a specific item by its ID with optional details."""
        found_item = next((item for item in items if item.id == item_id), None)
        if found_item is None:
            raise HTTPException(status_code=404, detail="Item not found")
        return found_item

    @app.post("/items/", response_model=Item, tags=["items"], operation_id="create_item")
    async def create_item(item: Item = Body(..., description="The item to create")) -> Item:
        """Create a new item in the database."""
        items.append(item)
        return item

    @app.put("/items/{item_id}", response_model=Item, tags=["items"], operation_id="update_item")
    async def update_item(
        item_id: int = Path(..., description="The ID of the item to update"),
        item: Item = Body(..., description="The updated item data"),
    ) -> Item:
        """Update an existing item."""
        item.id = item_id
        return item

    @app.delete("/items/{item_id}", status_code=204, tags=["items"], operation_id="delete_item")
    async def delete_item(item_id: int = Path(..., description="The ID of the item to delete")) -> None:
        """Delete an item from the database."""
        return None

    @app.get("/error", tags=["error"], operation_id="raise_error")
    async def raise_error() -> None:
        """Fail on purpose and cause a 500 error."""
        raise Exception("This is a test error")

    return app


@pytest.fixture
def simple_fastapi_app() -> FastAPI:
    return make_simple_fastapi_app()


@pytest.fixture
def simple_fastapi_app_with_root_path() -> FastAPI:
    return make_simple_fastapi_app(parametrized_config={"root_path": "/api/v1"})


================================================
FILE: tests/fixtures/types.py
================================================
from typing import Optional, List, Dict, Any
from datetime import datetime, date
from enum import Enum
from uuid import UUID

from pydantic import BaseModel, Field


class Item(BaseModel):
    id: int
    name: str
    description: Optional[str] = None
    price: float
    tags: List[str] = []


class OrderStatus(str, Enum):
    PENDING = "pending"
    PROCESSING = "processing"
    SHIPPED = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"
    RETURNED = "returned"


class PaymentMethod(str, Enum):
    CREDIT_CARD = "credit_card"
    DEBIT_CARD = "debit_card"
    PAYPAL = "paypal"
    BANK_TRANSFER = "bank_transfer"
    CASH_ON_DELIVERY = "cash_on_delivery"


class ProductCategory(str, Enum):
    ELECTRONICS = "electronics"
    CLOTHING = "clothing"
    FOOD = "food"
    BOOKS = "books"
    OTHER = "other"


class ProductVariant(BaseModel):
    sku: str = Field(..., description="Stock keeping unit code")
    color: Optional[str] = Field(None, description="Color variant")
    size: Optional[str] = Field(None, description="Size variant")
    weight: Optional[float] = Field(None, description="Weight in kg", gt=0)
    dimensions: Optional[Dict[str, float]] = Field(None, description="Dimensions in cm (length, width, height)")
    in_stock: bool = Field(True, description="Whether this variant is in stock")
    stock_count: Optional[int] = Field(None, description="Number of items in stock", ge=0)


class Address(BaseModel):
    street: str
    city: str
    state: str
    postal_code: str
    country: str
    is_primary: bool = False


class CustomerTier(str, Enum):
    STANDARD = "standard"
    PREMIUM = "premium"
    VIP = "vip"


class Customer(BaseModel):
    id: UUID
    email: str
    full_name: str
    phone: Optional[str] = Field(None, min_length=10, max_length=15)
    tier: CustomerTier = CustomerTier.STANDARD
    addresses: List[Address] = []
    is_active: bool = True
    created_at: datetime
    last_login: Optional[datetime] = None
    preferences: Dict[str, Any] = {}
    consent: Dict[str, bool] = {}


class Product(BaseModel):
    id: UUID
    name: str
    description: str
    category: ProductCategory
    price: float = Field(..., gt=0)
    discount_percent: Optional[float] = Field(None, ge=0, le=100)
    tax_rate: Optional[float] = Field(None, ge=0, le=100)
    variants: List[ProductVariant] = []
    tags: List[str] = []
    image_urls: List[str] = []
    rating: Optional[float] = Field(None, ge=0, le=5)
    review_count: int = Field(0, ge=0)
    created_at: datetime
    updated_at: Optional[datetime] = None
    is_available: bool = True
    metadata: Dict[str, Any] = {}


class OrderItem(BaseModel):
    product_id: UUID
    variant_sku: Optional[str] = None
    quantity: int = Field(..., gt=0)
    unit_price: float
    discount_amount: float = 0
    total: float


class PaymentDetails(BaseModel):
    method: PaymentMethod
    transaction_id: Optional[str] = None
    status: str
    amount: float
    currency: str = "USD"
    paid_at: Optional[datetime] = None


class OrderRequest(BaseModel):
    customer_id: UUID
    items: List[OrderItem]
    shipping_address_id: UUID
    billing_address_id: Optional[UUID] = None
    payment_method: PaymentMethod
    notes: Optional[str] = None
    use_loyalty_points: bool = False


class OrderResponse(BaseModel):
    id: UUID
    customer_id: UUID
    status: OrderStatus = OrderStatus.PENDING
    items: List[OrderItem]
    shipping_address: Address
    billing_address: Address
    payment: PaymentDetails
    subtotal: float
    shipping_cost: float
    tax_amount: float
    discount_amount: float
    total_amount: float
    tracking_number: Optional[str] = None
    estimated_delivery: Optional[date] = None
    created_at: datetime
    updated_at: Optional[datetime] = None
    notes: Optional[str] = None
    metadata: Dict[str, Any] = {}


class PaginatedResponse(BaseModel):
    items: List[Any]
    total: int
    page: int
    size: int
    pages: int


class ErrorResponse(BaseModel):
    status_code: int
    message: str
    details: Optional[Dict[str, Any]] = None


================================================
FILE: tests/test_basic_functionality.py
================================================
from fastapi import FastAPI
from mcp.server.lowlevel.server import Server

from fastapi_mcp import FastApiMCP


def test_create_mcp_server(simple_fastapi_app: FastAPI):
    """Test creating an MCP server without mounting it."""
    mcp = FastApiMCP(
        simple_fastapi_app,
        name="Test MCP Server",
        description="Test description",
    )

    # Verify the MCP server was created correctly
    assert mcp.name == "Test MCP Server"
    assert mcp.description == "Test description"
    assert isinstance(mcp.server, Server)
    assert len(mcp.tools) > 0, "Should have extracted tools from the app"
    assert len(mcp.operation_map) > 0, "Should have operation mapping"

    # Check that the operation map contains all expected operations from simple_app
    expected_operations = ["list_items", "get_item", "create_item", "update_item", "delete_item", "raise_error"]
    for op in expected_operations:
        assert op in mcp.operation_map, f"Operation {op} not found in operation map"


def test_default_values(simple_fastapi_app: FastAPI):
    """Test that default values are used when not explicitly provided."""
    mcp = FastApiMCP(simple_fastapi_app)

    # Verify default values
    assert mcp.name == simple_fastapi_app.title
    assert mcp.description == simple_fastapi_app.description

    # Mount with default path
    mcp.mount()

    # Check that the MCP server was properly mounted
    # Look for a route that includes our mount path in its pattern
    route_found = any("/mcp" in str(route) for route in simple_fastapi_app.routes)
    assert route_found, "MCP server mount point not found in app routes"


def test_normalize_paths(simple_fastapi_app: FastAPI):
    """Test that mount paths are normalized correctly."""
    mcp = FastApiMCP(simple_fastapi_app)

    # Test with path without leading slash
    mount_path = "test-mcp"
    mcp.mount(mount_path=mount_path)

    # Check that the route was added with a normalized path
    route_found = any("/test-mcp" in str(route) for route in simple_fastapi_app.routes)
    assert route_found, "Normalized mount path not found in app routes"

    # Create a new MCP server
    mcp2 = FastApiMCP(simple_fastapi_app)

    # Test with path with trailing slash
    mount_path = "/test-mcp2/"
    mcp2.mount(mount_path=mount_path)

    # Check that the route was added with a normalized path
    route_found = any("/test-mcp2" in str(route) for route in simple_fastapi_app.routes)
    assert route_found, "Normalized mount path not found in app routes"


================================================
FILE: tests/test_configuration.py
================================================
from fastapi import FastAPI
import pytest

from fastapi_mcp import FastApiMCP


def test_default_configuration(simple_fastapi_app: FastAPI):
    """Test the default configuration of FastApiMCP."""
    # Create MCP server with defaults
    mcp_server = FastApiMCP(simple_fastapi_app)

    # Check default name and description
    assert mcp_server.name == simple_fastapi_app.title
    assert mcp_server.description == simple_fastapi_app.description

    # Check default options
    assert mcp_server._describe_all_responses is False
    assert mcp_server._describe_full_response_schema is False


def test_custom_configuration(simple_fastapi_app: FastAPI):
    """Test a custom configuration of FastApiMCP."""
    # Create MCP server with custom options
    custom_name = "Custom MCP Server"
    custom_description = "A custom MCP server for testing"

    mcp_server = FastApiMCP(
        simple_fastapi_app,
        name=custom_name,
        description=custom_description,
        describe_all_responses=True,
        describe_full_response_schema=True,
    )

    # Check custom name and description
    assert mcp_server.name == custom_name
    assert mcp_server.description == custom_description

    # Check custom options
    assert mcp_server._describe_all_responses is True
    assert mcp_server._describe_full_response_schema is True


def test_describe_all_responses_config_simple_app(simple_fastapi_app: FastAPI):
    """Test the describe_all_responses behavior with the simple app."""
    mcp_default = FastApiMCP(
        simple_fastapi_app,
    )

    mcp_all_responses = FastApiMCP(
        simple_fastapi_app,
        describe_all_responses=True,
    )

    for tool in mcp_default.tools:
        assert tool.description is not None
        if tool.name == "raise_error":
            pass
        elif tool.name != "delete_item":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**Example Response:**") == 1, (
                "The description should only contain one example response"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain a full output schema"
            )
        else:
            # The delete endpoint in the Items API returns a 204 status code
            assert tool.description.count("**200**") == 0, "The description should not contain a 200 status code"
            assert tool.description.count("**204**") == 1, "The description should contain a 204 status code"
            # The delete endpoint in the Items API returns a 204 status code and has no response body
            assert tool.description.count("**Example Response:**") == 0, (
                "The description should not contain any example responses"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain a full output schema"
            )

    for tool in mcp_all_responses.tools:
        assert tool.description is not None
        if tool.name == "raise_error":
            pass
        elif tool.name != "delete_item":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            assert tool.description.count("**Example Response:**") == 2, (
                "The description should contain two example responses"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain a full output schema"
            )
        else:
            assert tool.description.count("**204**") == 1, "The description should contain a 204 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            # The delete endpoint in the Items API returns a 204 status code and has no response body
            # But FastAPI's default 422 response should be present
            # So just 1 instance of Example Response should be present
            assert tool.description.count("**Example Response:**") == 1, (
                "The description should contain one example response"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain any output schema"
            )


def test_describe_full_response_schema_config_simple_app(simple_fastapi_app: FastAPI):
    """Test the describe_full_response_schema behavior with the simple app."""

    mcp_full_response_schema = FastApiMCP(
        simple_fastapi_app,
        describe_full_response_schema=True,
    )

    for tool in mcp_full_response_schema.tools:
        assert tool.description is not None
        if tool.name == "raise_error":
            pass
        elif tool.name != "delete_item":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**Example Response:**") == 1, (
                "The description should only contain one example response"
            )
            assert tool.description.count("**Output Schema:**") == 1, (
                "The description should contain one full output schema"
            )
        else:
            # The delete endpoint in the Items API returns a 204 status code
            assert tool.description.count("**200**") == 0, "The description should not contain a 200 status code"
            assert tool.description.count("**204**") == 1, "The description should contain a 204 status code"
            # The delete endpoint in the Items API returns a 204 status code and has no response body
            assert tool.description.count("**Example Response:**") == 0, (
                "The description should not contain any example responses"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain a full output schema"
            )


def test_describe_all_responses_and_full_response_schema_config_simple_app(simple_fastapi_app: FastAPI):
    """Test the describe_all_responses and describe_full_response_schema params together with the simple app."""

    mcp_all_responses_and_full_response_schema = FastApiMCP(
        simple_fastapi_app,
        describe_all_responses=True,
        describe_full_response_schema=True,
    )

    for tool in mcp_all_responses_and_full_response_schema.tools:
        assert tool.description is not None
        if tool.name == "raise_error":
            pass
        elif tool.name != "delete_item":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            assert tool.description.count("**Example Response:**") == 2, (
                "The description should contain two example responses"
            )
            assert tool.description.count("**Output Schema:**") == 2, (
                "The description should contain two full output schemas"
            )
        else:
            # The delete endpoint in the Items API returns a 204 status code
            assert tool.description.count("**200**") == 0, "The description should not contain a 200 status code"
            assert tool.description.count("**204**") == 1, "The description should contain a 204 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            # The delete endpoint in the Items API returns a 204 status code and has no response body
            # But FastAPI's default 422 response should be present
            # So just 1 instance of Example Response and Output Schema should be present
            assert tool.description.count("**Example Response:**") == 1, (
                "The description should contain one example response"
            )
            assert tool.description.count("**Output Schema:**") == 1, (
                "The description should contain one full output schema"
            )


def test_describe_all_responses_config_complex_app(complex_fastapi_app: FastAPI):
    """Test the describe_all_responses behavior with the complex app."""
    mcp_default = FastApiMCP(
        complex_fastapi_app,
    )

    mcp_all_responses = FastApiMCP(
        complex_fastapi_app,
        describe_all_responses=True,
    )

    # Test default behavior (only success responses)
    for tool in mcp_default.tools:
        assert tool.description is not None

        # Check get_product which has a 200 response and 404 error response defined
        if tool.name == "get_product":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**404**") == 0, "The description should not contain a 404 status code"
            # Some endpoints might not have example responses if they couldn't be generated
            # Only verify no error responses are included

        # Check create_order which has 201, 400, 404, and 422 responses defined
        elif tool.name == "create_order":
            assert tool.description.count("**201**") == 1, "The description should contain a 201 status code"
            assert tool.description.count("**400**") == 0, "The description should not contain a 400 status code"
            assert tool.description.count("**404**") == 0, "The description should not contain a 404 status code"
            assert tool.description.count("**422**") == 0, "The description should not contain a 422 status code"
            # Some endpoints might not have example responses if they couldn't be generated

        # Check get_customer which has 200, 404, and 403 responses defined
        elif tool.name == "get_customer":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**404**") == 0, "The description should not contain a 404 status code"
            assert tool.description.count("**403**") == 0, "The description should not contain a 403 status code"
            # Based on the error message, this endpoint doesn't have example responses in the description
            assert tool.description.count("**Example Response:**") == 0, (
                "This endpoint doesn't appear to have example responses in the default configuration"
            )
            assert tool.description.count("**Output Schema:**") == 0, (
                "The description should not contain a full output schema"
            )

    # Test with describe_all_responses=True (should include error responses)
    for tool in mcp_all_responses.tools:
        assert tool.description is not None

        # Check get_product which has a 200 response and 404 error response defined
        if tool.name == "get_product":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**404**") == 1, "The description should contain a 404 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            # Don't check exact count as implementations may vary, just ensure there are examples

        # Check create_order which has 201, 400, 404, and 422 responses defined
        elif tool.name == "create_order":
            assert tool.description.count("**201**") == 1, "The description should contain a 201 status code"
            assert tool.description.count("**400**") == 1, "The description should contain a 400 status code"
            assert tool.description.count("**404**") == 1, "The description should contain a 404 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            # Don't check exact count as implementations may vary, just ensure there are examples

        # Check get_customer which has 200, 404, and 403 responses defined
        elif tool.name == "get_customer":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**404**") == 1, "The description should contain a 404 status code"
            assert tool.description.count("**403**") == 1, "The description should contain a 403 status code"
            assert tool.description.count("**422**") == 1, "The description should contain a 422 status code"
            # Based on error messages, we need to check actual implementation behavior


def test_describe_full_response_schema_config_complex_app(complex_fastapi_app: FastAPI):
    """Test the describe_full_response_schema behavior with the complex app."""
    mcp_full_response_schema = FastApiMCP(
        complex_fastapi_app,
        describe_full_response_schema=True,
    )

    for tool in mcp_full_response_schema.tools:
        assert tool.description is not None

        # Check get_product which has a 200 response and 404 error response defined
        if tool.name == "get_product":
            assert tool.description.count("**200**") == 1, "The description should contain a 200 status code"
            assert tool.description.count("**404**") == 0, "The description should not contain a 404 status code"
            # Only verify the success response schema is present
            assert tool.description.count("**Output Schema:**") >= 1, (
                "The description should contain at least o
Download .txt
gitextract_ks2z9rdn/

├── .coveragerc
├── .cursorignore
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── documentation.md
│   │   └── feature_request.md
│   ├── codecov.yml
│   ├── dependabot.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── ci.yml
│       └── release.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .python-version
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── README_zh-CN.md
├── docs/
│   ├── advanced/
│   │   ├── asgi.mdx
│   │   ├── auth.mdx
│   │   ├── deploy.mdx
│   │   ├── refresh.mdx
│   │   └── transport.mdx
│   ├── configurations/
│   │   ├── customization.mdx
│   │   └── tool-naming.mdx
│   ├── docs.json
│   └── getting-started/
│       ├── FAQ.mdx
│       ├── best-practices.mdx
│       ├── installation.mdx
│       ├── quickstart.mdx
│       └── welcome.mdx
├── examples/
│   ├── 01_basic_usage_example.py
│   ├── 02_full_schema_description_example.py
│   ├── 03_custom_exposed_endpoints_example.py
│   ├── 04_separate_server_example.py
│   ├── 05_reregister_tools_example.py
│   ├── 06_custom_mcp_router_example.py
│   ├── 07_configure_http_timeout_example.py
│   ├── 08_auth_example_token_passthrough.py
│   ├── 09_auth_example_auth0.py
│   ├── README.md
│   ├── __init__.py
│   └── shared/
│       ├── __init__.py
│       ├── apps/
│       │   ├── __init__.py
│       │   └── items.py
│       ├── auth.py
│       └── setup.py
├── fastapi_mcp/
│   ├── __init__.py
│   ├── auth/
│   │   ├── __init__.py
│   │   └── proxy.py
│   ├── openapi/
│   │   ├── __init__.py
│   │   ├── convert.py
│   │   └── utils.py
│   ├── server.py
│   ├── transport/
│   │   ├── __init__.py
│   │   ├── http.py
│   │   └── sse.py
│   ├── types.py
│   └── utils/
│       └── __init__.py
├── mypy.ini
├── pyproject.toml
├── pytest.ini
└── tests/
    ├── __init__.py
    ├── conftest.py
    ├── fixtures/
    │   ├── complex_app.py
    │   ├── conftest.py
    │   ├── example_data.py
    │   ├── simple_app.py
    │   └── types.py
    ├── test_basic_functionality.py
    ├── test_configuration.py
    ├── test_http_real_transport.py
    ├── test_mcp_complex_app.py
    ├── test_mcp_execute_api_tool.py
    ├── test_mcp_simple_app.py
    ├── test_openapi_conversion.py
    ├── test_sse_mock_transport.py
    ├── test_sse_real_transport.py
    └── test_types_validation.py
Download .txt
SYMBOL INDEX (191 symbols across 29 files)

FILE: examples/05_reregister_tools_example.py
  function new_endpoint (line 18) | async def new_endpoint():

FILE: examples/08_auth_example_token_passthrough.py
  function private (line 41) | async def private(token=Depends(token_auth_scheme)):

FILE: examples/09_auth_example_auth0.py
  class Settings (line 16) | class Settings(BaseSettings):
    method auth0_jwks_url (line 31) | def auth0_jwks_url(self):
    method auth0_oauth_metadata_url (line 35) | def auth0_oauth_metadata_url(self):
    class Config (line 38) | class Config:
  function lifespan (line 45) | async def lifespan(app: FastAPI):
  function verify_auth (line 53) | async def verify_auth(request: Request) -> dict[str, Any]:
  function get_current_user_id (line 90) | async def get_current_user_id(claims: dict = Depends(verify_auth)) -> str:
  function public (line 104) | async def public():
  function protected (line 109) | async def protected(user_id: str = Depends(get_current_user_id)):

FILE: examples/shared/apps/items.py
  class Item (line 13) | class Item(BaseModel):
  function list_items (line 25) | async def list_items(skip: int = 0, limit: int = 10):
  function read_item (line 35) | async def read_item(item_id: int):
  function create_item (line 47) | async def create_item(item: Item):
  function update_item (line 58) | async def update_item(item_id: int, item: Item):
  function delete_item (line 73) | async def delete_item(item_id: int):
  function search_items (line 87) | async def search_items(

FILE: examples/shared/auth.py
  function fetch_jwks_public_key (line 15) | async def fetch_jwks_public_key(url: str) -> str:

FILE: examples/shared/setup.py
  class LoggingConfig (line 6) | class LoggingConfig(BaseModel):
  function setup_logging (line 34) | def setup_logging():

FILE: fastapi_mcp/auth/proxy.py
  function setup_oauth_custom_metadata (line 22) | def setup_oauth_custom_metadata(
  function setup_oauth_metadata_proxy (line 47) | def setup_oauth_metadata_proxy(
  function setup_oauth_authorize_proxy (line 128) | def setup_oauth_authorize_proxy(
  function setup_oauth_fake_dynamic_register_endpoint (line 230) | def setup_oauth_fake_dynamic_register_endpoint(

FILE: fastapi_mcp/openapi/convert.py
  function convert_openapi_to_mcp_tools (line 17) | def convert_openapi_to_mcp_tools(

FILE: fastapi_mcp/openapi/utils.py
  function get_single_param_type_from_schema (line 4) | def get_single_param_type_from_schema(param_schema: Dict[str, Any]) -> str:
  function resolve_schema_references (line 19) | def resolve_schema_references(schema_part: Dict[str, Any], reference_sch...
  function clean_schema_for_display (line 60) | def clean_schema_for_display(schema: Dict[str, Any]) -> Dict[str, Any]:
  function generate_example_from_schema (line 103) | def generate_example_from_schema(schema: Dict[str, Any]) -> Any:

FILE: fastapi_mcp/server.py
  class FastApiMCP (line 22) | class FastApiMCP:
    method __init__ (line 27) | def __init__(
    method setup_server (line 126) | def setup_server(self) -> None:
    method _register_mcp_connection_endpoint_sse (line 188) | def _register_mcp_connection_endpoint_sse(
    method _register_mcp_messages_endpoint_sse (line 205) | def _register_mcp_messages_endpoint_sse(
    method _register_mcp_endpoints_sse (line 221) | def _register_mcp_endpoints_sse(
    method _register_mcp_http_endpoint (line 231) | def _register_mcp_http_endpoint(
    method _register_mcp_endpoints_http (line 248) | def _register_mcp_endpoints_http(
    method _setup_auth_2025_03_26 (line 257) | def _setup_auth_2025_03_26(self):
    method _setup_auth (line 301) | def _setup_auth(self):
    method mount_http (line 312) | def mount_http(
    method mount_sse (line 368) | def mount_sse(
    method mount (line 426) | def mount(
    method _execute_api_tool (line 484) | async def _execute_api_tool(
    method _request (line 572) | async def _request(
    method _filter_tools (line 594) | def _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[...

FILE: fastapi_mcp/transport/http.py
  class FastApiHttpSessionManager (line 12) | class FastApiHttpSessionManager:
    method __init__ (line 17) | def __init__(
    method _ensure_session_manager_started (line 33) | async def _ensure_session_manager_started(self) -> None:
    method handle_fastapi_request (line 80) | async def handle_fastapi_request(self, request: Request) -> Response:
    method shutdown (line 128) | async def shutdown(self) -> None:

FILE: fastapi_mcp/transport/sse.py
  class FastApiSseTransport (line 17) | class FastApiSseTransport(SseServerTransport):
    method handle_fastapi_post_message (line 18) | async def handle_fastapi_post_message(self, request: Request) -> Respo...
    method _send_message_safely (line 87) | async def _send_message_safely(

FILE: fastapi_mcp/types.py
  class BaseType (line 18) | class BaseType(BaseModel):
  class HTTPRequestInfo (line 22) | class HTTPRequestInfo(BaseType):
  class OAuthMetadata (line 31) | class OAuthMetadata(BaseType):
    method validate_non_empty_lists (line 123) | def validate_non_empty_lists(cls, v, info):
    method validate_endpoints_for_grant_types (line 130) | def validate_endpoints_for_grant_types(self):
    method model_dump (line 135) | def model_dump(
  class AuthConfig (line 172) | class AuthConfig(BaseType):
    method validate_required_fields (line 355) | def validate_required_fields(self):
  class ClientRegistrationRequest (line 369) | class ClientRegistrationRequest(BaseType):
  class ClientRegistrationResponse (line 376) | class ClientRegistrationResponse(BaseType):

FILE: tests/conftest.py
  function pytest_configure (line 16) | def pytest_configure(config):
  function pytest_sessionfinish (line 30) | def pytest_sessionfinish(session, exitstatus):

FILE: tests/fixtures/complex_app.py
  function make_complex_fastapi_app (line 20) | def make_complex_fastapi_app(
  function complex_fastapi_app (line 131) | def complex_fastapi_app(

FILE: tests/fixtures/conftest.py
  function make_fastapi_app_base (line 5) | def make_fastapi_app_base(parametrized_config: dict[str, Any] | None = N...

FILE: tests/fixtures/example_data.py
  function example_address (line 24) | def example_address() -> Address:
  function example_product_variant (line 29) | def example_product_variant() -> ProductVariant:
  function example_product (line 36) | def example_product(example_product_variant) -> Product:
  function example_customer (line 55) | def example_customer(example_address) -> Customer:
  function example_order_item (line 70) | def example_order_item() -> OrderItem:
  function example_payment_details (line 82) | def example_payment_details() -> PaymentDetails:
  function example_order_request (line 94) | def example_order_request(example_order_item) -> OrderRequest:
  function example_order_response (line 107) | def example_order_response(example_order_item, example_address, example_...
  function example_paginated_products (line 130) | def example_paginated_products(example_product) -> PaginatedResponse:

FILE: tests/fixtures/simple_app.py
  function make_simple_fastapi_app (line 11) | def make_simple_fastapi_app(parametrized_config: dict[str, Any] | None =...
  function simple_fastapi_app (line 68) | def simple_fastapi_app() -> FastAPI:
  function simple_fastapi_app_with_root_path (line 73) | def simple_fastapi_app_with_root_path() -> FastAPI:

FILE: tests/fixtures/types.py
  class Item (line 9) | class Item(BaseModel):
  class OrderStatus (line 17) | class OrderStatus(str, Enum):
  class PaymentMethod (line 26) | class PaymentMethod(str, Enum):
  class ProductCategory (line 34) | class ProductCategory(str, Enum):
  class ProductVariant (line 42) | class ProductVariant(BaseModel):
  class Address (line 52) | class Address(BaseModel):
  class CustomerTier (line 61) | class CustomerTier(str, Enum):
  class Customer (line 67) | class Customer(BaseModel):
  class Product (line 81) | class Product(BaseModel):
  class OrderItem (line 100) | class OrderItem(BaseModel):
  class PaymentDetails (line 109) | class PaymentDetails(BaseModel):
  class OrderRequest (line 118) | class OrderRequest(BaseModel):
  class OrderResponse (line 128) | class OrderResponse(BaseModel):
  class PaginatedResponse (line 149) | class PaginatedResponse(BaseModel):
  class ErrorResponse (line 157) | class ErrorResponse(BaseModel):

FILE: tests/test_basic_functionality.py
  function test_create_mcp_server (line 7) | def test_create_mcp_server(simple_fastapi_app: FastAPI):
  function test_default_values (line 28) | def test_default_values(simple_fastapi_app: FastAPI):
  function test_normalize_paths (line 45) | def test_normalize_paths(simple_fastapi_app: FastAPI):

FILE: tests/test_configuration.py
  function test_default_configuration (line 7) | def test_default_configuration(simple_fastapi_app: FastAPI):
  function test_custom_configuration (line 21) | def test_custom_configuration(simple_fastapi_app: FastAPI):
  function test_describe_all_responses_config_simple_app (line 44) | def test_describe_all_responses_config_simple_app(simple_fastapi_app: Fa...
  function test_describe_full_response_schema_config_simple_app (line 106) | def test_describe_full_response_schema_config_simple_app(simple_fastapi_...
  function test_describe_all_responses_and_full_response_schema_config_simple_app (line 139) | def test_describe_all_responses_and_full_response_schema_config_simple_a...
  function test_describe_all_responses_config_complex_app (line 177) | def test_describe_all_responses_config_complex_app(complex_fastapi_app: ...
  function test_describe_full_response_schema_config_complex_app (line 248) | def test_describe_full_response_schema_config_complex_app(complex_fastap...
  function test_describe_all_responses_and_full_response_schema_config_complex_app (line 292) | def test_describe_all_responses_and_full_response_schema_config_complex_...
  function test_filtering_functionality (line 346) | def test_filtering_functionality():
  function test_filtering_edge_cases (line 408) | def test_filtering_edge_cases():
  function test_filtering_with_missing_operation_ids (line 482) | def test_filtering_with_missing_operation_ids():
  function test_filter_with_empty_tools (line 529) | def test_filter_with_empty_tools():
  function test_filtering_with_empty_tags_array (line 556) | def test_filtering_with_empty_tags_array():

FILE: tests/test_http_real_transport.py
  function run_server (line 23) | def run_server(server_port: int, fastapi_app: FastAPI) -> None:
  function server (line 80) | def server(request: pytest.FixtureRequest) -> Generator[str, None, None]:
  function http_client (line 134) | async def http_client(server: str) -> AsyncGenerator[httpx.AsyncClient, ...
  function test_http_initialize_request (line 140) | async def test_http_initialize_request(http_client: httpx.AsyncClient, s...
  function test_http_list_tools (line 173) | async def test_http_list_tools(http_client: httpx.AsyncClient, server: s...
  function test_http_call_tool (line 240) | async def test_http_call_tool(http_client: httpx.AsyncClient, server: st...
  function test_http_ping (line 312) | async def test_http_ping(http_client: httpx.AsyncClient, server: str) ->...
  function test_http_error_handling (line 372) | async def test_http_error_handling(http_client: httpx.AsyncClient, serve...
  function test_http_invalid_method (line 389) | async def test_http_invalid_method(http_client: httpx.AsyncClient, serve...
  function test_http_notification_handling (line 437) | async def test_http_notification_handling(http_client: httpx.AsyncClient...

FILE: tests/test_mcp_complex_app.py
  function fastapi_mcp (line 15) | def fastapi_mcp(complex_fastapi_app: FastAPI) -> FastApiMCP:
  function lowlevel_server_complex_app (line 26) | def lowlevel_server_complex_app(fastapi_mcp: FastApiMCP) -> Server:
  function test_list_tools (line 31) | async def test_list_tools(lowlevel_server_complex_app: Server):
  function test_call_tool_list_products_default (line 44) | async def test_call_tool_list_products_default(lowlevel_server_complex_a...
  function test_call_tool_list_products_with_filters (line 61) | async def test_call_tool_list_products_with_filters(lowlevel_server_comp...
  function test_call_tool_get_product (line 80) | async def test_call_tool_get_product(lowlevel_server_complex_app: Server...
  function test_call_tool_get_product_with_options (line 99) | async def test_call_tool_get_product_with_options(lowlevel_server_comple...
  function test_call_tool_create_order (line 117) | async def test_call_tool_create_order(lowlevel_server_complex_app: Serve...
  function test_call_tool_create_order_validation_error (line 146) | async def test_call_tool_create_order_validation_error(lowlevel_server_c...
  function test_call_tool_get_customer (line 166) | async def test_call_tool_get_customer(lowlevel_server_complex_app: Serve...
  function test_call_tool_get_customer_with_options (line 184) | async def test_call_tool_get_customer_with_options(lowlevel_server_compl...
  function test_error_handling_missing_parameter (line 208) | async def test_error_handling_missing_parameter(lowlevel_server_complex_...

FILE: tests/test_mcp_execute_api_tool.py
  function test_execute_api_tool_success (line 10) | async def test_execute_api_tool_success(simple_fastapi_app: FastAPI):
  function test_execute_api_tool_with_query_params (line 51) | async def test_execute_api_tool_with_query_params(simple_fastapi_app: Fa...
  function test_execute_api_tool_with_body (line 91) | async def test_execute_api_tool_with_body(simple_fastapi_app: FastAPI):
  function test_execute_api_tool_with_non_ascii_chars (line 140) | async def test_execute_api_tool_with_non_ascii_chars(simple_fastapi_app:...

FILE: tests/test_mcp_simple_app.py
  function fastapi_mcp (line 15) | def fastapi_mcp(simple_fastapi_app: FastAPI) -> FastApiMCP:
  function fastapi_mcp_with_custom_header (line 26) | def fastapi_mcp_with_custom_header(simple_fastapi_app: FastAPI) -> FastA...
  function lowlevel_server_simple_app (line 38) | def lowlevel_server_simple_app(fastapi_mcp: FastApiMCP) -> Server:
  function test_list_tools (line 43) | async def test_list_tools(lowlevel_server_simple_app: Server):
  function test_call_tool_get_item_1 (line 57) | async def test_call_tool_get_item_1(lowlevel_server_simple_app: Server):
  function test_call_tool_get_item_2 (line 75) | async def test_call_tool_get_item_2(lowlevel_server_simple_app: Server):
  function test_call_tool_raise_error (line 93) | async def test_call_tool_raise_error(lowlevel_server_simple_app: Server):
  function test_error_handling (line 106) | async def test_error_handling(lowlevel_server_simple_app: Server):
  function test_complex_tool_arguments (line 119) | async def test_complex_tool_arguments(lowlevel_server_simple_app: Server):
  function test_call_tool_list_items_default (line 144) | async def test_call_tool_list_items_default(lowlevel_server_simple_app: ...
  function test_call_tool_list_items_with_pagination (line 162) | async def test_call_tool_list_items_with_pagination(lowlevel_server_simp...
  function test_call_tool_get_item_not_found (line 180) | async def test_call_tool_get_item_not_found(lowlevel_server_simple_app: ...
  function test_call_tool_update_item (line 193) | async def test_call_tool_update_item(lowlevel_server_simple_app: Server):
  function test_call_tool_delete_item (line 220) | async def test_call_tool_delete_item(lowlevel_server_simple_app: Server):
  function test_call_tool_get_item_with_details (line 233) | async def test_call_tool_get_item_with_details(lowlevel_server_simple_ap...
  function test_headers_passthrough_to_tool_handler (line 252) | async def test_headers_passthrough_to_tool_handler(fastapi_mcp: FastApiM...
  function test_custom_header_passthrough_to_tool_handler (line 331) | async def test_custom_header_passthrough_to_tool_handler(fastapi_mcp_wit...
  function test_context_extraction_in_tool_handler (line 374) | async def test_context_extraction_in_tool_handler(fastapi_mcp: FastApiMCP):

FILE: tests/test_openapi_conversion.py
  function test_simple_app_conversion (line 13) | def test_simple_app_conversion(simple_fastapi_app: FastAPI):
  function test_complex_app_conversion (line 38) | def test_complex_app_conversion(complex_fastapi_app: FastAPI):
  function test_describe_full_response_schema (line 63) | def test_describe_full_response_schema(simple_fastapi_app: FastAPI):
  function test_describe_all_responses (line 94) | def test_describe_all_responses(complex_fastapi_app: FastAPI):
  function test_schema_utils (line 123) | def test_schema_utils():
  function test_parameter_handling (line 161) | def test_parameter_handling(complex_fastapi_app: FastAPI):
  function test_request_body_handling (line 233) | def test_request_body_handling(complex_fastapi_app: FastAPI):
  function test_missing_type_handling (line 305) | def test_missing_type_handling(complex_fastapi_app: FastAPI):
  function test_body_params_descriptions_and_defaults (line 330) | def test_body_params_descriptions_and_defaults(complex_fastapi_app: Fast...
  function test_body_params_edge_cases (line 380) | def test_body_params_edge_cases(complex_fastapi_app: FastAPI):

FILE: tests/test_sse_mock_transport.py
  function mock_transport (line 15) | def mock_transport() -> FastApiSseTransport:
  function valid_session_id (line 23) | def valid_session_id():
  function mock_writer (line 29) | def mock_writer():
  function test_handle_post_message_missing_session_id (line 34) | async def test_handle_post_message_missing_session_id(mock_transport: Fa...
  function test_handle_post_message_invalid_session_id (line 49) | async def test_handle_post_message_invalid_session_id(mock_transport: Fa...
  function test_handle_post_message_session_not_found (line 64) | async def test_handle_post_message_session_not_found(
  function test_handle_post_message_validation_error (line 81) | async def test_handle_post_message_validation_error(
  function test_handle_post_message_general_exception (line 108) | async def test_handle_post_message_general_exception(
  function test_send_message_safely_with_validation_error (line 135) | async def test_send_message_safely_with_validation_error(
  function test_send_message_safely_with_jsonrpc_message (line 156) | async def test_send_message_safely_with_jsonrpc_message(
  function test_send_message_safely_exception_handling (line 175) | async def test_send_message_safely_exception_handling(

FILE: tests/test_sse_real_transport.py
  function run_server (line 27) | def run_server(server_port: int, fastapi_app: FastAPI) -> None:
  function server (line 84) | def server(request: pytest.FixtureRequest) -> Generator[str, None, None]:
  function http_client (line 138) | async def http_client(server: str) -> AsyncGenerator[httpx.AsyncClient, ...
  function test_raw_sse_connection (line 144) | async def test_raw_sse_connection(http_client: httpx.AsyncClient, server...
  function test_sse_basic_connection (line 175) | async def test_sse_basic_connection(server: str) -> None:
  function test_sse_tool_call (line 189) | async def test_sse_tool_call(server: str) -> None:

FILE: tests/test_types_validation.py
  class TestOAuthMetadata (line 11) | class TestOAuthMetadata:
    method test_non_empty_lists_validation (line 12) | def test_non_empty_lists_validation(self):
    method test_authorization_endpoint_required_for_authorization_code (line 28) | def test_authorization_endpoint_required_for_authorization_code(self):
    method test_model_dump_excludes_none (line 46) | def test_model_dump_excludes_none(self):
  class TestAuthConfig (line 58) | class TestAuthConfig:
    method test_required_fields_validation (line 59) | def test_required_fields_validation(self):
    method test_client_id_required_for_setup_proxies (line 80) | def test_client_id_required_for_setup_proxies(self):
    method test_client_secret_required_for_fake_registration (line 94) | def test_client_secret_required_for_fake_registration(self):
Condensed preview — 80 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (306K chars).
[
  {
    "path": ".coveragerc",
    "chars": 208,
    "preview": "[run]\nomit =\n    examples/*\n    tests/*\nconcurrency = multiprocessing\nparallel = true\nsigterm = true\ndata_file = .covera"
  },
  {
    "path": ".cursorignore",
    "chars": 56,
    "preview": "# Repomix output\n!repomix-output.txt\n!repomix-output.xml"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 341,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG]\"\nlabels: bug\nassignees: ''\n\n---\n\n**Describe"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/documentation.md",
    "chars": 150,
    "preview": "---\nname: Documentation\nabout: Report an issue related to the fastapi-mcp documentation/examples\ntitle: ''\nlabels: docum"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 604,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is"
  },
  {
    "path": ".github/codecov.yml",
    "chars": 164,
    "preview": "coverage:\n  status:\n    project:\n      default:\n        base: pr\n        target: auto\n        threshold: 0.5%\n        in"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 383,
    "preview": "version: 2\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n  "
  },
  {
    "path": ".github/pull_request_template.md",
    "chars": 225,
    "preview": "## Describe your changes\n\n## Issue ticket number and link (if applicable)\n\n## Screenshots of the feature / bugfix\n\n## Ch"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 1971,
    "preview": "name: CI\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  ruff:\n    name: Ruff\n    runs-o"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 832,
    "preview": "name: Release\n\non:\n  release:\n    types: [created]\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: "
  },
  {
    "path": ".gitignore",
    "chars": 2006,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": ".pre-commit-config.yaml",
    "chars": 358,
    "preview": "repos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v5.0.0\n    hooks:\n      - id: trailing-whitespa"
  },
  {
    "path": ".python-version",
    "chars": 4,
    "preview": "3.12"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 6419,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 4041,
    "preview": "# Contributing to FastAPI-MCP\n\nFirst off, thank you for considering contributing to FastAPI-MCP!\n\n## Development Setup\n\n"
  },
  {
    "path": "LICENSE",
    "chars": 1068,
    "preview": "MIT License\n\nCopyright (c) 2024 Tadata Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
  },
  {
    "path": "MANIFEST.in",
    "chars": 221,
    "preview": "include LICENSE\ninclude README.md\ninclude INSTALL.md\ninclude pyproject.toml\ninclude setup.py\n\nrecursive-include examples"
  },
  {
    "path": "README.md",
    "chars": 4572,
    "preview": "<p align=\"center\"><a href=\"https://github.com/tadata-org/fastapi_mcp\"><img src=\"https://github.com/user-attachments/asse"
  },
  {
    "path": "README_zh-CN.md",
    "chars": 6531,
    "preview": "<p align=\"center\"><a href=\"https://github.com/tadata-org/fastapi_mcp\"><img src=\"https://github.com/user-attachments/asse"
  },
  {
    "path": "docs/advanced/asgi.mdx",
    "chars": 754,
    "preview": "---\ntitle: Transport\ndescription: How to communicate with the FastAPI app\nicon: microchip\n---\n\nFastAPI-MCP uses ASGI tra"
  },
  {
    "path": "docs/advanced/auth.mdx",
    "chars": 7954,
    "preview": "---\ntitle: Authentication & Authorization\nicon: key\n---\n\nFastAPI-MCP supports authentication and authorization using you"
  },
  {
    "path": "docs/advanced/deploy.mdx",
    "chars": 785,
    "preview": "---\ntitle: Deploying the Server\nicon: play\n---\n\n## Deploying separately from original FastAPI app\n\nYou are not limited t"
  },
  {
    "path": "docs/advanced/refresh.mdx",
    "chars": 624,
    "preview": "---\ntitle: Refreshing the Server\ndescription: Adding endpoints after MCP server creation\nicon: arrows-rotate\n---\n\nIf you"
  },
  {
    "path": "docs/advanced/transport.mdx",
    "chars": 2069,
    "preview": "---\ntitle: MCP Transport\ndescription: Understanding MCP transport methods and how to choose between them\nicon: car\n---\n\n"
  },
  {
    "path": "docs/configurations/customization.mdx",
    "chars": 3076,
    "preview": "---\ntitle: Customization\nicon: pen\n---\n\n## Server metadata\n\nYou can define the MCP server name and description by modify"
  },
  {
    "path": "docs/configurations/tool-naming.mdx",
    "chars": 956,
    "preview": "---\ntitle: Tool Naming\nicon: input-text    \n---\n\nFastAPI-MCP uses the `operation_id` from your FastAPI routes as the MCP"
  },
  {
    "path": "docs/docs.json",
    "chars": 2051,
    "preview": "{\n  \"$schema\": \"https://mintlify.com/docs.json\",\n  \"name\": \"FastAPI MCP\",\n  \"background\": {\n    \"color\": {\n      \"dark\":"
  },
  {
    "path": "docs/getting-started/FAQ.mdx",
    "chars": 2822,
    "preview": "---\ntitle: FAQ\ndescription: Frequently Asked Questions\nicon: question\n---\n\n## Usage\n### How do I configure HTTP request "
  },
  {
    "path": "docs/getting-started/best-practices.mdx",
    "chars": 1935,
    "preview": "---\ntitle: Best Practices\nicon: thumbs-up\n---\n\nThis guide outlines best practices for converting standard APIs into Mode"
  },
  {
    "path": "docs/getting-started/installation.mdx",
    "chars": 385,
    "preview": "---\ntitle: Installation\nicon: arrow-down-to-line\n---\n\n## Install FastAPI-MCP\n\nWe recommend using [uv](https://docs.astra"
  },
  {
    "path": "docs/getting-started/quickstart.mdx",
    "chars": 2318,
    "preview": "---\ntitle: Quickstart\nicon: rocket\n---\n\nThis guide will help you quickly run your first MCP server using FastAPI-MCP.\n\nI"
  },
  {
    "path": "docs/getting-started/welcome.mdx",
    "chars": 1351,
    "preview": "---\ntitle: \"Welcome to FastAPI-MCP!\"\nsidebarTitle: \"Welcome!\"\ndescription: Expose your FastAPI endpoints as Model Contex"
  },
  {
    "path": "examples/01_basic_usage_example.py",
    "chars": 379,
    "preview": "from examples.shared.apps.items import app  # The FastAPI app\nfrom examples.shared.setup import setup_logging\n\nfrom fast"
  },
  {
    "path": "examples/02_full_schema_description_example.py",
    "chars": 752,
    "preview": "\"\"\"\nThis example shows how to describe the full response schema instead of just a response example.\n\"\"\"\n\nfrom examples.s"
  },
  {
    "path": "examples/03_custom_exposed_endpoints_example.py",
    "chars": 2617,
    "preview": "\"\"\"\nThis example shows how to customize exposing endpoints by filtering operation IDs and tags.\nNotes on filtering:\n- Yo"
  },
  {
    "path": "examples/04_separate_server_example.py",
    "chars": 879,
    "preview": "\"\"\"\nThis example shows how to run the MCP server and the FastAPI app separately.\nYou can create an MCP server from one F"
  },
  {
    "path": "examples/05_reregister_tools_example.py",
    "chars": 809,
    "preview": "\"\"\"\nThis example shows how to re-register tools if you add endpoints after the MCP server was created.\n\"\"\"\n\nfrom example"
  },
  {
    "path": "examples/06_custom_mcp_router_example.py",
    "chars": 633,
    "preview": "\"\"\"\nThis example shows how to mount the MCP server to a specific APIRouter, giving a custom mount path.\n\"\"\"\n\nfrom exampl"
  },
  {
    "path": "examples/07_configure_http_timeout_example.py",
    "chars": 552,
    "preview": "\"\"\"\nThis example shows how to configure the HTTP client timeout for the MCP server.\nIn case you have API endpoints that "
  },
  {
    "path": "examples/08_auth_example_token_passthrough.py",
    "chars": 1289,
    "preview": "\"\"\"\nThis example shows how to reject any request without a valid token passed in the Authorization header.\n\nIn order to "
  },
  {
    "path": "examples/09_auth_example_auth0.py",
    "chars": 4308,
    "preview": "from fastapi import FastAPI, Depends, HTTPException, Request, status\nfrom pydantic_settings import BaseSettings\nfrom typ"
  },
  {
    "path": "examples/README.md",
    "chars": 781,
    "preview": "# FastAPI-MCP Examples\n\nThe following examples demonstrate various features and usage patterns of FastAPI-MCP:\n\n1. [Basi"
  },
  {
    "path": "examples/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "examples/shared/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "examples/shared/apps/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "examples/shared/apps/items.py",
    "chars": 3875,
    "preview": "\"\"\"\nSimple example of using FastAPI-MCP to add an MCP server to a FastAPI app.\n\"\"\"\n\nfrom fastapi import FastAPI, HTTPExc"
  },
  {
    "path": "examples/shared/auth.py",
    "chars": 1727,
    "preview": "from jwt.algorithms import RSAAlgorithm\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazma"
  },
  {
    "path": "examples/shared/setup.py",
    "chars": 1076,
    "preview": "import logging\n\nfrom pydantic import BaseModel\n\n\nclass LoggingConfig(BaseModel):\n    LOGGER_NAME: str = \"fastapi_mcp\"\n  "
  },
  {
    "path": "fastapi_mcp/__init__.py",
    "chars": 501,
    "preview": "\"\"\"\nFastAPI-MCP: Automatic MCP server generator for FastAPI applications.\n\nCreated by Tadata Inc. (https://github.com/ta"
  },
  {
    "path": "fastapi_mcp/auth/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "fastapi_mcp/auth/proxy.py",
    "chars": 9523,
    "preview": "from typing_extensions import Annotated, Doc\nfrom fastapi import FastAPI, HTTPException, Request, status\nfrom fastapi.re"
  },
  {
    "path": "fastapi_mcp/openapi/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "fastapi_mcp/openapi/convert.py",
    "chars": 12376,
    "preview": "import json\nimport logging\nfrom typing import Any, Dict, List, Tuple\n\nimport mcp.types as types\n\nfrom .utils import (\n  "
  },
  {
    "path": "fastapi_mcp/openapi/utils.py",
    "chars": 5451,
    "preview": "from typing import Any, Dict\n\n\ndef get_single_param_type_from_schema(param_schema: Dict[str, Any]) -> str:\n    \"\"\"\n    G"
  },
  {
    "path": "fastapi_mcp/server.py",
    "chars": 26501,
    "preview": "import json\nimport httpx\nfrom typing import Dict, Optional, Any, List, Union, Literal, Sequence\nfrom typing_extensions i"
  },
  {
    "path": "fastapi_mcp/transport/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "fastapi_mcp/transport/http.py",
    "chars": 5311,
    "preview": "import logging\nimport asyncio\n\nfrom fastapi import Request, Response, HTTPException\nfrom mcp.server.lowlevel.server impo"
  },
  {
    "path": "fastapi_mcp/transport/sse.py",
    "chars": 5056,
    "preview": "from uuid import UUID\nimport logging\nfrom typing import Union\n\nfrom anyio.streams.memory import MemoryObjectSendStream\nf"
  },
  {
    "path": "fastapi_mcp/types.py",
    "chars": 11698,
    "preview": "import time\nfrom typing import Any, Dict, Annotated, Union, Optional, Sequence, Literal, List\nfrom typing_extensions imp"
  },
  {
    "path": "fastapi_mcp/utils/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "mypy.ini",
    "chars": 7,
    "preview": "[mypy]\n"
  },
  {
    "path": "pyproject.toml",
    "chars": 2145,
    "preview": "[build-system]\nrequires = [\"hatchling\", \"tomli\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"fastapi-mcp\"\nversi"
  },
  {
    "path": "pytest.ini",
    "chars": 247,
    "preview": "[pytest]\naddopts = -vvv --cov=. --cov-report xml --cov-report term-missing --cov-fail-under=80 --cov-config=.coveragerc\n"
  },
  {
    "path": "tests/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tests/conftest.py",
    "chars": 1491,
    "preview": "import sys\nimport os\nimport pytest\nimport coverage\n\n# Add the parent directory to the path\nsys.path.insert(0, os.path.ab"
  },
  {
    "path": "tests/fixtures/complex_app.py",
    "chars": 5463,
    "preview": "from typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\n\nfrom fastapi import FastAPI, Query, Path, Bod"
  },
  {
    "path": "tests/fixtures/conftest.py",
    "chars": 418,
    "preview": "from typing import Any\nfrom fastapi import FastAPI\n\n\ndef make_fastapi_app_base(parametrized_config: dict[str, Any] | Non"
  },
  {
    "path": "tests/fixtures/example_data.py",
    "chars": 3747,
    "preview": "from datetime import datetime, date\nfrom uuid import UUID\n\nimport pytest\n\nfrom .types import (\n    Address,\n    ProductV"
  },
  {
    "path": "tests/fixtures/simple_app.py",
    "chars": 3109,
    "preview": "from typing import Optional, List, Any\n\nfrom fastapi import FastAPI, Query, Path, Body, HTTPException\nimport pytest\n\nfro"
  },
  {
    "path": "tests/fixtures/types.py",
    "chars": 4106,
    "preview": "from typing import Optional, List, Dict, Any\nfrom datetime import datetime, date\nfrom enum import Enum\nfrom uuid import "
  },
  {
    "path": "tests/test_basic_functionality.py",
    "chars": 2527,
    "preview": "from fastapi import FastAPI\nfrom mcp.server.lowlevel.server import Server\n\nfrom fastapi_mcp import FastApiMCP\n\n\ndef test"
  },
  {
    "path": "tests/test_configuration.py",
    "chars": 28617,
    "preview": "from fastapi import FastAPI\nimport pytest\n\nfrom fastapi_mcp import FastApiMCP\n\n\ndef test_default_configuration(simple_fa"
  },
  {
    "path": "tests/test_http_real_transport.py",
    "chars": 14898,
    "preview": "import multiprocessing\nimport socket\nimport time\nimport os\nimport signal\nimport atexit\nimport sys\nimport threading\nimpor"
  },
  {
    "path": "tests/test_mcp_complex_app.py",
    "chars": 8333,
    "preview": "import json\n\nimport pytest\nimport mcp.types as types\nfrom mcp.server.lowlevel import Server\nfrom mcp.shared.memory impor"
  },
  {
    "path": "tests/test_mcp_execute_api_tool.py",
    "chars": 6034,
    "preview": "import pytest\nfrom unittest.mock import AsyncMock, patch, MagicMock\nfrom fastapi import FastAPI\n\nfrom fastapi_mcp import"
  },
  {
    "path": "tests/test_mcp_simple_app.py",
    "chars": 17663,
    "preview": "import json\n\nimport pytest\nimport mcp.types as types\nfrom mcp.server.lowlevel import Server\nfrom mcp.shared.memory impor"
  },
  {
    "path": "tests/test_openapi_conversion.py",
    "chars": 17092,
    "preview": "from fastapi import FastAPI\nfrom fastapi.openapi.utils import get_openapi\nimport mcp.types as types\n\nfrom fastapi_mcp.op"
  },
  {
    "path": "tests/test_sse_mock_transport.py",
    "chars": 7654,
    "preview": "import pytest\nimport uuid\nfrom uuid import UUID\nfrom unittest.mock import AsyncMock, MagicMock, patch\nfrom fastapi impor"
  },
  {
    "path": "tests/test_sse_real_transport.py",
    "chars": 6456,
    "preview": "import anyio\nimport multiprocessing\nimport socket\nimport time\nimport os\nimport signal\nimport atexit\nimport sys\nimport th"
  },
  {
    "path": "tests/test_types_validation.py",
    "chars": 3760,
    "preview": "import pytest\nfrom pydantic import ValidationError\nfrom fastapi import Depends\n\nfrom fastapi_mcp.types import (\n    OAut"
  }
]

About this extraction

This page contains the full source code of the tadata-org/fastapi_mcp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 80 files (280.4 KB), approximately 66.7k tokens, and a symbol index with 191 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!