fastapi-fastmcp 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/PKG-INFO +425 -421
  2. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/README.md +389 -385
  3. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/PKG-INFO +425 -421
  4. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/SOURCES.txt +1 -0
  5. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/__init__.py +13 -13
  6. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/__main__.py +6 -6
  7. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/core.py +163 -9
  8. fastapi_fastmcp-0.2.0/fastapi_mcp/templates.py +724 -0
  9. fastapi_fastmcp-0.2.0/fastapi_mcp/ui.py +601 -0
  10. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/pyproject.toml +1 -2
  11. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/setup.cfg +4 -4
  12. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_auto_scan.py +105 -105
  13. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_coexistence.py +56 -56
  14. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_coverage_complete.py +13 -1
  15. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_hybrid.py +73 -73
  16. fastapi_fastmcp-0.2.0/tests/test_ui.py +402 -0
  17. fastapi_fastmcp-0.1.2/fastapi_mcp/ui.py +0 -764
  18. fastapi_fastmcp-0.1.2/tests/test_ui.py +0 -181
  19. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/LICENSE +0 -0
  20. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/dependency_links.txt +0 -0
  21. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/entry_points.txt +0 -0
  22. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/requires.txt +0 -0
  23. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_fastmcp.egg-info/top_level.txt +0 -0
  24. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/cli.py +0 -0
  25. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/dispatcher.py +0 -0
  26. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/fastapi_mcp/scanner.py +0 -0
  27. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_cli.py +0 -0
  28. {fastapi_fastmcp-0.1.2 → fastapi_fastmcp-0.2.0}/tests/test_enterprise.py +0 -0
