🚀 The fast, Pythonic way to build MCP servers and clients.
update docs
Jeremiah Lowin526f1993c24d
diff --git a/README.md b/README.mdindex 387b50437..a27c58fa5 100644--- a/README.md+++ b/README.md@@ -93,7 +93,7 @@ FastMCP provides a high-level, Pythonic interface for building and interacting w## Why FastMCP?-The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It’s designed to be high-level and Pythonic; in most cases, decorating a function is all you need.+The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic; in most cases, decorating a function is all you need.FastMCP aims to be:@@ -552,13 +552,13 @@ proxy_client = Client()# Create a proxy server that connects to the client and exposes its capabilities-proxy = FastMCP.as_proxy(proxy_client, name="Stdio-to-SSE Proxy")+proxy = FastMCP.from_client(proxy_client, name="Stdio-to-SSE Proxy")if __name__ == "__main__":proxy.run(transport='sse')```-`FastMCP.as_proxy` is an `async` classmethod. It connects to the target, discovers its capabilities, and dynamically builds the proxy server instance.+`FastMCP.from_client` is a class method that connects to the target, discovers its capabilities, and dynamically builds the proxy server instance.diff --git a/docs/clients/overview.mdx b/docs/clients/overview.mdxindex 7f4212f08..5a381ff68 100644--- a/docs/clients/overview.mdx+++ b/docs/clients/overview.mdx@@ -248,5 +248,5 @@ async def safe_call_tool():Other errors, like connection failures, will raise standard Python exceptions (e.g., `ConnectionError`, `TimeoutError`).<Tip>-The client transport often has its own error-handling mechanisms, so you can not always trap errors like those raised by `call_tool` outside of the `async with` block. Instead, you can call `call_tools(..., return_raw_result=True)` to get the raw result object and handle errors yourself by checking its `isError` attribute.+The client transport often has its own error-handling mechanisms, so you can not always trap errors like those raised by `call_tool` outside of the `async with` block. Instead, you can call `call_tool(..., _return_raw_result=True)` to get the raw `mcp.types.CallToolResult` object and handle errors yourself by checking its `isError` attribute.</Tip>diff --git a/docs/patterns/composition.mdx b/docs/patterns/composition.mdxindex f9a531372..d00522595 100644--- a/docs/patterns/composition.mdx+++ b/docs/patterns/composition.mdx@@ -1,11 +1,14 @@---title: Server CompositionsidebarTitle: Composition-description: Combine multiple FastMCP servers into a single, larger application using mounting.+description: Combine multiple FastMCP servers into a single, larger application using mounting and importing.icon: puzzle-piece----As your MCP applications grow, you might want to organize your tools, resources, and prompts into logical modules or reuse existing server components. FastMCP supports composition through the `server.mount()` method, allowing you to combine multiple `FastMCP` instances into a single, unified server.+As your MCP applications grow, you might want to organize your tools, resources, and prompts into logical modules or reuse existing server components. FastMCP supports composition through two methods:++- **`import_server`**: For a one-time copy of components with prefixing (static composition).+- **`mount`**: For creating a live link where the main server delegates requests to the subserver (dynamic composition).## Why Compose Servers?@@ -14,13 +17,14 @@ As your MCP applications grow, you might want to organize your tools, resources,- **Teamwork**: Different teams can work on separate FastMCP servers that are later combined.- **Organization**: Keep related functionality grouped together logically.-## Mounting Subservers+## Importing Subservers (Static Composition)-The `mount()` method attaches all components (tools, resources, templates, prompts) from one `FastMCP` instance (the *subserver*) onto another (the *main server*). A `prefix` is added to avoid naming conflicts.+The `import_server()` method copies all components (tools, resources, templates, prompts) from one `FastMCP` instance (the *subserver*) into another (the *main server*). A `prefix` is added to avoid naming conflicts.```pythonfrom fastmcp import FastMCPfrom typing import dict, list+import asyncio# --- Define Subservers ---@@ -53,14 +57,15 @@ def explain_addition() -> str:# --- Define Main Server ---main_mcp = FastMCP(name="MainApp")-# --- Mount Subservers ----# Mount weather service with prefix "weather"-main_mcp.mount("weather", weather_mcp)+# --- Import Subservers ---+async def setup():+ # Import weather service with prefix "weather"+ await main_mcp.import_server("weather", weather_mcp)-# Mount calculator service with prefix "calc"-main_mcp.mount("calc", calc_mcp)+ # Import calculator service with prefix "calc"+ await main_mcp.import_server("calc", calc_mcp)-# --- Now, main_mcp contains combined components ---+# --- Now, main_mcp contains *copied* components ---# Tools:# - "weather_get_forecast"# - "calc_add"@@ -70,13 +75,15 @@ main_mcp.mount("calc", calc_mcp)# - "calc_explain_addition"if __name__ == "__main__":+ # In a real app, you might run this async or setup imports differently+ asyncio.run(setup())# Run the main server, which now includes components from both subserversmain_mcp.run()```-### How Mounting Works+### How Importing Works-When you call `main_mcp.mount(prefix, subserver)`:+When you call `await main_mcp.import_server(prefix, subserver)`:1. **Tools**: All tools from `subserver` are added to `main_mcp`. Their names are automatically prefixed using the `prefix` and a default separator (`_`).- `subserver.tool(name="my_tool")` becomes `main_mcp.tool(name="{prefix}_my_tool")`.@@ -86,14 +93,15 @@ When you call `main_mcp.mount(prefix, subserver)`:- `subserver.resource(uri="data://{id}")` becomes `main_mcp.resource(uri="{prefix}+data://{id}")`.4. **Prompts**: All prompts from `subserver` are added, with names prefixed like tools.- `subserver.prompt(name="my_prompt")` becomes `main_mcp.prompt(name="{prefix}_my_prompt")`.-5. **Lifespan Management**: If the `subserver` has a `lifespan` function defined, it will be automatically executed within the `main_mcp`'s lifespan context. This ensures that setup and teardown logic for the subserver runs correctly.++Note that `import_server` performs a **one-time copy** of components from the `subserver` into the `main_mcp` instance at the time the method is called. Changes made to the `subserver` *after* `import_server` is called **will not** be reflected in `main_mcp`. Also, the `subserver`'s `lifespan` context is **not** executed by the main server when using `import_server`.### Customizing Separators-You might prefer different separators for the prefixed names and URIs. You can customize these when calling `mount()`:+You might prefer different separators for the prefixed names and URIs. You can customize these when calling `import_server()`:```python-main_mcp.mount(+await main_mcp.import_server(prefix="api",app=some_subserver,tool_separator="/", # Tool name becomes: "api/sub_tool_name"@@ -106,8 +114,92 @@ main_mcp.mount(Be cautious when choosing separators. Some MCP clients (like Claude Desktop) might have restrictions on characters allowed in tool names (e.g., `/` might not be supported). The defaults (`_` for names, `+` for URIs) are generally safe.</Warning>+## Mounting Subservers (Live Linking)++The `mount()` method creates a **live link** between the `main_mcp` server and the `subserver`. Instead of copying components, requests for components matching the `prefix` are **delegated** to the `subserver` at runtime.++```python+import asyncio+from fastmcp import FastMCP, Client++# --- Define Subserver ---+dynamic_mcp = FastMCP(name="DynamicService")+@dynamic_mcp.tool()+def initial_tool(): return "Initial Tool Exists"++# --- Define Main Server ---+main_mcp = FastMCP(name="MainAppLive")++# --- Mount Subserver (Sync operation) ---+main_mcp.mount("dynamic", dynamic_mcp)++print("Mounted dynamic_mcp.")++# --- Add a tool AFTER mounting ---+@dynamic_mcp.tool()+def added_later(): return "Tool Added Dynamically!"++print("Added 'added_later' tool to dynamic_mcp.")++# --- Test Access ---+async def test_dynamic_mount():+ # Need to use await for get_tools now+ tools_before = await main_mcp.get_tools()+ print("Tools available via main_mcp:", list(tools_before.keys()))+ # Expected: ['dynamic_initial_tool', 'dynamic_added_later']++ async with Client(main_mcp) as client:+ # Call the dynamically added tool via the main server+ result = await client.call_tool("dynamic_added_later")+ print("Result of calling dynamic_added_later:", result[0].text)+ # Expected: Tool Added Dynamically!++if __name__ == "__main__":+ # Need async context to test+ asyncio.run(test_dynamic_mount())+ # To run the server itself:+ # main_mcp.run()+```++### How Mounting Works++When you call `main_mcp.mount(prefix, server)`:++1. **Live Link**: A live connection is established between `main_mcp` and the `subserver`.+2. **Dynamic Updates**: Changes made to the `subserver` (e.g., adding new tools) **will be reflected** immediately when accessing components through `main_mcp`.+3. **Lifespan Management**: The `subserver`'s `lifespan` context **is automatically managed** and executed within the `main_mcp`'s lifespan.+4. **Delegation**: Requests for components matching the prefix are delegated to the subserver at runtime.++The same prefixing rules apply as with `import_server` for naming tools, resources, templates, and prompts.++### Customizing Separators++Similar to `import_server`, you can customize the separators for the prefixed names and URIs:++```python+main_mcp.mount(+ prefix="api",+ app=some_subserver,+ tool_separator="/", # Tool name becomes: "api/sub_tool_name"+ resource_separator=":", # Resource URI becomes: "api:data://sub_resource"+ prompt_separator="." # Prompt name becomes: "api.sub_prompt_name"+)+```++## Comparing Import and Mount++| Feature | `import_server` | `mount` |+|---------|----------------|---------|+| **Synchronicity** | Async (must be awaited) | Sync |+| **Composition Type** | One-time copy (static) | Live link (dynamic) |+| **Updates** | Changes to subserver NOT reflected | Changes to subserver immediately reflected |+| **Lifespan** | Not managed | Automatically managed |+| **Best For** | Bundling finalized components | Modular runtime composition |+## Example: Modular Application+Here's how a modular application might use `import_server`:+```python# modules/text_utils.pyfrom fastmcp import FastMCP@@ -146,20 +238,23 @@ def get_table_schema(table: str) -> dict:# ------------------------------# main_app.pyfrom fastmcp import FastMCP+import asynciofrom modules.text_utils import text_mcp # Import server instancesfrom modules.data_api import data_mcpapp = FastMCP(name="MainApplication")-# Mount the utility servers-app.mount("text", text_mcp)-app.mount("data", data_mcp)+# Setup function for async imports+async def setup():+ # Import the utility servers+ await app.import_server("text", text_mcp)+ await app.import_server("data", data_mcp)@app.tool()def process_and_analyze(record_id: int) -> str:"""Fetches a record and analyzes its string representation."""# In a real application, you'd use proper methods to interact between- # mounted tools rather than accessing internal managers+ # imported tools rather than accessing internal managers# Get record datarecord = {"id": record_id, "value": random.random()}@@ -173,6 +268,9 @@ def process_and_analyze(record_id: int) -> str:)if __name__ == "__main__":+ # Run async setup before starting the server+ asyncio.run(setup())+ # Run the serverapp.run()```diff --git a/docs/patterns/proxying.mdx b/docs/patterns/proxying.mdxindex d880b95b2..e0204446e 100644--- a/docs/patterns/proxying.mdx+++ b/docs/patterns/proxying.mdx@@ -5,7 +5,7 @@ description: Use FastMCP to act as an intermediary or change transport for othericon: arrows-retweet----FastMCP provides a powerful proxying capability that allows one FastMCP server instance to act as a frontend for another MCP server (which could be remote, running on a different transport, or even another FastMCP instance). This is achieved using the `FastMCP.as_proxy()` class method.+FastMCP provides a powerful proxying capability that allows one FastMCP server instance to act as a frontend for another MCP server (which could be remote, running on a different transport, or even another FastMCP instance). This is achieved using the `FastMCP.from_client()` class method.## What is Proxying?@@ -32,7 +32,7 @@ sequenceDiagram## Creating a Proxy-The easiest way to create a proxy is using the `FastMCP.as_proxy()` class method. This creates a standard FastMCP server that forwards requests to another MCP server.+The easiest way to create a proxy is using the `FastMCP.from_client()` class method. This creates a standard FastMCP server that forwards requests to another MCP server.```pythonfrom fastmcp import FastMCP, Client@@ -41,8 +41,8 @@ from fastmcp import FastMCP, Client# This could be any MCP server - remote, local, or using any transportbackend_client = Client("backend_server.py") # Could be "http://remote.server/sse", etc.-# Create the proxy server with as_proxy()-proxy_server = await FastMCP.as_proxy(+# Create the proxy server with from_client()+proxy_server = FastMCP.from_client(backend_client,name="MyProxyServer" # Optional settings for the proxy)@@ -51,13 +51,17 @@ proxy_server = await FastMCP.as_proxy(# with any transport (SSE, stdio, etc.) just like any other FastMCP server```-**How `as_proxy` Works:**+**How `from_client` Works:**1. It connects to the backend server using the provided client.2. It discovers all the tools, resources, resource templates, and prompts available on the backend server.3. It creates corresponding "proxy" components that forward requests to the backend.4. It returns a standard `FastMCP` server instance that can be used like any other.+<Note>+Currently, proxying focuses primarily on exposing the major MCP objects (tools, resources, templates, and prompts). Some advanced MCP features like notifications and sampling are not fully supported in proxies in the current version. Support for these additional features may be added in future releases.+</Note>+### Bridging TransportsA common use case is to bridge transports. For example, making a remote SSE server available locally via Stdio:@@ -69,7 +73,7 @@ from fastmcp import FastMCP, Clientclient = Client("http://example.com/mcp/sse")# Create a proxy server - it's just a regular FastMCP server-proxy = await FastMCP.as_proxy(client, name="SSE to Stdio Proxy")+proxy = FastMCP.from_client(client, name="SSE to Stdio Proxy")# The proxy can now be used with any transport# No special handling needed - it works like any FastMCP server@@ -90,7 +94,7 @@ def tool_a() -> str:return "A"# Create a proxy of the original server-proxy = await FastMCP.as_proxy(+proxy = FastMCP.from_client(original_server,name="Proxy Server")@@ -101,9 +105,6 @@ proxy = await FastMCP.as_proxy(## `FastMCPProxy` Class-Internally, `FastMCP.as_proxy()` uses the `FastMCPProxy` class. You generally don't need to interact with this class directly, but it's available if needed. It has two primary async constructors:--* `FastMCPProxy.from_client(client: Client, **settings)`: Creates a proxy from a client instance.-* `FastMCPProxy.from_server(server: FastMCP, **settings)`: Creates a proxy from another FastMCP server instance.+Internally, `FastMCP.from_client()` uses the `FastMCPProxy` class. You generally don't need to interact with this class directly, but it's available if needed.Using the class directly might be necessary for advanced scenarios, like subclassing `FastMCPProxy` to add custom logic before or after forwarding requests.\ No newline at end of filediff --git a/docs/servers/fastmcp.mdx b/docs/servers/fastmcp.mdxindex d950dcea0..d07cc219d 100644--- a/docs/servers/fastmcp.mdx+++ b/docs/servers/fastmcp.mdx@@ -223,17 +223,22 @@ fastmcp run my_server.py:mcp --transport sse --log-level DEBUGThe CLI can dynamically find and run FastMCP server objects in your files, but including the `if __name__ == "__main__":` block ensures compatibility with all clients.+## Composing Servers-## Mounting Subservers+FastMCP provides two methods for composing multiple servers together:-FastMCP allows you to compose complex applications by mounting other FastMCP servers as subservers. This is useful for:+1. `import_server()`: One-time static import of components (async)+2. `mount()`: Live link delegating to subservers (sync)-- Organizing large applications into logical components-- Reusing existing FastMCP servers as parts of a larger system-- Creating domain-specific servers that can be used independently or composed+This allows you to organize large applications into logical components, reuse existing FastMCP servers, and create domain-specific servers that can be used independently or composed.++### Importing Subservers (Static Composition)++The `import_server()` method performs a one-time copy of all components from a subserver into the main server with prefixed names:```pythonfrom fastmcp import FastMCP+import asyncio# Create the main servermain_mcp = FastMCP(name="MainServer")@@ -254,54 +259,125 @@ def add(a: float, b: float) -> float:"""Add two numbers."""return a + b-# Mount the subservers with prefixes-main_mcp.mount("weather", weather_mcp)-main_mcp.mount("calc", calculator_mcp)+# Import the subservers with prefixes+async def setup():+ await main_mcp.import_server("weather", weather_mcp)+ await main_mcp.import_server("calc", calculator_mcp)# Now main_mcp has access to both subservers' tools:# - "weather_get_forecast" (from weather_mcp)# - "calc_add" (from calculator_mcp)if __name__ == "__main__":+ # Run async setup+ asyncio.run(setup())+ # Then run the servermain_mcp.run()```-### How Mounting Works+#### How Import Works-When you mount a server with `main_mcp.mount(prefix, subserver)`:+When you import a server with `await main_mcp.import_server(prefix, subserver)`:-1. All tools from the subserver are imported with prefixed names:+1. All tools from the subserver are copied with prefixed names:- `tool_name` becomes `{prefix}_tool_name`- Default separator is `_`, but can be customized-2. All resources and resource templates are imported with prefixed URIs:+2. All resources and resource templates are copied with prefixed URIs:- `resource://data` becomes `{prefix}+resource://data`- Default separator is `+`, but can be customized-3. All prompts are imported with prefixed names:+3. All prompts are copied with prefixed names:- `prompt_name` becomes `{prefix}_prompt_name`- Default separator is `_`, but can be customized-4. The subserver's lifespan is managed automatically when the main server starts and stops+4. This is a **one-time copy** - changes to the subserver after importing won't be reflected in the main server++5. The subserver's lifespan is **not** managed by the main server++### Mounting Subservers (Live Linking)++The `mount()` method creates a live link between servers, delegating requests to the appropriate subserver:++```python+from fastmcp import FastMCP++# Create the main server+main_mcp = FastMCP(name="MainServer")++# Create a domain-specific subserver+weather_mcp = FastMCP(name="WeatherService")++@weather_mcp.tool()+def get_forecast(city: str) -> dict:+ """Get the weather forecast for a city."""+ return {"city": city, "forecast": "Sunny", "temperature": 72}++# Mount the subserver (sync operation)+main_mcp.mount("weather", weather_mcp)++# Later, add another tool to the subserver+@weather_mcp.tool()+def get_temperature(city: str) -> float:+ """Get the current temperature for a city."""+ return 72.5 # Example value++# The new tool is automatically available through the main server+# as "weather_get_temperature"++if __name__ == "__main__":+ main_mcp.run()+```++#### How Mounting Works++When you mount a server with `main_mcp.mount(prefix, subserver)`:++1. A live link is created between the main server and the subserver+2. Requests for components matching the prefix are delegated to the subserver+3. Changes to the subserver are **immediately reflected** when accessing through the main server+4. The subserver's lifespan **is automatically managed** by the main server### Customizing Separators-You can customize the separators used for naming:+For both `import_server()` and `mount()`, you can customize the separators used for naming:```python-main_mcp.mount(+# For import_server (async)+await main_mcp.import_server("weather",weather_mcp,tool_separator="-", # Use "weather-get_forecast" instead of "weather_get_forecast"resource_separator=".", # Use "weather.resource://data" instead of "weather+resource://data"prompt_separator=":" # Use "weather:prompt_name" instead of "weather_prompt_name")++# For mount (sync)+main_mcp.mount(+ "weather",+ weather_mcp,+ tool_separator="-",+ resource_separator=".",+ prompt_separator=":"+)```<Warning>Some MCP clients may reject certain separators as invalid. For example, Claude Desktop does not support `/` in tool names.</Warning>+### Comparison++| Feature | `import_server()` | `mount()` |+|---------|------------------|-----------|+| **Synchronicity** | Async (must be awaited) | Sync |+| **Composition Type** | One-time copy (static) | Live link (dynamic) |+| **Updates** | Changes to subserver NOT reflected | Changes immediately reflected |+| **Lifespan** | Not managed | Automatically managed |+| **Best For** | Bundling finalized components | Modular runtime composition |++For more detailed examples, see the [Server Composition](/patterns/composition) guide.+## Server ConfigurationServer behavior, like transport settings (host, port for SSE) and how duplicate components are handled, can be configured via `ServerSettings`. These settings can be passed during `FastMCP` initialization, set via environment variables (prefixed with `FASTMCP_SERVER_`), or loaded from a `.env` file.