Skip to content

Feature/use request context #191

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
22 changes: 15 additions & 7 deletions fastapi_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,7 @@ def decorator(

async def handler(req: types.CallToolRequest):
try:
# Pull the original HTTP request info from the MCP message. It was injected in
# `FastApiSseTransport.handle_fastapi_post_message()`
if hasattr(req.params, "_http_request_info") and req.params._http_request_info is not None:
http_request_info = HTTPRequestInfo.model_validate(req.params._http_request_info)
results = await func(req.params.name, (req.params.arguments or {}), http_request_info)
else:
results = await func(req.params.name, (req.params.arguments or {}))
results = await func(req.params.name, (req.params.arguments or {}))
return types.ServerResult(types.CallToolResult(content=list(results), isError=False))
except Exception as e:
return types.ServerResult(
Expand Down Expand Up @@ -177,6 +171,20 @@ async def handle_list_tools() -> List[types.Tool]:
async def handle_call_tool(
name: str, arguments: Dict[str, Any], http_request_info: Optional[HTTPRequestInfo] = None
) -> List[Union[types.TextContent, types.ImageContent, types.EmbeddedResource]]:
request = self.server.request_context.request

http_request_info = None
if request:
body = await request.body()
http_request_info = HTTPRequestInfo(
method=request.method,
path=request.url.path,
headers=dict(request.headers),
cookies=request.cookies,
query_params=dict(request.query_params),
body=body.decode(),
)

return await self._execute_api_tool(
client=self._http_client,
tool_name=name,
Expand Down
15 changes: 0 additions & 15 deletions fastapi_mcp/transport/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from pydantic import ValidationError
from mcp.server.sse import SseServerTransport
from mcp.types import JSONRPCMessage, JSONRPCError, ErrorData
from fastapi_mcp.types import HTTPRequestInfo


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -59,20 +58,6 @@ async def handle_fastapi_post_message(self, request: Request) -> Response:

try:
message = JSONRPCMessage.model_validate_json(body)

# HACK to inject the HTTP request info into the MCP message,
# so we can use it for auth.
# It is then used in our custom `LowlevelMCPServer.call_tool()` decorator.
if hasattr(message.root, "params") and message.root.params is not None:
message.root.params["_http_request_info"] = HTTPRequestInfo(
method=request.method,
path=request.url.path,
headers=dict(request.headers),
cookies=request.cookies,
query_params=dict(request.query_params),
body=body.decode(),
).model_dump(mode="json")

logger.debug(f"Validated client message: {message}")
except ValidationError as err:
logger.error(f"Failed to parse message: {err}")
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ dependencies = [
"fastapi>=0.100.0",
"typer>=0.9.0",
"rich>=13.0.0",
"mcp>=1.8.1",
"mcp>=1.10.1",
"pydantic>=2.0.0",
"pydantic-settings>=2.5.2",
"uvicorn>=0.20.0",
Expand Down
Loading