-
Notifications
You must be signed in to change notification settings - Fork 856
Description
fastapi-mcp library causes RecursionError: maximum recursion depth exceeded when processing FastAPI applications with recursive Pydantic models (self-referencing models).
Environment:
fastapi-mcp version: 0.4.0
FastAPI version: 0.115.x
Python version: 3.12
OS: Linux (Docker container)
Minimal Reproduction:
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
class Post(BaseModel):
id: str
text: str
isTarget: bool
comments: Optional[List['Post']] = None # This recursive reference triggers the bug
class Request(BaseModel):
posts: List[Post]
@app.get("/ping")
async def ping():
return {"pong": True}
@app.post("/test")
async def test_endpoint(request: Request):
return {"received": len(request.posts)}
if name == "main":
try:
mcp = FastApiMCP(app)
mcp.mount_http() # RecursionError occurs here
except RecursionError as e:
print(f"RecursionError: {e}")
Error Details:
Stack Trace:
File "/app/.venv/lib/python3.12/site-packages/fastapi_mcp/openapi/utils.py", line 50, in resolve_schema_references
schema_part[key] = resolve_schema_references(value, reference_schema)
File "/app/.venv/lib/python3.12/site-packages/fastapi_mcp/openapi/utils.py", line 54, in resolve_schema_references
resolve_schema_references(item, reference_schema) if isinstance(item, dict) else item for item in value
...
RecursionError: maximum recursion depth exceeded
Root Cause Analysis:
The issue occurs in fastapi_mcp/openapi/utils.py in the resolve_schema_references function. When FastAPI generates OpenAPI schemas for recursive Pydantic models, it creates circular $ref references. The fastapi-mcp library's schema resolution logic doesn't handle these circular references properly, causing infinite recursion.
Expected Behavior:
MCP should mount successfully and handle recursive Pydantic models gracefully, either by:
Detecting circular references and stopping recursion
Using a different schema resolution strategy
Providing a configuration option to disable deep schema introspection
Workaround:
Currently using try/catch to disable MCP when recursion occurs:
try:
mcp = FastApiMCP(app)
mcp.mount_http()
except RecursionError:
import warnings
warnings.warn("fastapi-mcp recursion bug - MCP disabled")
Impact:
This affects any FastAPI application with recursive data models (common in hierarchical data structures like comments, categories, organizational charts, etc.).
Additional Context:
Simple FastAPI apps without recursive models work fine
The issue is specifically in the OpenAPI schema processing, not in the MCP protocol itself
Core FastAPI functionality is unaffected - only MCP integration fails