@@ -1,421 +1,425 @@
1
- Metadata-Version: 2.4
2
- Name: fastapi-fastmcp
3
- Version: 0.1.2
4
- Summary: The unified bridge between FastAPI and FastMCP / Model Context Protocol.
5
- Author: Manav Mehta
6
- License: MIT
7
- Project-URL: Homepage, https://github.com/manavmehta2403/fastapi-mcp
8
- Project-URL: Repository, https://github.com/manavmehta2403/fastapi-mcp
9
- Project-URL: Issues, https://github.com/manavmehta2403/fastapi-mcp/issues
10
- Keywords: fastapi,mcp,fastmcp,model-context-protocol,ai,agents,llm,claude,cursor
11
- Classifier: Development Status :: 4 - Beta
12
- Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: MIT License
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.10
16
- Classifier: Programming Language :: Python :: 3.11
17
- Classifier: Programming Language :: Python :: 3.12
18
- Classifier: Programming Language :: Python :: 3.13
19
- Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
20
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
- Requires-Python: >=3.10
22
- Description-Content-Type: text/markdown
23
- License-File: LICENSE
24
- Requires-Dist: fastapi>=0.100.0
25
- Requires-Dist: mcp>=1.0.0
26
- Requires-Dist: httpx>=0.25.0
27
- Requires-Dist: pydantic>=2.0.0
28
- Requires-Dist: starlette>=0.27.0
29
- Requires-Dist: uvicorn>=0.22.0
30
- Provides-Extra: test
31
- Requires-Dist: pytest>=8.0.0; extra == "test"
32
- Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
33
- Requires-Dist: pytest-cov>=4.0.0; extra == "test"
34
- Requires-Dist: pylint>=3.0.0; extra == "test"
35
- Dynamic: license-file
36
-
37
- # FastAPI-MCP ⚡🤖
38
-
39
- <p align="center">
40
- <b>The unified bridge between FastAPI and FastMCP / Model Context Protocol.</b><br>
41
- <i>Serve REST APIs and MCP AI Tools simultaneously from a single server with zero resource overhead.</i>
42
- </p>
43
-
44
- <p align="center">
45
- <a href="#-key-highlights"><img src="https://img.shields.io/badge/FastAPI-009688?style=flat&logo=fastapi&logoColor=white" alt="FastAPI"></a>
46
- <a href="#-key-highlights"><img src="https://img.shields.io/badge/MCP-Protocol-blueviolet?style=flat" alt="MCP"></a>
47
- <a href="#-key-highlights"><img src="https://img.shields.io/badge/Python-3.10+-3776AB?style=flat&logo=python&logoColor=white" alt="Python"></a>
48
- <a href="#license"><img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License"></a>
49
- </p>
50
-
51
- ---
52
-
53
- ## 🌟 Key Highlights
54
-
55
- * 🤝 **True Protocol Coexistence**: Serve your REST API (OpenAPI/Swagger docs), MCP Server-Sent Events (SSE), and Streamable HTTP endpoints from a **single Uvicorn process and single port**.
56
- * 🛠️ **Dual `@app.api_tool` Decorator**: Define an endpoint once — it instantly becomes both an HTTP REST endpoint for web clients and an MCP tool for AI agents (Claude, Cursor, Antigravity).
57
- * 🔄 **2-Line Existing App Conversion**: Point to any existing FastAPI application and automatically expose its endpoints as MCP tools with zero changes to your existing code.
58
- * 📖 **Built-in MCP Swagger Explorer (`/mcp/docs`)**: An interactive visual playground for testing MCP tools right alongside FastAPI's `/docs`. Inspect parameters and execute tools live with "Try it out" in your browser.
59
- * ⚡ **Zero-Network In-Memory Dispatch**: In-memory ASGI transport executes tool calls directly without TCP socket loopbacks, preserving FastAPI `Depends()` injections, auth, and Pydantic validation.
60
-
61
- ---
62
-
63
- ## 💡 Why a Single Server Architecture? (Resource & Performance Benefits)
64
-
65
- Running separate microservices or independent processes for REST and MCP introduces unnecessary infrastructure complexity and resource waste:
66
-
67
- ### 1. Zero Process Multiplication & Low Memory Footprint
68
- A typical Python web server process uses 60–150 MB of RAM at boot. Running a separate server process for MCP doubles baseline memory consumption and CPU thread contention. With `fastapi-mcp`, everything runs in a **single shared event loop**, conserving memory on budget VMs and cloud containers.
69
-
70
- ### 2. Zero-Network In-Memory Execution
71
- When an AI agent triggers an MCP tool that maps to a FastAPI route, `fastapi-mcp` dispatches the request through an **in-memory ASGI pipeline (`httpx.ASGITransport`)**:
72
- - No TCP socket handshakes
73
- - No loopback network latency
74
- - Sub-millisecond execution speeds
75
-
76
- ### 3. Shared Database Pools & Dependencies
77
- Instead of maintaining two independent database connection pools (one for your REST API and one for your MCP server), your MCP tools directly reuse the existing FastAPI `Depends(get_db)` connection pool and caching layers.
78
-
79
- ### 4. Single Source of Truth for Schemas
80
- You define your Pydantic v2 data models once. Both your OpenAPI specification (`/docs`) and your MCP tool definitions (`/mcp/docs`) are generated from the exact same model definitions without drift.
81
-
82
- ---
83
-
84
- ## 🏗️ Architecture Overview
85
-
86
- ```
87
- +-----------------------+
88
- | AI Agent / Client |
89
- | (Claude Desktop, Cursor|
90
- +-----------+-----------+
91
- |
92
- +------------------------+-----------------------+
93
- | (HTTP / SSE) | (stdio)
94
- v v
95
- +--------------------+---------------------+ +-----------------+---------------------+
96
- | FastAPI ASGI Server (Uvicorn) | | fastapi-mcp CLI (stdio) |
97
- | - Swagger UI: /docs | | (Direct pipe for desktop LLM agents) |
98
- | - REST Endpoints: /items, /users | +-----------------+---------------------+
99
- | - MCP Streamable: /mcp | |
100
- | - MCP SSE Stream: /sse | |
101
- | - MCP Swagger Explorer: /mcp/docs | |
102
- +--------------------+---------------------+ |
103
- | |
104
- +------------------------+-----------------------+
105
- |
106
- v
107
- +---------------+---------------+
108
- | FastAPIMCP Unified Hub |
109
- +---------------+---------------+
110
- |
111
- +-------------------------+-------------------------+
112
- | |
113
- v v
114
- +-------------------+--------------------+ +-----------------+-------------------+
115
- | Route Scanner & Dynamic Tools | | Native MCP Tools |
116
- | - Inspects Path, Query, Body, Headers | | - @app.tool() |
117
- | - Filters out Depends(db), Request | | - @app.resource() |
118
- | - Preserves Pydantic Schema & Docstrings| | - @app.prompt() |
119
- +-------------------+--------------------+ +-----------------+-------------------+
120
- | |
121
- v v
122
- +-------------------+---------------------------------------------------+-------------------+
123
- | In-Memory ASGITransport Dispatcher |
124
- | Resolves Depends() -> Validates Schema -> Invokes Route -> Returns Structured Result |
125
- +-------------------------------------------------------------------------------------------+
126
- ```
127
-
128
- ---
129
-
130
- ## 📦 Installation
131
-
132
- ```bash
133
- pip install fastapi-fastmcp
134
- ```
135
-
136
- *(Works with the latest releases of `fastapi`, `mcp`, `pydantic`, `httpx`, and `uvicorn`)*
137
-
138
- ---
139
-
140
- ## 🚀 Quickstart Guides
141
-
142
- ### Pattern 1: Convert an Existing FastAPI App (2 Lines)
143
-
144
- Take any existing FastAPI application with routes, database sessions, and dependencies, and expose it to AI agents:
145
-
146
- ```python
147
- from fastapi import FastAPI, Depends, Query, Path
148
- from pydantic import BaseModel, Field
149
- from fastapi_mcp import FastAPIMCP
150
-
151
- app = FastAPI(title="Store API")
152
-
153
- class Item(BaseModel):
154
- name: str = Field(..., description="Product title")
155
- price: float = Field(..., description="Product price")
156
-
157
- def get_db():
158
- return {"status": "connected"}
159
-
160
- @app.get("/items/{item_id}", summary="Get item details")
161
- async def get_item(
162
- item_id: int = Path(..., description="Unique product ID"),
163
- verbose: bool = Query(False, description="Include detailed specs"),
164
- db: dict = Depends(get_db) # Auto-resolved in-memory, hidden from LLM schema!
165
- ):
166
- """Retrieve item details by ID."""
167
- return {"id": item_id, "verbose": verbose, "db": db["status"]}
168
-
169
- @app.post("/items", summary="Create item")
170
- async def create_item(item: Item, db: dict = Depends(get_db)):
171
- """Create a new item in the catalog."""
172
- return {"status": "created", "item": item.model_dump()}
173
-
174
- # -------------------------------------------------------------
175
- # 🌟 CONVERT & MOUNT IN 2 LINES:
176
- # -------------------------------------------------------------
177
- mcp = FastAPIMCP.bind(app, name="StoreMCP")
178
- mcp.mount_to(app, path="/mcp", sse_path="/sse")
179
- ```
180
-
181
- ---
182
-
183
- ### Pattern 2: Hybrid Dual API (`@app.api_tool`)
184
-
185
- Build new services where functions are simultaneously REST endpoints and MCP tools:
186
-
187
- ```python
188
- from fastapi_mcp import FastAPIMCP
189
- from pydantic import BaseModel, Field
190
-
191
- # FastAPIMCP is a drop-in replacement for FastAPI
192
- app = FastAPIMCP(title="Hybrid Service", mcp_name="UnifiedServer")
193
-
194
- class CalculateRequest(BaseModel):
195
- x: float = Field(..., description="First operand")
196
- y: float = Field(..., description="Second operand")
197
- op: str = Field("add", description="Operation: 'add', 'sub', 'mul', 'div'")
198
-
199
- # 1. 🛠️ DUAL ENDPOINT: Accessible via REST POST /math/calc AND as MCP Tool 'calculate'
200
- @app.api_tool("/math/calc", methods=["POST"], tool_name="calculate")
201
- async def calculate(data: CalculateRequest) -> dict:
202
- """Perform mathematical calculations."""
203
- if data.op == "add":
204
- res = data.x + data.y
205
- elif data.op == "mul":
206
- res = data.x * data.y
207
- else:
208
- res = data.x - data.y
209
- return {"result": res, "op": data.op}
210
-
211
- # 2. 🧩 PURE MCP TOOL: Agent-only tool (hidden from public REST routes)
212
- @app.tool(name="internal_rag_search")
213
- async def internal_search(query: str) -> list[str]:
214
- """Search internal documentation."""
215
- return [f"Article match for '{query}'"]
216
-
217
- # 3. 🌐 PURE REST ROUTE: Standard FastAPI route
218
- @app.get("/health")
219
- async def health():
220
- return {"status": "ok"}
221
-
222
- # Mount MCP endpoints onto the server
223
- app.mount_mcp(path="/mcp", sse_path="/sse")
224
- ```
225
-
226
- ---
227
-
228
- ## 🌐 Deployment Options
229
-
230
- ### Option A: Single Port Deployment (Default & Recommended)
231
- Serve both your REST API and MCP transports from the same port:
232
-
233
- ```bash
234
- uvicorn main:app --host 0.0.0.0 --port 8000
235
- ```
236
-
237
- Available endpoints on port 8000:
238
- * **FastAPI Swagger UI**: `http://localhost:8000/docs`
239
- * **MCP Swagger Explorer**: `http://localhost:8000/mcp/docs`
240
- * **MCP Streamable HTTP**: `http://localhost:8000/mcp`
241
- * **MCP Server-Sent Events (SSE)**: `http://localhost:8000/sse`
242
-
243
- ---
244
-
245
- ### Option B: Split Port Deployment (Network Segmentation)
246
- If your infrastructure requires keeping internal AI traffic on an isolated private port while serving public REST traffic externally:
247
-
248
- ```python
249
- import uvicorn
250
- import threading
251
-
252
- # Serve REST on public port 8000, and MCP on internal port 9000
253
- def run_rest():
254
- uvicorn.run(app, host="0.0.0.0", port=8000)
255
-
256
- def run_mcp():
257
- # Run standalone MCP SSE or streamable app on isolated port
258
- mcp_app = mcp.mcp_server.streamable_http_app()
259
- uvicorn.run(mcp_app, host="127.0.0.1", port=9000)
260
-
261
- if __name__ == "__main__":
262
- threading.Thread(target=run_mcp, daemon=True).start()
263
- run_rest()
264
- ```
265
-
266
- ---
267
-
268
- ## 📖 Dual-Engine MCP Swagger Explorer (`/mcp/docs` & `/mcp/ui`)
269
-
270
- FastAPI-MCP provides a seamless, hybrid documentation experience for your Model Context Protocol tools:
271
-
272
- 1. **Official Swagger UI (`/mcp/docs`)**:
273
- - The literal, official Swagger UI powered by OpenAPI 3.1.
274
- - Built-in `curl` command generator, request schema validation, and "Try it out" live execution directly into `/mcp/tools/{tool_name}`.
275
- - Groups tools cleanly by route tags or under `MCP Tools`.
276
-
277
- 2. **100% Offline Standalone Explorer (`/mcp/ui`)**:
278
- - Zero-CDN, air-gapped standalone HTML/CSS/JS explorer.
279
- - Styled pixel-for-pixel to match Swagger UI's iconic design and buttons.
280
- - Connects directly to in-process execution via `/mcp/ui/call`.
281
-
282
- 3. **Dynamic MCP OpenAPI 3.1 Specification (`/mcp/openapi.json`)**:
283
- - Machine-readable OpenAPI 3.1 contract of all your MCP tools.
284
- - Ready for import into Postman, Insomnia, or client SDK generators.
285
-
286
- ---
287
-
288
- ## 💻 Claude Desktop & Cursor Integration
289
-
290
- Run your FastAPI application directly over `stdio` without needing an active HTTP server:
291
-
292
- Add this to your `claude_desktop_config.json`:
293
-
294
- ```json
295
- {
296
- "mcpServers": {
297
- "my-fastapi-app": {
298
- "command": "python",
299
- "args": ["-m", "fastapi_mcp.cli", "run", "main:app", "--transport", "stdio"]
300
- }
301
- }
302
- }
303
- ```
304
-
305
- ---
306
-
307
- ## 🛡️ Enterprise Hardening: Solving Production Bottlenecks
308
-
309
- In large enterprise microservices with dozens or hundreds of routes, simply dumping every endpoint as an individual MCP tool creates serious production hurdles. `fastapi-mcp` ships with built-in primitives to solve them:
310
-
311
- ### 1. Librarian Discovery Pattern (Preventing Context Window Bloat)
312
- Exposing 80+ tools dumps 15,000–25,000 tokens into the LLM system prompt on every single turn, degrading reasoning and exploding API bills.
313
-
314
- Activate **Librarian Mode** to condense all catalog tools into **3 lightweight meta-tools**:
315
- ```python
316
- mcp = FastAPIMCP.bind(app, librarian=True)
317
- ```
318
- The LLM now only sees:
319
- * `list_api_categories()`: Browse high-level domains (e.g. `billing`, `inventory`, `users`) with tool summaries.
320
- * `search_api_tools(query, category)`: Fetch detailed schemas for matching tools on demand.
321
- * `execute_api_tool(tool_name, arguments)`: Dynamically invoke the requested underlying endpoint.
322
-
323
- ### 2. Dry-Run Simulation Mode (`enable_dry_run=True`)
324
- Allow AI agents to validate parameters and simulate state mutations (`POST`, `PUT`, `DELETE`, `PATCH`) safely:
325
- ```python
326
- mcp = FastAPIMCP.bind(app, enable_dry_run=True)
327
- ```
328
- * Injects a `dry_run: bool = False` argument into mutation tools.
329
- * Dispatches in-memory with `X-Dry-Run: true` header and `?dry_run=true` query parameter.
330
- * Wraps responses with `{"dry_run": True, "simulated": True, "result": ...}` so agents can test changes before committing them.
331
-
332
- ### 3. Dynamic Session Context Provider (Multi-Tenant Stdio & SSE Auth)
333
- Desktop agents connecting via `stdio` (like Claude Desktop or Cursor) do not send standard HTTP `Authorization: Bearer <token>` headers. Without caller context, endpoints with `Depends(get_current_user)` fail with 401 Unauthorized.
334
-
335
- Inject authentication claims dynamically per session:
336
- ```python
337
- def resolve_tenant_context(tool_args: dict) -> dict:
338
- # Resolve active tenant / user from session or environment
339
- return {"Authorization": "Bearer session-token-xyz", "X-Tenant-ID": "acme-corp"}
340
-
341
- mcp = FastAPIMCP.bind(
342
- app,
343
- session_context_provider=resolve_tenant_context,
344
- )
345
-
346
- # Or update dynamically during runtime
347
- mcp.set_session_context_provider(lambda kwargs: {"Authorization": "Bearer rotated-token"})
348
- ```
349
-
350
- ---
351
-
352
- ## 🛠️ CLI Utilities
353
-
354
- ### 1. Inspect Tools and Schemas
355
- Inspect which tools and schemas are generated from your FastAPI application:
356
- ```bash
357
- fastapi-mcp inspect main:app
358
- ```
359
-
360
- Output:
361
- ```text
362
- === FastAPI-MCP Server: UnifiedServer ===
363
- Found 2 tools:
364
-
365
- * Tool: calculate
366
- Description: [POST /math/calc] Perform mathematical calculations.
367
- Arguments (1):
368
- - data: CalculateRequest (required) - Calculation input data
369
-
370
- * Tool: internal_rag_search
371
- Description: Search internal documentation.
372
- Arguments (1):
373
- - query: string (required)
374
- ```
375
-
376
- Export schema as JSON:
377
- ```bash
378
- fastapi-mcp inspect main:app --json
379
- ```
380
-
381
- ### 2. Run Directly from CLI
382
- ```bash
383
- fastapi-mcp run main:app --transport stdio
384
- fastapi-mcp run main:app --transport sse
385
- ```
386
-
387
- ---
388
-
389
- ## ⚙️ Route Filtering & Custom Headers
390
-
391
- ```python
392
- mcp = FastAPIMCP.bind(
393
- app,
394
- # Exclude internal routes
395
- exclude_paths=["/admin/*", "/metrics"],
396
- # Only expose routes with specific OpenAPI tags
397
- include_tags={"mcp", "public"},
398
- # Filter methods
399
- include_methods={"GET", "POST"},
400
- # Static auth headers for protected routes
401
- default_headers={"Authorization": "Bearer internal-service-token"},
402
- # Or dynamic headers callback
403
- headers_factory=lambda: {"X-Request-Source": "mcp-agent"}
404
- )
405
- ```
406
-
407
- ---
408
-
409
- ## 🧪 Running Tests
410
-
411
- The test suite covers route auto-scanning, in-memory ASGI dispatch, dual-mode decorators, single-port co-hosting, and the MCP Swagger UI:
412
-
413
- ```bash
414
- pytest tests/ -v
415
- ```
416
-
417
- ---
418
-
419
- ## 📄 License
420
-
421
- MIT License. See [LICENSE](LICENSE) for details.
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-fastmcp
3
+ Version: 0.2.0
4
+ Summary: The unified bridge between FastAPI and FastMCP / Model Context Protocol.
5
+ Author: Manav Mehta
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/manavmehta2403/fastapi-mcp
8
+ Project-URL: Repository, https://github.com/manavmehta2403/fastapi-mcp
9
+ Project-URL: Issues, https://github.com/manavmehta2403/fastapi-mcp/issues
10
+ Keywords: fastapi,mcp,fastmcp,model-context-protocol,ai,agents,llm,claude,cursor
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: fastapi>=0.100.0
25
+ Requires-Dist: mcp>=1.0.0
26
+ Requires-Dist: httpx>=0.25.0
27
+ Requires-Dist: pydantic>=2.0.0
28
+ Requires-Dist: starlette>=0.27.0
29
+ Requires-Dist: uvicorn>=0.22.0
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=8.0.0; extra == "test"
32
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
33
+ Requires-Dist: pytest-cov>=4.0.0; extra == "test"
34
+ Requires-Dist: pylint>=3.0.0; extra == "test"
35
+ Dynamic: license-file
36
+
37
+ # FastAPI-MCP ⚡🤖
38
+
39
+ <p align="center">
40
+ <b>The unified bridge between FastAPI and FastMCP / Model Context Protocol.</b><br>
41
+ <i>Serve REST APIs and MCP AI Tools simultaneously from a single server with zero resource overhead.</i>
42
+ </p>
43
+
44
+ <p align="center">
45
+ <a href="#-key-highlights"><img src="https://img.shields.io/badge/FastAPI-009688?style=flat&logo=fastapi&logoColor=white" alt="FastAPI"></a>
46
+ <a href="#-key-highlights"><img src="https://img.shields.io/badge/MCP-Protocol-blueviolet?style=flat" alt="MCP"></a>
47
+ <a href="#-key-highlights"><img src="https://img.shields.io/badge/Python-3.10+-3776AB?style=flat&logo=python&logoColor=white" alt="Python"></a>
48
+ <a href="#license"><img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License"></a>
49
+ </p>
50
+
51
+ ---
52
+
53
+ ## 🌟 Key Highlights
54
+
55
+ * 🤝 **True Protocol Coexistence**: Serve your REST API (OpenAPI/Swagger docs), MCP Server-Sent Events (SSE), and Streamable HTTP endpoints from a **single Uvicorn process and single port**.
56
+ * 🛠️ **Dual `@app.api_tool` Decorator**: Define an endpoint once — it instantly becomes both an HTTP REST endpoint for web clients and an MCP tool for AI agents (Claude, Cursor, Windsurf).
57
+ * 🤖 **FastAPI-MCP Studio (`/mcp/ui`)**: Full-featured developer studio covering all 3 MCP primitives (**Tools**, **Resources**, and **Prompts**) with visual testing, execution latency timers, and 1-click executable code snippets (Python FastMCP, cURL JSON-RPC 2.0, TypeScript SDK).
58
+ * 🌐 **Unified Navigation Dock**: Bridges FastAPI REST documentation (`/docs`, `/redoc`) and MCP Developer Studio (`/mcp/ui`) with seamless, zero-breaking-change navigation and a 1-click **Client Connect Modal** (Claude, Cursor, Windsurf).
59
+ * 🔄 **2-Line Existing App Conversion**: Point to any existing FastAPI application and automatically expose its endpoints as MCP tools with zero changes to your existing code.
60
+ * ⚡ **Zero-Network In-Memory Dispatch**: In-memory ASGI transport executes tool calls directly without TCP socket loopbacks, preserving FastAPI `Depends()` injections, auth, and Pydantic validation.
61
+
62
+ ---
63
+
64
+ ## 💡 Why a Single Server Architecture? (Resource & Performance Benefits)
65
+
66
+ Running separate microservices or independent processes for REST and MCP introduces unnecessary infrastructure complexity and resource waste:
67
+
68
+ ### 1. Zero Process Multiplication & Low Memory Footprint
69
+ A typical Python web server process uses 60–150 MB of RAM at boot. Running a separate server process for MCP doubles baseline memory consumption and CPU thread contention. With `fastapi-mcp`, everything runs in a **single shared event loop**, conserving memory on budget VMs and cloud containers.
70
+
71
+ ### 2. Zero-Network In-Memory Execution
72
+ When an AI agent triggers an MCP tool that maps to a FastAPI route, `fastapi-mcp` dispatches the request through an **in-memory ASGI pipeline (`httpx.ASGITransport`)**:
73
+ - No TCP socket handshakes
74
+ - No loopback network latency
75
+ - Sub-millisecond execution speeds
76
+
77
+ ### 3. Shared Database Pools & Dependencies
78
+ Instead of maintaining two independent database connection pools (one for your REST API and one for your MCP server), your MCP tools directly reuse the existing FastAPI `Depends(get_db)` connection pool and caching layers.
79
+
80
+ ### 4. Single Source of Truth for Schemas
81
+ You define your Pydantic v2 data models once. Both your OpenAPI specification (`/docs`) and your MCP tool definitions (`/mcp/docs`) are generated from the exact same model definitions without drift.
82
+
83
+ ---
84
+
85
+ ## 🏗️ Architecture Overview
86
+
87
+ ```
88
+ +-----------------------+
89
+ | AI Agent / Client |
90
+ | (Claude Desktop, Cursor|
91
+ +-----------+-----------+
92
+ |
93
+ +------------------------+-----------------------+
94
+ | (HTTP / SSE) | (stdio)
95
+ v v
96
+ +--------------------+---------------------+ +-----------------+---------------------+
97
+ | FastAPI ASGI Server (Uvicorn) | | fastapi-mcp CLI (stdio) |
98
+ | - Swagger UI: /docs | | (Direct pipe for desktop LLM agents) |
99
+ | - REST Endpoints: /items, /users | +-----------------+---------------------+
100
+ | - MCP Streamable: /mcp | |
101
+ | - MCP SSE Stream: /sse | |
102
+ | - MCP Swagger Explorer: /mcp/docs | |
103
+ +--------------------+---------------------+ |
104
+ | |
105
+ +------------------------+-----------------------+
106
+ |
107
+ v
108
+ +---------------+---------------+
109
+ | FastAPIMCP Unified Hub |
110
+ +---------------+---------------+
111
+ |
112
+ +-------------------------+-------------------------+
113
+ | |
114
+ v v
115
+ +-------------------+--------------------+ +-----------------+-------------------+
116
+ | Route Scanner & Dynamic Tools | | Native MCP Tools |
117
+ | - Inspects Path, Query, Body, Headers | | - @app.tool() |
118
+ | - Filters out Depends(db), Request | | - @app.resource() |
119
+ | - Preserves Pydantic Schema & Docstrings| | - @app.prompt() |
120
+ +-------------------+--------------------+ +-----------------+-------------------+
121
+ | |
122
+ v v
123
+ +-------------------+---------------------------------------------------+-------------------+
124
+ | In-Memory ASGITransport Dispatcher |
125
+ | Resolves Depends() -> Validates Schema -> Invokes Route -> Returns Structured Result |
126
+ +-------------------------------------------------------------------------------------------+
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 📦 Installation
132
+
133
+ ```bash
134
+ pip install fastapi-fastmcp
135
+ ```
136
+
137
+ *(Works with the latest releases of `fastapi`, `mcp`, `pydantic`, `httpx`, and `uvicorn`)*
138
+
139
+ ---
140
+
141
+ ## 🚀 Quickstart Guides
142
+
143
+ ### Pattern 1: Convert an Existing FastAPI App (2 Lines)
144
+
145
+ Take any existing FastAPI application with routes, database sessions, and dependencies, and expose it to AI agents:
146
+
147
+ ```python
148
+ from fastapi import FastAPI, Depends, Query, Path
149
+ from pydantic import BaseModel, Field
150
+ from fastapi_mcp import FastAPIMCP
151
+
152
+ app = FastAPI(title="Store API")
153
+
154
+ class Item(BaseModel):
155
+ name: str = Field(..., description="Product title")
156
+ price: float = Field(..., description="Product price")
157
+
158
+ def get_db():
159
+ return {"status": "connected"}
160
+
161
+ @app.get("/items/{item_id}", summary="Get item details")
162
+ async def get_item(
163
+ item_id: int = Path(..., description="Unique product ID"),
164
+ verbose: bool = Query(False, description="Include detailed specs"),
165
+ db: dict = Depends(get_db) # Auto-resolved in-memory, hidden from LLM schema!
166
+ ):
167
+ """Retrieve item details by ID."""
168
+ return {"id": item_id, "verbose": verbose, "db": db["status"]}
169
+
170
+ @app.post("/items", summary="Create item")
171
+ async def create_item(item: Item, db: dict = Depends(get_db)):
172
+ """Create a new item in the catalog."""
173
+ return {"status": "created", "item": item.model_dump()}
174
+
175
+ # -------------------------------------------------------------
176
+ # 🌟 CONVERT & MOUNT IN 2 LINES:
177
+ # -------------------------------------------------------------
178
+ mcp = FastAPIMCP.bind(app, name="StoreMCP")
179
+ mcp.mount_to(app, path="/mcp", sse_path="/sse")
180
+ ```
181
+
182
+ ---
183
+
184
+ ### Pattern 2: Hybrid Dual API (`@app.api_tool`)
185
+
186
+ Build new services where functions are simultaneously REST endpoints and MCP tools:
187
+
188
+ ```python
189
+ from fastapi_mcp import FastAPIMCP
190
+ from pydantic import BaseModel, Field
191
+
192
+ # FastAPIMCP is a drop-in replacement for FastAPI
193
+ app = FastAPIMCP(title="Hybrid Service", mcp_name="UnifiedServer")
194
+
195
+ class CalculateRequest(BaseModel):
196
+ x: float = Field(..., description="First operand")
197
+ y: float = Field(..., description="Second operand")
198
+ op: str = Field("add", description="Operation: 'add', 'sub', 'mul', 'div'")
199
+
200
+ # 1. 🛠️ DUAL ENDPOINT: Accessible via REST POST /math/calc AND as MCP Tool 'calculate'
201
+ @app.api_tool("/math/calc", methods=["POST"], tool_name="calculate")
202
+ async def calculate(data: CalculateRequest) -> dict:
203
+ """Perform mathematical calculations."""
204
+ if data.op == "add":
205
+ res = data.x + data.y
206
+ elif data.op == "mul":
207
+ res = data.x * data.y
208
+ else:
209
+ res = data.x - data.y
210
+ return {"result": res, "op": data.op}
211
+
212
+ # 2. 🧩 PURE MCP TOOL: Agent-only tool (hidden from public REST routes)
213
+ @app.tool(name="internal_rag_search")
214
+ async def internal_search(query: str) -> list[str]:
215
+ """Search internal documentation."""
216
+ return [f"Article match for '{query}'"]
217
+
218
+ # 3. 🌐 PURE REST ROUTE: Standard FastAPI route
219
+ @app.get("/health")
220
+ async def health():
221
+ return {"status": "ok"}
222
+
223
+ # Mount MCP endpoints onto the server
224
+ app.mount_mcp(path="/mcp", sse_path="/sse")
225
+ ```
226
+
227
+ ---
228
+
229
+ ## 🌐 Deployment Options
230
+
231
+ ### Option A: Single Port Deployment (Default & Recommended)
232
+ Serve both your REST API and MCP transports from the same port:
233
+
234
+ ```bash
235
+ uvicorn main:app --host 0.0.0.0 --port 8000
236
+ ```
237
+
238
+ Available endpoints on port 8000:
239
+ * **FastAPI REST Swagger UI**: `http://localhost:8000/docs`
240
+ * **FastAPI REST ReDoc**: `http://localhost:8000/redoc`
241
+ * **FastAPI-MCP Developer Studio**: `http://localhost:8000/mcp/ui`
242
+ * **MCP OpenAPI 3.1 Specification**: `http://localhost:8000/mcp/openapi.json`
243
+ * **MCP Streamable HTTP Transport**: `http://localhost:8000/mcp`
244
+ * **MCP Server-Sent Events (SSE)**: `http://localhost:8000/sse`
245
+
246
+ ---
247
+
248
+ ### Option B: Split Port Deployment (Network Segmentation)
249
+ If your infrastructure requires keeping internal AI traffic on an isolated private port while serving public REST traffic externally:
250
+
251
+ ```python
252
+ import uvicorn
253
+ import threading
254
+
255
+ # Serve REST on public port 8000, and MCP on internal port 9000
256
+ def run_rest():
257
+ uvicorn.run(app, host="0.0.0.0", port=8000)
258
+
259
+ def run_mcp():
260
+ # Run standalone MCP SSE or streamable app on isolated port
261
+ mcp_app = mcp.mcp_server.streamable_http_app()
262
+ uvicorn.run(mcp_app, host="127.0.0.1", port=9000)
263
+
264
+ if __name__ == "__main__":
265
+ threading.Thread(target=run_mcp, daemon=True).start()
266
+ run_rest()
267
+ ```
268
+
269
+ ---
270
+
271
+ ## 🤖 FastAPI-MCP Studio (`/mcp/ui`) & Unified Navigation
272
+
273
+ FastAPI-MCP v0.2.0 introduces a dedicated, world-class developer studio that unifies REST documentation and the Model Context Protocol ecosystem:
274
+
275
+ ### 1. The 3 MCP Primitives in One Workbench
276
+ - 🛠️ **Tools (`@app.api_tool()`, `@app.tool()`)**: Dynamic schema parameter forms, live in-memory execution, latency timing (e.g. `200 OK (34ms)`), formatted output viewer, and 1-click executable client snippets (**Python FastMCP Client**, **cURL JSON-RPC 2.0**, and **TypeScript SDK**).
277
+ - 📦 **Resources (`@app.resource()`)**: Explore URI schemes (e.g. `company://config`), inspect MIME types, and read live payloads with 1-click execution.
278
+ - 💬 **Prompts (`@app.prompt()`)**: Preview prompt templates, supply test arguments, and inspect rendered user/system messages in real time.
279
+
280
+ ### 2. Unified Navigation Dock
281
+ A persistent, blurred top navigation bar bridges your entire stack:
282
+ - **REST API Group**: 1-click access to FastAPI Swagger (`/docs`) and ReDoc (`/redoc`).
283
+ - **MCP Group**: Direct link to the MCP Studio (`/mcp/ui`).
284
+ - **🔌 Connect Client Modal**: Ready-to-copy configuration JSON snippets for **Claude Desktop** (`claude_desktop_config.json`), **Cursor IDE** (`.cursor/mcp.json`), **Windsurf** (`mcp_config.json`), and legacy **SSE Transport**.
285
+
286
+ ### 3. OpenAPI 3.1 Spec & Schema Export
287
+ - Export the complete machine-readable OpenAPI 3.1 specification at `/mcp/openapi.json`.
288
+ - 1-click **Copy Tool Schema** buttons to copy exact Pydantic/OpenAPI JSON schemas directly into AI prompts, LangChain, or agentic frameworks.
289
+
290
+ ---
291
+
292
+ ## 💻 Claude Desktop & Cursor Integration
293
+
294
+ Run your FastAPI application directly over `stdio` without needing an active HTTP server:
295
+
296
+ Add this to your `claude_desktop_config.json`:
297
+
298
+ ```json
299
+ {
300
+ "mcpServers": {
301
+ "my-fastapi-app": {
302
+ "command": "python",
303
+ "args": ["-m", "fastapi_mcp.cli", "run", "main:app", "--transport", "stdio"]
304
+ }
305
+ }
306
+ }
307
+ ```
308
+
309
+ ---
310
+
311
+ ## 🛡️ Enterprise Hardening: Solving Production Bottlenecks
312
+
313
+ In large enterprise microservices with dozens or hundreds of routes, simply dumping every endpoint as an individual MCP tool creates serious production hurdles. `fastapi-mcp` ships with built-in primitives to solve them:
314
+
315
+ ### 1. Librarian Discovery Pattern (Preventing Context Window Bloat)
316
+ Exposing 80+ tools dumps 15,000–25,000 tokens into the LLM system prompt on every single turn, degrading reasoning and exploding API bills.
317
+
318
+ Activate **Librarian Mode** to condense all catalog tools into **3 lightweight meta-tools**:
319
+ ```python
320
+ mcp = FastAPIMCP.bind(app, librarian=True)
321
+ ```
322
+ The LLM now only sees:
323
+ * `list_api_categories()`: Browse high-level domains (e.g. `billing`, `inventory`, `users`) with tool summaries.
324
+ * `search_api_tools(query, category)`: Fetch detailed schemas for matching tools on demand.
325
+ * `execute_api_tool(tool_name, arguments)`: Dynamically invoke the requested underlying endpoint.
326
+
327
+ ### 2. Dry-Run Simulation Mode (`enable_dry_run=True`)
328
+ Allow AI agents to validate parameters and simulate state mutations (`POST`, `PUT`, `DELETE`, `PATCH`) safely:
329
+ ```python
330
+ mcp = FastAPIMCP.bind(app, enable_dry_run=True)
331
+ ```
332
+ * Injects a `dry_run: bool = False` argument into mutation tools.
333
+ * Dispatches in-memory with `X-Dry-Run: true` header and `?dry_run=true` query parameter.
334
+ * Wraps responses with `{"dry_run": True, "simulated": True, "result": ...}` so agents can test changes before committing them.
335
+
336
+ ### 3. Dynamic Session Context Provider (Multi-Tenant Stdio & SSE Auth)
337
+ Desktop agents connecting via `stdio` (like Claude Desktop or Cursor) do not send standard HTTP `Authorization: Bearer <token>` headers. Without caller context, endpoints with `Depends(get_current_user)` fail with 401 Unauthorized.
338
+
339
+ Inject authentication claims dynamically per session:
340
+ ```python
341
+ def resolve_tenant_context(tool_args: dict) -> dict:
342
+ # Resolve active tenant / user from session or environment
343
+ return {"Authorization": "Bearer session-token-xyz", "X-Tenant-ID": "acme-corp"}
344
+
345
+ mcp = FastAPIMCP.bind(
346
+ app,
347
+ session_context_provider=resolve_tenant_context,
348
+ )
349
+
350
+ # Or update dynamically during runtime
351
+ mcp.set_session_context_provider(lambda kwargs: {"Authorization": "Bearer rotated-token"})
352
+ ```
353
+
354
+ ---
355
+
356
+ ## 🛠️ CLI Utilities
357
+
358
+ ### 1. Inspect Tools and Schemas
359
+ Inspect which tools and schemas are generated from your FastAPI application:
360
+ ```bash
361
+ fastapi-mcp inspect main:app
362
+ ```
363
+
364
+ Output:
365
+ ```text
366
+ === FastAPI-MCP Server: UnifiedServer ===
367
+ Found 2 tools:
368
+
369
+ * Tool: calculate
370
+ Description: [POST /math/calc] Perform mathematical calculations.
371
+ Arguments (1):
372
+ - data: CalculateRequest (required) - Calculation input data
373
+
374
+ * Tool: internal_rag_search
375
+ Description: Search internal documentation.
376
+ Arguments (1):
377
+ - query: string (required)
378
+ ```
379
+
380
+ Export schema as JSON:
381
+ ```bash
382
+ fastapi-mcp inspect main:app --json
383
+ ```
384
+
385
+ ### 2. Run Directly from CLI
386
+ ```bash
387
+ fastapi-mcp run main:app --transport stdio
388
+ fastapi-mcp run main:app --transport sse
389
+ ```
390
+
391
+ ---
392
+
393
+ ## ⚙️ Route Filtering & Custom Headers
394
+
395
+ ```python
396
+ mcp = FastAPIMCP.bind(
397
+ app,
398
+ # Exclude internal routes
399
+ exclude_paths=["/admin/*", "/metrics"],
400
+ # Only expose routes with specific OpenAPI tags
401
+ include_tags={"mcp", "public"},
402
+ # Filter methods
403
+ include_methods={"GET", "POST"},
404
+ # Static auth headers for protected routes
405
+ default_headers={"Authorization": "Bearer internal-service-token"},
406
+ # Or dynamic headers callback
407
+ headers_factory=lambda: {"X-Request-Source": "mcp-agent"}
408
+ )
409
+ ```
410
+
411
+ ---
412
+
413
+ ## 🧪 Running Tests
414
+
415
+ The test suite covers route auto-scanning, in-memory ASGI dispatch, dual-mode decorators, single-port co-hosting, and the MCP Swagger UI:
416
+
417
+ ```bash
418
+ pytest tests/ -v
419
+ ```
420
+
421
+ ---
422
+
423
+ ## 📄 License
424
+
425
+ MIT License. See [LICENSE](LICENSE) for details.