Skip to content

use FastAPI's natively injected background_tasks instance instead of creating a new one #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions fastapi_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import httpx
from typing import Dict, Optional, Any, List, Union

from fastapi import FastAPI, Request, APIRouter
from fastapi import FastAPI, Request, APIRouter, BackgroundTasks
from fastapi.openapi.utils import get_openapi
from mcp.server.lowlevel.server import Server
import mcp.types as types
Expand Down Expand Up @@ -183,8 +183,8 @@

# Route for MCP messages
@router.post(f"{mount_path}/messages/", include_in_schema=False, operation_id="mcp_messages")
async def handle_post_message(request: Request):
return await sse_transport.handle_fastapi_post_message(request)
async def handle_post_message(request: Request, background_tasks: BackgroundTasks):
return await sse_transport.handle_fastapi_post_message(request, background_tasks)

Check warning on line 187 in fastapi_mcp/server.py

View check run for this annotation

Codecov / codecov/patch

fastapi_mcp/server.py#L187

Added line #L187 was not covered by tests

# HACK: If we got a router and not a FastAPI instance, we need to re-include the router so that
# FastAPI will pick up the new routes we added. The problem with this approach is that we assume
Expand Down
8 changes: 3 additions & 5 deletions fastapi_mcp/transport/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


class FastApiSseTransport(SseServerTransport):
async def handle_fastapi_post_message(self, request: Request) -> Response:
async def handle_fastapi_post_message(self, request: Request, background_tasks: BackgroundTasks) -> Response:
"""
A reimplementation of the handle_post_message method of SseServerTransport
that integrates better with FastAPI.
Expand Down Expand Up @@ -60,8 +60,7 @@ async def handle_fastapi_post_message(self, request: Request) -> Response:
logger.debug(f"Validated client message: {message}")
except ValidationError as err:
logger.error(f"Failed to parse message: {err}")
# Create background task to send error
background_tasks = BackgroundTasks()
# Create background task to send error, to avoid ASGI race conditions
background_tasks.add_task(self._send_message_safely, writer, err)
response = JSONResponse(content={"error": "Could not parse message"}, status_code=400)
response.background = background_tasks
Expand All @@ -70,8 +69,7 @@ async def handle_fastapi_post_message(self, request: Request) -> Response:
logger.error(f"Error processing request body: {e}")
raise HTTPException(status_code=400, detail="Invalid request body")

# Create background task to send message
background_tasks = BackgroundTasks()
# Create background task to send message, to avoid ASGI race conditions
background_tasks.add_task(self._send_message_safely, writer, message)
logger.debug("Accepting message, will send in background")

Expand Down