-
Notifications
You must be signed in to change notification settings - Fork 554
mcp route adds POST request method #159
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
LTaooo
wants to merge
1
commit into
tadata-org:main
Choose a base branch
from
LTaooo:patch-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Waiting for this |
If you're in a hurry, you can overwrite the FastApiMCP class first. Or use this: https://github.com/jlowin/fastmcp |
@LTaooo Thank you, I just switched to fastmcp |
bumping this |
Any plan to merge this soon? Thanks! |
I need it also :/ |
We need it! |
For those who don't want to modify the code in their own repository, I recommend using the following monkey patching method. # demo.py
# author: Doiiars
# ... Other import statements ...
from fastapi_mcp import FastApiMCP
from fastapi_mcp.server import FastApiSseTransport
from fastapi import FastAPI, APIRouter, Request, params, Depends
from typing import Optional, Sequence
# ...
# --- Monkey Patching FastApiMCP ---
# 1. Define our own version, completely replacing the original implementation
def patched_register_mcp_connection_endpoint_sse(
self,
router: FastAPI | APIRouter,
transport: FastApiSseTransport,
mount_path: str,
dependencies: Optional[Sequence[params.Depends]],
):
"""
This is a patched version of _register_mcp_connection_endpoint_sse.
It replaces @router.get with @router.api_route(methods=["GET", "POST"])
and injects a custom dependency.
"""
logger.info(f"--- Patched function called! Registering route for MCP endpoint at '{mount_path}' (GET/POST) ---")
# --- Add your custom logic here ---
# For example, we can add a custom dependency for authentication or logging
async def custom_dependency(request: Request):
logger.info(f"MCP connection request from: {request.client.host}")
# You can add authentication logic here, and raise HTTPException if it fails
# Add our dependency to the existing list of dependencies
new_dependencies = list(dependencies) if dependencies else []
new_dependencies.append(Depends(custom_dependency))
logger.info("Custom dependency injected successfully.")
# ------------------------------------
# 2. Rewrite the route registration logic, using api_route and specifying methods
@router.api_route(
mount_path,
include_in_schema=False,
operation_id="mcp_connection",
dependencies=new_dependencies, # Use our modified dependencies
methods=["GET", "POST"]
)
async def handle_mcp_connection(request: Request):
async with transport.connect_sse(request.scope, request.receive, request._send) as (reader, writer):
await self.server.run(
reader,
writer,
self.server.create_initialization_options(notification_options=None, experimental_capabilities={}),
raise_exceptions=False,
)
logger.info(f"Successfully registered MCP endpoint to '{mount_path}' using methods GET, POST.")
# 3. Apply the patch: replace the original version with our patched version
FastApiMCP._register_mcp_connection_endpoint_sse = patched_register_mcp_connection_endpoint_sse
logger.info("FastApiMCP._register_mcp_connection_endpoint_sse has been successfully patched.")
# --- End of Monkey Patching ---
mcp = FastApiMCP(app)
# Mount the MCP server directly to your FastAPI app
mcp.mount()
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Describe your changes
mcp route adds POST request method
Issue ticket number and link (if applicable)
#154