Skip to content

Fast API Auto MCP — native MCP server support via mcp_url#1

Open
swe-brain[bot] wants to merge 1 commit intomasterfrom
claude/swe-brain/fast-api-auto-mcp
Open

Fast API Auto MCP — native MCP server support via mcp_url#1
swe-brain[bot] wants to merge 1 commit intomasterfrom
claude/swe-brain/fast-api-auto-mcp

Conversation

@swe-brain
Copy link
Copy Markdown

@swe-brain swe-brain Bot commented Apr 20, 2026

Summary

Adds first-class MCP (Model Context Protocol) support to FastAPI. Enable with a single parameter: app = FastAPI(mcp_url="/mcp"). FastAPI automatically generates an MCP server at that path exposing all schema-included routes as callable tools, executed in-process with zero network overhead.

Trying It on an Existing FastAPI App

1. Install FastAPI from this fork + the MCP dependency

pip install "git+https://github.com/ArcInstitute/fastapi.git@claude/swe-brain/fast-api-auto-mcp" "mcp>=1.9"

This installs FastAPI from the feature branch (which has mcp_url support) alongside the MCP SDK. The mcp_url parameter doesn't exist in the PyPI release yet.

2. Add mcp_url to your app

# Before
app = FastAPI()

# After — one line change
app = FastAPI(mcp_url="/mcp")

3. Run your app normally

uvicorn myapp:app --reload

4. Connect Claude Desktop

Add this to your claude_desktop_config.json (usually at ~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": ["mcp-remote", "http://localhost:8000/mcp/"]
    }
  }
}

Restart Claude Desktop. Your API routes will appear as tools Claude can call directly.

5. Quick smoke-test (no Claude Desktop needed)

import httpx

with httpx.Client(base_url="http://localhost:8000", follow_redirects=True) as client:
    resp = client.post(
        "/mcp/",
        json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}},
        headers={"Content-Type": "application/json", "Accept": "application/json, text/event-stream"},
    )
    print(resp.json())

Note: The MCP endpoint is at /mcp/ (trailing slash). Real MCP clients follow the 307 redirect automatically; when using httpx directly pass follow_redirects=True or hit /mcp/ directly.


Implementation Plan

Files Created

fastapi/mcp/__init__.py — public exports (MCPApp)

fastapi/mcp/generator.py — converts APIRoute objects to MCP Tool definitions:

  • Iterates routes with include_in_schema=True
  • Tool name: route.unique_id (e.g. read_item_items__item_id__get)
  • Tool description: summary or description or "METHOD /path"
  • Input schema: path params + query params as top-level fields; request body as body field
  • Reuses already-generated app.openapi() schema — no re-computation

fastapi/mcp/server.py — stateless MCPApp ASGI app:

  • Per request: creates a StreamableHTTPServerTransport with is_json_response_enabled=True
  • Runs MCP server alongside transport in an anyio task group (stateless mode)
  • Tool calls execute via httpx.AsyncClient(transport=ASGITransport(app=fastapi_app)) — in-process, zero network overhead, passes through all FastAPI middleware
  • Handles path params (substituted into URL template), query params, and JSON body

Files Modified

fastapi/applications.py — added mcp_url: str | None = None parameter with full annotated_doc docstring; stores as self.mcp_url; mounts MCPApp in setup() when set; raises helpful ImportError if mcp package not installed

pyproject.toml — added [project.optional-dependencies] mcp = ["mcp>=1.9"]

Tests

tests/test_mcp.py — 7 tests × 2 backends (asyncio + trio) = 14 total, all passing:

  1. test_mcp_disabled_by_defaultFastAPI() without mcp_url → 404 at /mcp
  2. test_mcp_custom_urlFastAPI(mcp_url="/api/mcp") mounts at custom path
  3. test_mcp_tools_list — tools/list returns all schema-included routes
  4. test_include_in_schema_false_excludedinclude_in_schema=False routes excluded
  5. test_mcp_tool_call_get — GET endpoint callable via MCP tools/call
  6. test_mcp_tool_call_post_with_body — POST with Pydantic body callable via MCP
  7. test_mcp_path_params — path parameters correctly substituted

Test Plan

  • All 14 tests pass (pytest tests/test_mcp.py -v)
  • No regressions in existing test suite
  • MCP disabled by default — no breaking changes to existing apps
  • Import error raised with helpful message when mcp not installed

Implemented by swe-brain · Planning issue: https://github.com/ArcInstitute/swe-brain/issues/7

Adds first-class MCP (Model Context Protocol) support to FastAPI.
When mcp_url is set, an MCP server is automatically mounted that
exposes all schema-included routes as callable MCP tools.

- fastapi/mcp/generator.py: converts APIRoute objects to MCP Tool definitions
- fastapi/mcp/server.py: stateless ASGI MCPApp using StreamableHTTP transport
- fastapi/applications.py: mcp_url parameter added to FastAPI.__init__ + setup()
- pyproject.toml: optional [mcp] dependency group added (mcp>=1.9)
- tests/test_mcp.py: 7 integration tests covering all plan requirements
@swe-brain
Copy link
Copy Markdown
Author

swe-brain Bot commented Apr 27, 2026

Gentle reminder: this PR has been open for 6 days awaiting review. @sullivanj91

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant