@@ -159,11 +159,20 @@ def mount(self, router: Optional[FastAPI | APIRouter] = None, mount_path: str =
159159 if not router :
160160 router = self .fastapi
161161
162- # Create SSE transport for MCP messages
163- sse_transport = FastApiSseTransport (f"{ mount_path } /messages/" )
162+ # Build the base path correctly for the SSE transport
163+ if isinstance (router , FastAPI ):
164+ base_path = router .root_path
165+ elif isinstance (router , APIRouter ):
166+ base_path = self .fastapi .root_path + router .prefix
167+ else :
168+ raise ValueError (f"Invalid router type: { type (router )} " )
169+
170+ messages_path = f"{ base_path } { mount_path } /messages/"
171+
172+ sse_transport = FastApiSseTransport (messages_path )
164173
165174 # Route for MCP connection
166- @router .get (mount_path , include_in_schema = False )
175+ @router .get (mount_path , include_in_schema = False , operation_id = "mcp_connection" )
167176 async def handle_mcp_connection (request : Request ):
168177 async with sse_transport .connect_sse (request .scope , request .receive , request ._send ) as (reader , writer ):
169178 await self .server .run (
@@ -173,10 +182,18 @@ async def handle_mcp_connection(request: Request):
173182 )
174183
175184 # Route for MCP messages
176- @router .post (f"{ mount_path } /messages/" , include_in_schema = False )
185+ @router .post (f"{ mount_path } /messages/" , include_in_schema = False , operation_id = "mcp_messages" )
177186 async def handle_post_message (request : Request ):
178187 return await sse_transport .handle_fastapi_post_message (request )
179188
189+ # HACK: If we got a router and not a FastAPI instance, we need to re-include the router so that
190+ # FastAPI will pick up the new routes we added. The problem with this approach is that we assume
191+ # that the router is a sub-router of self.fastapi, which may not always be the case.
192+ #
193+ # TODO: Find a better way to do this.
194+ if isinstance (router , APIRouter ):
195+ self .fastapi .include_router (router )
196+
180197 logger .info (f"MCP server listening at { mount_path } " )
181198
182199 async def _execute_api_tool (
0 commit comments