---
title: 'Integrate FastMCP with FastAPI Applications'
date: '2026-03-01T07:40:50+07:00'
description: 'Discover how to effortlessly generate Model Context Protocol (MCP) servers from existing FastAPI applications or mount MCP endpoints within them using FastMCP.'
author: 'AI Assistant'
image: '/images/post/integrate-fastmcp-fastapi-applications.jpg'
alt: 'An abstract representation of integration, showing high-speed data flow between two interconnected API nodes representing FastMCP and FastAPI.'
tags: ['fastapi', 'fastmcp', 'mcp', 'python', 'api-integration', 'llm', 'ai-agent']
---

If you are building Python backend services, there's a good chance you are using **FastAPI**. With the rise of AI agents, making these APIs accessible to Large Language Models (LLMs) via the **Model Context Protocol (MCP)** has become crucial.

**FastMCP** offers two highly effective methods for integrating with FastAPI: **generating** an MCP server directly from your existing FastAPI app, or **mounting** an MCP server as a sub-application within FastAPI.

## Method 1: Generating an MCP Server from FastAPI

If you have an existing FastAPI application and want to expose its endpoints to an LLM, FastMCP can automatically convert those endpoints into MCP tools.

### Basic Conversion
Using the `FastMCP.from_fastapi()` method, every route in your FastAPI app becomes an accessible tool for your AI agents.

```python
from fastapi import FastAPI
from fastmcp import FastMCP

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"id": user_id, "name": "Alice"}

# Convert the entire FastAPI app into an MCP server
mcp = FastMCP.from_fastapi(app, name="User API MCP Server")

if __name__ == "__main__":
    mcp.run()
```

### Advanced Mapping and Authentication
Just like the OpenAPI integration, you can use `RouteMap` to precisely control which endpoints become Tools, Resources, or Resource Templates.

Additionally, if your FastAPI endpoints are protected, you can pass security headers via `httpx_client_kwargs` to ensure the generated MCP server can successfully communicate with them.

```python
mcp = FastMCP.from_fastapi(
    app,
    httpx_client_kwargs={"headers": {"Authorization": "Bearer YOUR_SECRET"}},
)
```

## Method 2: Mounting an MCP Server into FastAPI

Instead of generating an MCP server *from* FastAPI, you might want to serve a custom MCP server *alongside* your regular REST endpoints. This is done by mounting the MCP server as an ASGI sub-application.

### Implementation Steps

1.  **Create your FastMCP server** with your custom tools and resources.
2.  **Generate the ASGI app** using `mcp.http_app(path='/mcp')`.
3.  **Mount it** into your main FastAPI application using `app.mount()`.

### Crucial: Managing Lifespans

A critical detail when mounting MCP inside FastAPI is **lifespan management**. You *must* pass the MCP app's lifespan to the main FastAPI app so that resources are properly initialized and cleaned up.

```python
from fastapi import FastAPI
from fastmcp import FastMCP

# 1. Define your MCP server
mcp = FastMCP("My Embedded MCP Server")

@mcp.tool()
def hello_mcp() -> str:
    return "Hello from the mounted MCP Server!"

# 2. Get the ASGI app
mcp_app = mcp.http_app(path="/mcp")

# 3. CRITICAL: Pass the MCP lifespan to FastAPI
app = FastAPI(lifespan=mcp_app.lifespan)

# 4. Mount the MCP app
app.mount("/mcp", mcp_app)
```

If your FastAPI application already has its own lifespan manager (e.g., for database connections), you can merge them using the `combine_lifespans` utility.

## Key Considerations

- **Operation IDs:** FastAPI's `operation_id` values become the MCP tool names. Always explicitly name your FastAPI endpoints to ensure LLMs get clear, understandable tool names.
- **CORS Configuration:** If you are using OAuth-protected MCP servers, avoid setting a top-level `CORSMiddleware` in FastAPI, as FastMCP manages its own necessary CORS logic.

## Conclusion

Whether you are exposing an existing REST API to agents or building a hybrid application that serves both humans and LLMs, FastMCP's FastAPI integration makes the process seamless, robust, and incredibly fast to implement.
