Skip to content

Commit e3692da

Browse files
committed
Expose fastapi-mcp
1 parent 00c3af2 commit e3692da

File tree

5 files changed

+62
-32
lines changed

5 files changed

+62
-32
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Python Workers: FastMCP Example
1+
# Python Workers: FastAPI-MCP Example
22

3-
This is an example of a Python Worker that uses the FastMCP package.
3+
This is an example of a Python Worker that uses the FastAPI-MCP package.
44

55
## Adding Packages
66

src/httpx_patch.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from httpx._transports.jsfetch import AsyncJavascriptFetchTransport
2+
3+
orig_handle_async_request = AsyncJavascriptFetchTransport.handle_async_request
4+
5+
async def handle_async_request(self, request):
6+
response = await orig_handle_async_request(self, request)
7+
# fix content-encoding headers because the javascript fetch handles that
8+
response.headers.update({"content-encoding": "identity"})
9+
return response
10+
11+
AsyncJavascriptFetchTransport.handle_async_request = handle_async_request

src/worker.py

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,63 @@
22
from workers import DurableObject
33
from logger import logger
44
import sys
5+
import httpx_patch # noqa: F401
56
sys.path.insert(0, "/session/metadata/vendor")
67
sys.path.insert(0, "/session/metadata")
78

89

9-
def setup_server():
10+
def setup_server(env):
11+
from fastapi import FastAPI, Request
12+
from pydantic import BaseModel
13+
from fastapi_mcp import FastApiMCP
1014
from exceptions import HTTPException, http_exception
11-
from mcp.server.fastmcp import FastMCP
12-
mcp = FastMCP("Demo")
13-
14-
@mcp.tool()
15-
def add(a: int, b: int) -> int:
16-
"""Add two numbers"""
17-
return a + b
18-
19-
@mcp.resource("greeting://{name}")
20-
def get_greeting(name: str) -> str:
21-
"""Get a personalized greeting"""
22-
return f"Hello, {name}!"
23-
24-
@mcp.tool()
25-
def calculate_bmi(weight_kg: float, height_m: float) -> float:
26-
"""Calculate BMI given weight in kg and height in meters"""
27-
return weight_kg / (height_m**2)
28-
29-
@mcp.prompt()
30-
def echo_prompt(message: str) -> str:
31-
"""Create an echo prompt"""
32-
return f"Please process this message: {message}"
33-
34-
app = mcp.sse_app()
15+
16+
app = FastAPI()
3517
app.add_exception_handler(HTTPException, http_exception)
18+
19+
mcp = FastApiMCP(app)
20+
21+
# Mount the MCP server directly to your FastAPI app
22+
mcp.mount()
23+
# Auto-generated operation_id (something like "read_user_users__user_id__get")
24+
@app.get("/")
25+
async def root():
26+
return {"message": "Hello, World!"}
27+
28+
@app.get("/env")
29+
async def root():
30+
return {"message": "Here is an example of getting an environment variable: " + env.MESSAGE}
31+
32+
class Item(BaseModel):
33+
name: str
34+
description: str | None = None
35+
price: float
36+
tax: float | None = None
37+
38+
@app.post("/items/")
39+
async def create_item(item: Item):
40+
return item
41+
42+
@app.put("/items/{item_id}")
43+
async def create_item(item_id: int, item: Item, q: str | None = None):
44+
result = {"item_id": item_id, **item.dict()}
45+
if q:
46+
result.update({"q": q})
47+
return result
48+
49+
@app.get("/items/{item_id}")
50+
async def read_item(item_id: int):
51+
return {"item_id": item_id}
52+
53+
mcp.setup_server()
3654
return mcp, app
3755

3856

3957
class FastMCPServer(DurableObject):
4058
def __init__(self, ctx, env):
4159
self.ctx = ctx
4260
self.env = env
43-
self.mcp, self.app = setup_server()
61+
self.mcp, self.app = setup_server(self.env)
4462

4563
async def call(self, request):
4664
import asgi

vendor.txt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
1-
mcp
2-
structlog
1+
fastapi-mcp
2+
fastapi
3+
pydantic
4+
structlog

wrangler.jsonc

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@
33
"main": "src/worker.py",
44
"compatibility_flags": [
55
"python_workers",
6-
"python_workers_durable_objects"
76
],
87
"compatibility_date": "2025-04-10",
98
"vars": {
10-
"API_HOST": "example.com"
9+
"MESSAGE": "hello world"
1110
},
1211
"rules": [
1312
{

0 commit comments

Comments
 (0)