diff --git a/docs/python-sdk/fastmcp-server-server.mdx b/docs/python-sdk/fastmcp-server-server.mdx
index ae1052a68..6fe769771 100644
--- a/docs/python-sdk/fastmcp-server-server.mdx
+++ b/docs/python-sdk/fastmcp-server-server.mdx
@@ -26,7 +26,7 @@ Default lifespan context manager that does nothing.
- An empty context object
-### `add_resource_prefix`
+### `add_resource_prefix`
```python
add_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str
@@ -64,7 +64,7 @@ add_resource_prefix("resource:///absolute/path", "prefix")
- `ValueError`: If the URI doesn't match the expected protocol\://path format
-### `remove_resource_prefix`
+### `remove_resource_prefix`
```python
remove_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str
@@ -103,7 +103,7 @@ remove_resource_prefix("resource://prefix//absolute/path", "prefix")
- `ValueError`: If the URI doesn't match the expected protocol\://path format
-### `has_resource_prefix`
+### `has_resource_prefix`
```python
has_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> bool
@@ -147,31 +147,31 @@ False
**Methods:**
-#### `settings`
+#### `settings`
```python
settings(self) -> Settings
```
-#### `name`
+#### `name`
```python
name(self) -> str
```
-#### `instructions`
+#### `instructions`
```python
instructions(self) -> str | None
```
-#### `version`
+#### `version`
```python
version(self) -> str | None
```
-#### `run_async`
+#### `run_async`
```python
run_async(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None
@@ -183,7 +183,7 @@ Run the FastMCP server asynchronously.
- `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http")
-#### `run`
+#### `run`
```python
run(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None
@@ -195,13 +195,13 @@ Run the FastMCP server. Note this is a synchronous function.
- `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http")
-#### `add_middleware`
+#### `add_middleware`
```python
add_middleware(self, middleware: Middleware) -> None
```
-#### `get_tools`
+#### `get_tools`
```python
get_tools(self) -> dict[str, Tool]
@@ -210,13 +210,13 @@ get_tools(self) -> dict[str, Tool]
Get all registered tools, indexed by registered key.
-#### `get_tool`
+#### `get_tool`
```python
get_tool(self, key: str) -> Tool
```
-#### `get_resources`
+#### `get_resources`
```python
get_resources(self) -> dict[str, Resource]
@@ -225,13 +225,13 @@ get_resources(self) -> dict[str, Resource]
Get all registered resources, indexed by registered key.
-#### `get_resource`
+#### `get_resource`
```python
get_resource(self, key: str) -> Resource
```
-#### `get_resource_templates`
+#### `get_resource_templates`
```python
get_resource_templates(self) -> dict[str, ResourceTemplate]
@@ -240,7 +240,7 @@ get_resource_templates(self) -> dict[str, ResourceTemplate]
Get all registered resource templates, indexed by registered key.
-#### `get_resource_template`
+#### `get_resource_template`
```python
get_resource_template(self, key: str) -> ResourceTemplate
@@ -249,7 +249,7 @@ get_resource_template(self, key: str) -> ResourceTemplate
Get a registered resource template by key.
-#### `get_prompts`
+#### `get_prompts`
```python
get_prompts(self) -> dict[str, Prompt]
@@ -258,13 +258,13 @@ get_prompts(self) -> dict[str, Prompt]
List all available prompts.
-#### `get_prompt`
+#### `get_prompt`
```python
get_prompt(self, key: str) -> Prompt
```
-#### `custom_route`
+#### `custom_route`
```python
custom_route(self, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True) -> Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]]
@@ -285,7 +285,7 @@ Starlette's reverse URL lookup feature)
- `include_in_schema`: Whether to include in OpenAPI schema, defaults to True
-#### `add_tool`
+#### `add_tool`
```python
add_tool(self, tool: Tool) -> Tool
@@ -303,7 +303,7 @@ with the Context type annotation. See the @tool decorator for examples.
- The tool instance that was added to the server.
-#### `remove_tool`
+#### `remove_tool`
```python
remove_tool(self, name: str) -> None
@@ -318,7 +318,7 @@ Remove a tool from the server.
- `NotFoundError`: If the tool is not found
-#### `add_tool_transformation`
+#### `add_tool_transformation`
```python
add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfig) -> None
@@ -327,7 +327,7 @@ add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfi
Add a tool transformation.
-#### `remove_tool_transformation`
+#### `remove_tool_transformation`
```python
remove_tool_transformation(self, tool_name: str) -> None
@@ -336,19 +336,19 @@ remove_tool_transformation(self, tool_name: str) -> None
Remove a tool transformation.
-#### `tool`
+#### `tool`
```python
tool(self, name_or_fn: AnyFunction) -> FunctionTool
```
-#### `tool`
+#### `tool`
```python
tool(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionTool]
```
-#### `tool`
+#### `tool`
```python
tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool
@@ -404,7 +404,7 @@ server.tool(my_function, name="custom_name")
```
-#### `add_resource`
+#### `add_resource`
```python
add_resource(self, resource: Resource) -> Resource
@@ -419,7 +419,7 @@ Add a resource to the server.
- The resource instance that was added to the server.
-#### `add_template`
+#### `add_template`
```python
add_template(self, template: ResourceTemplate) -> ResourceTemplate
@@ -434,7 +434,7 @@ Add a resource template to the server.
- The template instance that was added to the server.
-#### `add_resource_fn`
+#### `add_resource_fn`
```python
add_resource_fn(self, fn: AnyFunction, uri: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None) -> None
@@ -454,7 +454,7 @@ has parameters, it will be registered as a template resource.
- `tags`: Optional set of tags for categorizing the resource
-#### `resource`
+#### `resource`
```python
resource(self, uri: str) -> Callable[[AnyFunction], Resource | ResourceTemplate]
@@ -514,7 +514,7 @@ async def get_weather(city: str) -> str:
```
-#### `add_prompt`
+#### `add_prompt`
```python
add_prompt(self, prompt: Prompt) -> Prompt
@@ -529,19 +529,19 @@ Add a prompt to the server.
- The prompt instance that was added to the server.
-#### `prompt`
+#### `prompt`
```python
prompt(self, name_or_fn: AnyFunction) -> FunctionPrompt
```
-#### `prompt`
+#### `prompt`
```python
prompt(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionPrompt]
```
-#### `prompt`
+#### `prompt`
```python
prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt
@@ -619,7 +619,7 @@ Decorator to register a prompt.
```
-#### `run_stdio_async`
+#### `run_stdio_async`
```python
run_stdio_async(self, show_banner: bool = True) -> None
@@ -628,7 +628,7 @@ run_stdio_async(self, show_banner: bool = True) -> None
Run the server using stdio transport.
-#### `run_http_async`
+#### `run_http_async`
```python
run_http_async(self, show_banner: bool = True, transport: Literal['http', 'streamable-http', 'sse'] = 'http', host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None, middleware: list[ASGIMiddleware] | None = None, stateless_http: bool | None = None) -> None
@@ -647,7 +647,7 @@ Run the server using HTTP transport.
- `stateless_http`: Whether to use stateless HTTP (defaults to settings.stateless_http)
-#### `run_sse_async`
+#### `run_sse_async`
```python
run_sse_async(self, host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None) -> None
@@ -656,7 +656,7 @@ run_sse_async(self, host: str | None = None, port: int | None = None, log_level:
Run the server using SSE transport.
-#### `sse_app`
+#### `sse_app`
```python
sse_app(self, path: str | None = None, message_path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan
@@ -670,7 +670,7 @@ Create a Starlette app for the SSE server.
- `middleware`: A list of middleware to apply to the app
-#### `streamable_http_app`
+#### `streamable_http_app`
```python
streamable_http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan
@@ -683,7 +683,7 @@ Create a Starlette app for the StreamableHTTP server.
- `middleware`: A list of middleware to apply to the app
-#### `http_app`
+#### `http_app`
```python
http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http') -> StarletteWithLifespan
@@ -700,13 +700,13 @@ Create a Starlette app using the specified HTTP transport.
- A Starlette application configured with the specified transport
-#### `run_streamable_http_async`
+#### `run_streamable_http_async`
```python
run_streamable_http_async(self, host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None) -> None
```
-#### `mount`
+#### `mount`
```python
mount(self, server: FastMCP[LifespanResultT], prefix: str | None = None, as_proxy: bool | None = None) -> None
@@ -760,7 +760,7 @@ automatically determined based on whether the server has a custom lifespan
- `prompt_separator`: Deprecated. Separator character for prompt names.
-#### `import_server`
+#### `import_server`
```python
import_server(self, server: FastMCP[LifespanResultT], prefix: str | None = None, tool_separator: str | None = None, resource_separator: str | None = None, prompt_separator: str | None = None) -> None
@@ -801,7 +801,7 @@ applied using the protocol\://prefix/path format
- `prompt_separator`: Deprecated. Separator for prompt names.
-#### `from_openapi`
+#### `from_openapi`
```python
from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route_maps: list[RouteMap] | list[RouteMapNew] | None = None, route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None, mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI | FastMCPOpenAPINew
@@ -810,7 +810,7 @@ from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route
Create a FastMCP server from an OpenAPI specification.
-#### `from_fastapi`
+#### `from_fastapi`
```python
from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | list[RouteMapNew] | None = None, route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None, mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI | FastMCPOpenAPINew
@@ -819,7 +819,7 @@ from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap]
Create a FastMCP server from a FastAPI application.
-#### `as_proxy`
+#### `as_proxy`
```python
as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy
@@ -833,7 +833,7 @@ instance or any value accepted as the `transport` argument of
`fastmcp.client.Client` constructor.
-#### `from_client`
+#### `from_client`
```python
from_client(cls, client: Client[ClientTransportT], **settings: Any) -> FastMCPProxy
@@ -842,4 +842,4 @@ from_client(cls, client: Client[ClientTransportT], **settings: Any) -> FastMCPPr
Create a FastMCP proxy server from a FastMCP client.
-### `MountedServer`
+### `MountedServer`
diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdx
index f720b672a..60714c992 100644
--- a/docs/servers/composition.mdx
+++ b/docs/servers/composition.mdx
@@ -310,4 +310,8 @@ server = FastMCP("LegacyServer", resource_prefix_format="protocol")
server = FastMCP("NewServer", resource_prefix_format="path")
```
-When mounting or importing servers, the prefix format of the parent server is used.
\ No newline at end of file
+When mounting or importing servers, the prefix format of the parent server is used.
+
+
+When mounting servers, custom HTTP routes defined with `@server.custom_route()` are also forwarded to the parent server, making them accessible through the parent's HTTP application.
+
diff --git a/src/fastmcp/server/http.py b/src/fastmcp/server/http.py
index 83da5752d..ad779b157 100644
--- a/src/fastmcp/server/http.py
+++ b/src/fastmcp/server/http.py
@@ -229,7 +229,7 @@ def create_sse_app(
# Add custom routes with lowest precedence
if routes:
server_routes.extend(routes)
- server_routes.extend(server._additional_http_routes)
+ server_routes.extend(server._get_additional_http_routes())
# Add middleware
if middleware:
@@ -331,7 +331,7 @@ def create_streamable_http_app(
# Add custom routes with lowest precedence
if routes:
server_routes.extend(routes)
- server_routes.extend(server._additional_http_routes)
+ server_routes.extend(server._get_additional_http_routes())
# Add middleware
if middleware:
diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py
index 40a5159dd..e245a99ed 100644
--- a/src/fastmcp/server/server.py
+++ b/src/fastmcp/server/server.py
@@ -172,6 +172,7 @@ class FastMCP(Generic[LifespanResultT]):
)
self._additional_http_routes: list[BaseRoute] = []
+ self._mounted_servers: list[MountedServer] = []
self._tool_manager = ToolManager(
duplicate_behavior=on_duplicate_tools,
mask_error_details=mask_error_details,
@@ -475,6 +476,24 @@ class FastMCP(Generic[LifespanResultT]):
return decorator
+ def _get_additional_http_routes(self) -> list[BaseRoute]:
+ """Get all additional HTTP routes including from mounted servers.
+
+ Returns a list of all custom HTTP routes from this server and
+ recursively from all mounted servers.
+
+ Returns:
+ List of Starlette BaseRoute objects
+ """
+ routes = list(self._additional_http_routes)
+
+ # Recursively get routes from mounted servers
+ for mounted_server in self._mounted_servers:
+ mounted_routes = mounted_server.server._get_additional_http_routes()
+ routes.extend(mounted_routes)
+
+ return routes
+
async def _mcp_list_tools(self) -> list[MCPTool]:
logger.debug("Handler called: list_tools")
@@ -1796,6 +1815,7 @@ class FastMCP(Generic[LifespanResultT]):
server=server,
resource_prefix_format=self.resource_prefix_format,
)
+ self._mounted_servers.append(mounted_server)
self._tool_manager.mount(mounted_server)
self._resource_manager.mount(mounted_server)
self._prompt_manager.mount(mounted_server)
diff --git a/tests/server/test_mount.py b/tests/server/test_mount.py
index 9fc642d9e..2defe3578 100644
--- a/tests/server/test_mount.py
+++ b/tests/server/test_mount.py
@@ -1019,3 +1019,125 @@ class TestResourceNamePrefixing:
# The template name should also be prefixed
template = templates["resource://prefix/user/{user_id}"]
assert template.name == "prefix_user_template"
+
+
+class TestCustomRouteForwarding:
+ """Test that custom HTTP routes from mounted servers are forwarded."""
+
+ async def test_get_additional_http_routes_empty(self):
+ """Test _get_additional_http_routes returns empty list for server with no routes."""
+ server = FastMCP("TestServer")
+ routes = server._get_additional_http_routes()
+ assert routes == []
+
+ async def test_get_additional_http_routes_with_custom_route(self):
+ """Test _get_additional_http_routes returns server's own routes."""
+ server = FastMCP("TestServer")
+
+ @server.custom_route("/test", methods=["GET"])
+ async def test_route(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "test"})
+
+ routes = server._get_additional_http_routes()
+ assert len(routes) == 1
+ assert routes[0].path == "/test" # type: ignore[attr-defined]
+
+ async def test_get_additional_http_routes_with_mounted_server(self):
+ """Test _get_additional_http_routes includes routes from mounted servers."""
+ main_server = FastMCP("MainServer")
+ sub_server = FastMCP("SubServer")
+
+ @sub_server.custom_route("/sub-route", methods=["GET"])
+ async def sub_route(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "from sub"})
+
+ # Mount the sub server
+ main_server.mount(sub_server, "sub")
+
+ routes = main_server._get_additional_http_routes()
+ assert len(routes) == 1
+ assert routes[0].path == "/sub-route" # type: ignore[attr-defined]
+
+ async def test_get_additional_http_routes_recursive(self):
+ """Test _get_additional_http_routes works recursively with nested mounts."""
+ main_server = FastMCP("MainServer")
+ sub_server = FastMCP("SubServer")
+ nested_server = FastMCP("NestedServer")
+
+ @main_server.custom_route("/main-route", methods=["GET"])
+ async def main_route(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "from main"})
+
+ @sub_server.custom_route("/sub-route", methods=["GET"])
+ async def sub_route(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "from sub"})
+
+ @nested_server.custom_route("/nested-route", methods=["GET"])
+ async def nested_route(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "from nested"})
+
+ # Create nested mounting: main -> sub -> nested
+ sub_server.mount(nested_server, "nested")
+ main_server.mount(sub_server, "sub")
+
+ routes = main_server._get_additional_http_routes()
+
+ # Should include all routes
+ assert len(routes) == 3
+ route_paths = [route.path for route in routes] # type: ignore[attr-defined]
+ assert "/main-route" in route_paths
+ assert "/sub-route" in route_paths
+ assert "/nested-route" in route_paths
+
+ async def test_mounted_servers_tracking(self):
+ """Test that _mounted_servers list tracks mounted servers correctly."""
+ main_server = FastMCP("MainServer")
+ sub_server1 = FastMCP("SubServer1")
+ sub_server2 = FastMCP("SubServer2")
+
+ # Initially no mounted servers
+ assert len(main_server._mounted_servers) == 0
+
+ # Mount first server
+ main_server.mount(sub_server1, "sub1")
+ assert len(main_server._mounted_servers) == 1
+ assert main_server._mounted_servers[0].server == sub_server1
+ assert main_server._mounted_servers[0].prefix == "sub1"
+
+ # Mount second server
+ main_server.mount(sub_server2, "sub2")
+ assert len(main_server._mounted_servers) == 2
+ assert main_server._mounted_servers[1].server == sub_server2
+ assert main_server._mounted_servers[1].prefix == "sub2"
+
+ async def test_multiple_routes_same_server(self):
+ """Test that multiple custom routes from same server are all included."""
+ server = FastMCP("TestServer")
+
+ @server.custom_route("/route1", methods=["GET"])
+ async def route1(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "route1"})
+
+ @server.custom_route("/route2", methods=["POST"])
+ async def route2(request):
+ from starlette.responses import JSONResponse
+
+ return JSONResponse({"message": "route2"})
+
+ routes = server._get_additional_http_routes()
+ assert len(routes) == 2
+ route_paths = [route.path for route in routes] # type: ignore[attr-defined]
+ assert "/route1" in route_paths
+ assert "/route2" in route_paths