FastAPI → Hyperia Bridge
Transform any FastAPI application into a live Hyperia MCP server with a single call—unlocking LLM‑ready tools and resources while preserving your existing Python business logic.
Prerequisite Install FastAPI & an ASGI runtime:
pip install fastapi uvicorn[standard]
.
1 Hello‑World Conversion
from fastapi import FastAPI
from hyperia import Hyperia
api = FastAPI()
@api.get("/ping")
def ping():
return {"pong": True}
mcp = Hyperia.from_fastapi(app=api, name="PingAPI")
if __name__ == "__main__":
mcp.run(transport="streamable-http", port=9100)
Now any Hyperia client (or Claude Desktop) can read_resource("resource://ping")
.
2 How the Converter Works
Inspects the FastAPI app’s router (
app.openapi()
behind the scenes).Applies route‑mapping rules (see §3).
Builds wrappers that:
Extract path/query/body args from the MCP call.
Invoke the FastAPI dependency graph (including
Depends
, auth, middle‑ ware).Serialise the Starlette
Response
→ MCP contents.
Registers the new callable with the Hyperia server.
Because we bypass the network, calls execute in‑process with the same Python interpreter—zero HTTP overhead.
3 Default Route Mapping
@api.get("/stats")
no params
Resource
resource://stats
@api.get("/users/{id}")
has path param
ResourceTemplate
users://{id}
any non‑GET (post/put/patch/delete
)
@api.post("/users")
Tool
createUser
(from op id or path)
Customise with route_maps
(same structure as OpenAPI integration):
from hyperia.server.openapi import RouteMap, RouteType
maps = [RouteMap(methods=["GET"], pattern=r"^/export/.*", route_type=RouteType.TOOL)]
mcp = Hyperia.from_fastapi(app, route_maps=maps)
all_routes_as_tools=True forces everything to be a Tool—nice for agent back‑ends.
4 Timeout & Concurrency Control
mcp = Hyperia.from_fastapi(app, timeout=4.0, max_concurrency=50)
timeout
– per‑request ceiling (seconds) for tool/resource execution.max_concurrency
– semaphore protecting the underlying FastAPI app when hit via MCP (does not affect external HTTP calls to the same FastAPI app).
5 Advanced Examples
5.1 CRUD Service with Pydantic Models
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
from hyperia import Hyperia
class Item(BaseModel): name: str; price: float
api = FastAPI(); db: dict[int, Item] = {}
@api.get("/items", response_model=list[Item])
def list_items(): return list(db.values())
@api.post("/items", response_model=Item, status_code=201)
def new(item: Item):
idx = len(db)+1; db[idx] = item; return item
@api.get("/items/{idx}")
def get(idx: int):
if idx not in db: raise HTTPException(404)
return db[idx]
mcp = Hyperia.from_fastapi(api, name="Shop")
Generated components:
Tool
new
(calls POST /items)Resource
items
(GET /items)Template
items://{idx}
(GET /items/{idx})
5.2 Streaming Responses
FastAPI StreamingResponse
→ Hyperia chunked TextContent
. Supports SSE or incremental JSON.
5.3 Auth Propagation
If your FastAPI endpoints use Depends(get_current_user)
, they still work—Hyperia just runs the dependency call chain.
For agent scenarios supply a dummy user via DependencyOverrides
before wrapping:
api.dependency_overrides[get_current_user] = lambda: User(id=1, name="agent")
6 Why Use FastAPI→Hyperia Instead of OpenAPI→Hyperia?
Same‑process calls
✔
✖ (HTTP)
Re‑use FastAPI dependencies & state
✔
✖
No existing spec file
✔
✖
You only have OpenAPI description
✖
✔
Need multi‑language SDKs
✖
✔ (just use spec)
You can even combine: expose some endpoints through HTTP (OpenAPI) and mount a FastAPI‑wrapped MCP for internal operations.
7 Limitations & Caveats
FastAPI middlewares that modify the raw ASGI send/receive flow (e.g. WebSocket) are ignored for MCP calls.
Background tasks run inside the MCP event‑loop—monitor memory.
Proprietary Response classes (FileResponse, RedirectResponse) map to simple
TextContent
with their.body
string or URL.Multipart form file uploads require the client to supply base64 blobs; binary passthrough coming in v2.6.
8 Troubleshooting
RuntimeError: FastAPI not installed
dependency missing
pip install fastapi
422 errors when tool called
Validation failed on pydantic model
check arg names & types; they must match FastAPI signature
Tool returns null
Endpoint returned Response(status_code=204)
Upgrade to v2.5 (maps 204 → empty list)
Last updated