π The fast, Pythonic way to build MCP servers and clients.
[πΆ] Transform MCP Server Tools (#1132)
William Easton1b953820b3c2
diff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdxindex 8be8c26d4..78d488af4 100644--- a/docs/clients/transports.mdx+++ b/docs/clients/transports.mdx@@ -308,3 +308,75 @@ async with client:answer = await client.call_tool("assistant_ask", {"question": "What?"})```+### Tool Transformation with FastMCP and MCPConfig++FastMCP supports basic tool transformations to be defined alongside the MCP Servers in the MCPConfig file.++```python+config = {+ "mcpServers": {+ "weather": {+ "url": "https://weather.example.com/mcp",+ "transport": "http",+ "tools": { } # <--- This is the tool transformation section+ }+ }+}+```++With these transformations, you can transform (change) the name, title, description, tags, enablement, and arguments of a tool.++For each argument the tool takes, you can transform (change) the name, description, default, visibility, whether it's required, and you can provide example values.++In the following example, we're transforming the `weather_get_forecast` tool to only retrieve the weather for `Miami` and hiding the `city` argument from the client.++```python+tool_transformations = {+ "weather_get_forecast": {+ "name": "miami_weather",+ "description": "Get the weather for Miami",+ "arguments": {+ "city": {+ "name": "city",+ "default": "Miami",+ "hide": True,+ }+ }+ }+}++config = {+ "mcpServers": {+ "weather": {+ "url": "https://weather.example.com/mcp",+ "transport": "http",+ "tools": tool_transformations+ }+ }+}+```++#### Allowlisting and Blocklisting Tools++Tools can be allowlisted or blocklisted from the client by applying `tags` to the tools on the server. In the following example, we're allowlisting only tools marked with the `forecast` tag, all other tools will be unavailable to the client.++```python+tool_transformations = {+ "weather_get_forecast": {+ "enabled": True,+ "tags": ["forecast"]+ }+}+++config = {+ "mcpServers": {+ "weather": {+ "url": "https://weather.example.com/mcp",+ "transport": "http",+ "tools": tool_transformations,+ "include_tags": ["forecast"]+ }+ }+}+```\ No newline at end of filediff --git a/docs/patterns/tool-transformation.mdx b/docs/patterns/tool-transformation.mdxindex 17462fd50..753a28765 100644--- a/docs/patterns/tool-transformation.mdx+++ b/docs/patterns/tool-transformation.mdx@@ -441,6 +441,41 @@ mcp.add_tool(new_tool)In the above example, `**kwargs` receives the renamed argument `b`, not the original argument `y`. It is therefore recommended to use with `forward()`, not `forward_raw()`.</Tip>+## Modifying MCP Tools with MCPConfig++When running MCP Servers under FastMCP with `MCPConfig`, you can also apply a subset of tool transformations+directly in the MCPConfig json file.++```json+{+ "mcpServers": {+ "weather": {+ "url": "https://weather.example.com/mcp",+ "transport": "http",+ "tools": {+ "weather_get_forecast": {+ "name": "miami_weather",+ "description": "Get the weather for Miami",+ "arguments": {+ "city": {+ "name": "city",+ "default": "Miami",+ "hide": True,+ }+ }+ }+ }+ }+ }+}+```++The `tools` section is a dictionary of tool names to tool configurations. Each tool configuration is a+dictionary of tool properties.++See the [MCPConfigTransport](/clients/transports#tool-transformation-with-fastmcp-and-mcpconfig) documentation for more details.++## Output Schema Control<VersionBadge version="2.10.0" />diff --git a/src/fastmcp/client/transports.py b/src/fastmcp/client/transports.pyindex 8cf90dfff..2ecdcf8cc 100644--- a/src/fastmcp/client/transports.py+++ b/src/fastmcp/client/transports.py@@ -732,7 +732,7 @@ class MCPConfigTransport(ClientTransport):1. If the MCPConfig contains exactly one server, it creates a direct transport to that server.2. If the MCPConfig contains multiple servers, it creates a composite client by mounting- all servers on a single FastMCP instance, with each server's name used as its mounting prefix.+ all servers on a single FastMCP instance, with each server's name, by default, used as its mounting prefix.In the multi-server case, tools are accessible with the prefix pattern `{server_name}_{tool_name}`and resources with the pattern `protocol://{server_name}/path/to/resource`.@@ -772,7 +772,9 @@ class MCPConfigTransport(ClientTransport):```"""- def __init__(self, config: MCPConfig | dict):+ def __init__(self, config: MCPConfig | dict, name_as_prefix: bool = True):+ from fastmcp.utilities.mcp_config import composite_server_from_mcp_config+if isinstance(config, dict):config = MCPConfig.from_dict(config)self.config = config@@ -787,15 +789,11 @@ class MCPConfigTransport(ClientTransport):# otherwise create a composite clientelse:- composite_server = FastMCP()-- for name, server in self.config.mcpServers.items():- composite_server.mount(- prefix=name,- server=FastMCP.as_proxy(backend=server.to_transport()),+ self.transport = FastMCPTransport(+ mcp=composite_server_from_mcp_config(+ self.config, name_as_prefix=name_as_prefix)-- self.transport = FastMCPTransport(mcp=composite_server)+ )@contextlib.asynccontextmanagerasync def connect_session(diff --git a/src/fastmcp/mcp_config.py b/src/fastmcp/mcp_config.pyindex 029c802d1..8d5576ec5 100644--- a/src/fastmcp/mcp_config.py+++ b/src/fastmcp/mcp_config.py@@ -23,17 +23,29 @@ Example configuration:from __future__ import annotationsimport datetime-import jsonimport refrom pathlib import Pathfrom typing import TYPE_CHECKING, Annotated, Any, Literalfrom urllib.parse import urlparseimport httpx-from pydantic import AnyUrl, BaseModel, ConfigDict, Field+from pydantic import (+ AnyUrl,+ BaseModel,+ ConfigDict,+ Field,+ ValidationInfo,+ model_validator,+)+from typing_extensions import Self, override++from fastmcp.tools.tool_transform import ToolTransformConfig+from fastmcp.utilities.types import FastMCPBaseModelif TYPE_CHECKING:from fastmcp.client.transports import (+ ClientTransport,+ FastMCPTransport,SSETransport,StdioTransport,StreamableHttpTransport,@@ -60,6 +72,39 @@ def infer_transport_type_from_url(return "http"+class _TransformingMCPServerMixin(FastMCPBaseModel):+ """A mixin that enables wrapping an MCP Server with tool transforms."""++ tools: dict[str, ToolTransformConfig] = Field(...)+ """The multi-tool transform to apply to the tools."""++ include_tags: set[str] | None = Field(+ default=None,+ description="The tags to include in the proxy.",+ )++ exclude_tags: set[str] | None = Field(+ default=None,+ description="The tags to exclude in the proxy.",+ )++ def to_transport(self) -> FastMCPTransport:+ """Get the transport for the server."""+ from fastmcp.client.transports import FastMCPTransport+ from fastmcp.server.server import FastMCP++ transport: ClientTransport = super().to_transport() # pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue, reportUnknownVariableType]++ wrapped_mcp_server = FastMCP.as_proxy(+ transport,+ tool_transformations=self.tools,+ include_tags=self.include_tags,+ exclude_tags=self.exclude_tags,+ )++ return FastMCPTransport(wrapped_mcp_server)++class StdioMCPServer(BaseModel):"""MCP server configuration for stdio transport.@@ -101,6 +146,10 @@ class StdioMCPServer(BaseModel):)+class TransformingStdioMCPServer(_TransformingMCPServerMixin, StdioMCPServer):+ """A Stdio server with tool transforms."""++class RemoteMCPServer(BaseModel):"""MCP server configuration for HTTP/SSE transport.@@ -162,120 +211,106 @@ class RemoteMCPServer(BaseModel):)+class TransformingRemoteMCPServer(_TransformingMCPServerMixin, RemoteMCPServer):+ """A Remote server with tool transforms."""+++TransformingMCPServerTypes = TransformingStdioMCPServer | TransformingRemoteMCPServer++CanonicalMCPServerTypes = StdioMCPServer | RemoteMCPServer++MCPServerTypes = TransformingMCPServerTypes | CanonicalMCPServerTypes++class MCPConfig(BaseModel):- """Canonical MCP configuration format.+ """A configuration object for MCP Servers that conforms to the canonical MCP configuration format+ while adding additional fields for enabling FastMCP-specific features like tool transformations+ and filtering by tags.- This defines the standard configuration format for Model Context Protocol servers.- The format is designed to be client-agnostic and extensible for future use cases.+ For an MCPConfig that is strictly canonical, see the `CanonicalMCPConfig` class."""- mcpServers: dict[str, StdioMCPServer | RemoteMCPServer]+ mcpServers: dict[str, MCPServerTypes]model_config = ConfigDict(extra="allow") # Preserve unknown top-level fields+ @model_validator(mode="before")+ def validate_mcp_servers(self, info: ValidationInfo) -> dict[str, Any]:+ """Validate the MCP servers."""+ if not isinstance(self, dict):+ raise ValueError("MCPConfig format requires a dictionary of servers.")++ if "mcpServers" not in self:+ self = {"mcpServers": self}++ return self++ def add_server(self, name: str, server: MCPServerTypes) -> None:+ """Add or update a server in the configuration."""+ self.mcpServers[name] = server+@classmethod- def from_dict(cls, config: dict[str, Any]) -> MCPConfig:+ def from_dict(cls, config: dict[str, Any]) -> Self:"""Parse MCP configuration from dictionary format."""- # Handle case where config is just the mcpServers object- if "mcpServers" not in config and any(- isinstance(v, dict) and ("command" in v or "url" in v)- for v in config.values()- ):- # This looks like a bare mcpServers object- servers_dict = config- else:- # Standard format with mcpServers wrapper- servers_dict = config.get("mcpServers", {})-- # Parse each server configuration- parsed_servers = {}- for name, server_config in servers_dict.items():- if not isinstance(server_config, dict):- continue-- # Determine if this is stdio or remote based on fields- if "command" in server_config:- parsed_servers[name] = StdioMCPServer.model_validate(server_config)- elif "url" in server_config:- parsed_servers[name] = RemoteMCPServer.model_validate(server_config)- else:- # Skip invalid server configs but preserve them as raw dicts- # This allows for forward compatibility with unknown server types- continue-- # Create config with any extra top-level fields preserved- config_data = {k: v for k, v in config.items() if k != "mcpServers"}- config_data["mcpServers"] = parsed_servers-- return cls.model_validate(config_data)+ return cls.model_validate(config)def to_dict(self) -> dict[str, Any]:"""Convert MCPConfig to dictionary format, preserving all fields."""- # Start with all extra fields at the top level- result = self.model_dump(exclude={"mcpServers"}, exclude_none=True)-- # Add mcpServers with all fields preserved- result["mcpServers"] = {- name: server.model_dump(exclude_none=True)- for name, server in self.mcpServers.items()- }-- return result+ return self.model_dump(exclude_none=True)def write_to_file(self, file_path: Path) -> None:"""Write configuration to JSON file."""file_path.parent.mkdir(parents=True, exist_ok=True)- with open(file_path, "w") as f:- json.dump(self.to_dict(), f, indent=2)+ file_path.write_text(self.model_dump_json(indent=2))@classmethod- def from_file(cls, file_path: Path) -> MCPConfig:+ def from_file(cls, file_path: Path) -> Self:"""Load configuration from JSON file."""- if not file_path.exists():- return cls(mcpServers={})- with open(file_path) as f:- content = f.read().strip()- if not content:- return cls(mcpServers={})- data = json.loads(content)- return cls.from_dict(data)-- def add_server(self, name: str, server: StdioMCPServer | RemoteMCPServer) -> None:+ if file_path.exists():+ if content := file_path.read_text().strip():+ return cls.model_validate_json(content)++ return cls(mcpServers={})+++class CanonicalMCPConfig(MCPConfig):+ """Canonical MCP configuration format.++ This defines the standard configuration format for Model Context Protocol servers.+ The format is designed to be client-agnostic and extensible for future use cases.+ """++ mcpServers: dict[str, CanonicalMCPServerTypes]++ @override+ def add_server(self, name: str, server: CanonicalMCPServerTypes) -> None:"""Add or update a server in the configuration."""self.mcpServers[name] = server- def remove_server(self, name: str) -> None:- """Remove a server from the configuration."""- if name in self.mcpServers:- del self.mcpServers[name]-def update_config_file(file_path: Path,server_name: str,- server_config: StdioMCPServer | RemoteMCPServer,+ server_config: CanonicalMCPServerTypes,) -> None:- """Update MCP configuration file with new server, preserving existing fields."""+ """Update an MCP configuration file from a server object, preserving existing fields.++ This is used for updating the mcpServer configurations of third-party tools so we do not+ worry about transforming server objects here."""config = MCPConfig.from_file(file_path)# If updating an existing server, merge with existing configuration# to preserve any unknown fields- if server_name in config.mcpServers:- existing_server = config.mcpServers[server_name]+ if existing_server := config.mcpServers.get(server_name):# Get the raw dict representation of both serversexisting_dict = existing_server.model_dump()+new_dict = server_config.model_dump(exclude_none=True)# Merge, with new values taking precedence- merged_dict = {**existing_dict, **new_dict}-- # Create new server instance with merged data- if "command" in merged_dict:- merged_server = StdioMCPServer.model_validate(merged_dict)- else:- merged_server = RemoteMCPServer.model_validate(merged_dict)+ merged_config = server_config.model_validate({**existing_dict, **new_dict})- config.add_server(server_name, merged_server)+ config.add_server(server_name, merged_config)else:config.add_server(server_name, server_config)diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.pyindex 576b75ef2..cfd8ba57a 100644--- a/src/fastmcp/server/proxy.py+++ b/src/fastmcp/server/proxy.py@@ -36,6 +36,9 @@ from fastmcp.server.dependencies import get_contextfrom fastmcp.server.server import FastMCPfrom fastmcp.tools.tool import Tool, ToolResultfrom fastmcp.tools.tool_manager import ToolManager+from fastmcp.tools.tool_transform import (+ apply_transformations_to_tools,+)from fastmcp.utilities.components import MirroredComponentfrom fastmcp.utilities.logging import get_logger@@ -71,7 +74,12 @@ class ProxyToolManager(ToolManager):else:raise e- return all_tools+ transformed_tools = apply_transformations_to_tools(+ tools=all_tools,+ transformations=self.transformations,+ )++ return transformed_toolsasync def list_tools(self) -> list[Tool]:"""Gets the filtered list of tools including local, mounted, and proxy tools."""@@ -469,7 +477,11 @@ class FastMCPProxy(FastMCP):raise ValueError("Must specify 'client_factory'")# Replace the default managers with our specialized proxy managers.- self._tool_manager = ProxyToolManager(client_factory=self.client_factory)+ self._tool_manager = ProxyToolManager(+ client_factory=self.client_factory,+ # Propagate the transformations from the base class tool manager+ transformations=self._tool_manager.transformations,+ )self._resource_manager = ProxyResourceManager(client_factory=self.client_factory)diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 240c29a26..33036d39d 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -26,6 +26,7 @@ from mcp.server.lowlevel.server import LifespanResultT, NotificationOptionsfrom mcp.server.stdio import stdio_serverfrom mcp.types import (AnyFunction,+ CallToolRequestParams,ContentBlock,GetPromptResult,ToolAnnotations,@@ -60,6 +61,7 @@ from fastmcp.server.middleware import Middleware, MiddlewareContextfrom fastmcp.settings import Settingsfrom fastmcp.tools import ToolManagerfrom fastmcp.tools.tool import FunctionTool, Tool, ToolResult+from fastmcp.tools.tool_transform import ToolTransformConfigfrom fastmcp.utilities.cache import TimedCachefrom fastmcp.utilities.cli import log_server_bannerfrom fastmcp.utilities.components import FastMCPComponent@@ -138,6 +140,7 @@ class FastMCP(Generic[LifespanResultT]):resource_prefix_format: Literal["protocol", "path"] | None = None,mask_error_details: bool | None = None,tools: list[Tool | Callable[..., Any]] | None = None,+ tool_transformations: dict[str, ToolTransformConfig] | None = None,dependencies: list[str] | None = None,include_tags: set[str] | None = None,exclude_tags: set[str] | None = None,@@ -167,6 +170,7 @@ class FastMCP(Generic[LifespanResultT]):self._tool_manager = ToolManager(duplicate_behavior=on_duplicate_tools,mask_error_details=mask_error_details,+ transformations=tool_transformations,)self._resource_manager = ResourceManager(duplicate_behavior=on_duplicate_resources,@@ -650,7 +654,7 @@ class FastMCP(Generic[LifespanResultT]):key=context.message.name, arguments=context.message.arguments or {})- mw_context = MiddlewareContext(+ mw_context = MiddlewareContext[CallToolRequestParams](message=mcp.types.CallToolRequestParams(name=key, arguments=arguments),source="client",type="request",@@ -806,6 +810,16 @@ class FastMCP(Generic[LifespanResultT]):except RuntimeError:pass # No context available+ def add_tool_transformation(+ self, tool_name: str, transformation: ToolTransformConfig+ ) -> None:+ """Add a tool transformation."""+ self._tool_manager.add_tool_transformation(tool_name, transformation)++ def remove_tool_transformation(self, tool_name: str) -> None:+ """Remove a tool transformation."""+ self._tool_manager.remove_tool_transformation(tool_name)+@overloaddef tool(self,diff --git a/src/fastmcp/tools/tool_manager.py b/src/fastmcp/tools/tool_manager.pyindex 90737984b..18ea883c0 100644--- a/src/fastmcp/tools/tool_manager.py+++ b/src/fastmcp/tools/tool_manager.py@@ -10,6 +10,10 @@ from fastmcp import settingsfrom fastmcp.exceptions import NotFoundError, ToolErrorfrom fastmcp.settings import DuplicateBehaviorfrom fastmcp.tools.tool import Tool, ToolResult+from fastmcp.tools.tool_transform import (+ ToolTransformConfig,+ apply_transformations_to_tools,+)from fastmcp.utilities.logging import get_loggerif TYPE_CHECKING:@@ -25,10 +29,12 @@ class ToolManager:self,duplicate_behavior: DuplicateBehavior | None = None,mask_error_details: bool | None = None,+ transformations: dict[str, ToolTransformConfig] | None = None,):self._tools: dict[str, Tool] = {}self._mounted_servers: list[MountedServer] = []self.mask_error_details = mask_error_details or settings.mask_error_details+ self.transformations = transformations or {}# Default to "warn" if None is providedif duplicate_behavior is None:@@ -82,7 +88,13 @@ class ToolManager:# Finally, add local tools, which always take precedenceall_tools.update(self._tools)- return all_tools++ transformed_tools = apply_transformations_to_tools(+ tools=all_tools,+ transformations=self.transformations,+ )++ return transformed_toolsasync def has_tool(self, key: str) -> bool:"""Check if a tool exists."""@@ -109,6 +121,15 @@ class ToolManager:tools_dict = await self._load_tools(via_server=True)return list(tools_dict.values())+ @property+ def _tools_transformed(self) -> list[str]:+ """Get the local tools."""++ return [+ transformation.name or tool_name+ for tool_name, transformation in self.transformations.items()+ ]+def add_tool_from_fn(self,fn: Callable[..., Any],@@ -155,6 +176,21 @@ class ToolManager:self._tools[tool.key] = toolreturn tool+ def add_tool_transformation(+ self, tool_name: str, transformation: ToolTransformConfig+ ) -> None:+ """Add a tool transformation."""+ self.transformations[tool_name] = transformation++ def get_tool_transformation(self, tool_name: str) -> ToolTransformConfig | None:+ """Get a tool transformation."""+ return self.transformations.get(tool_name)++ def remove_tool_transformation(self, tool_name: str) -> None:+ """Remove a tool transformation."""+ if tool_name in self.transformations:+ del self.transformations[tool_name]+def remove_tool(self, key: str) -> None:"""Remove a tool from the server.@@ -175,7 +211,7 @@ class ToolManager:filtered protocol path."""# 1. Check local tools first. The server will have already applied its filter.- if key in self._tools:+ if key in self._tools or key in self._tools_transformed:tool = await self.get_tool(key)if not tool:raise NotFoundError(f"Tool {key!r} not found")diff --git a/src/fastmcp/tools/tool_transform.py b/src/fastmcp/tools/tool_transform.pyindex 09c89cc2f..aca45d8f8 100644--- a/src/fastmcp/tools/tool_transform.py+++ b/src/fastmcp/tools/tool_transform.py@@ -4,14 +4,22 @@ import inspectfrom collections.abc import Callablefrom contextvars import ContextVarfrom dataclasses import dataclass-from typing import Any, Literal+from typing import Annotated, Any, Literalfrom mcp.types import ToolAnnotationsfrom pydantic import ConfigDict+from pydantic.fields import Field+from pydantic.functional_validators import BeforeValidatorfrom fastmcp.tools.tool import ParsedFunction, Tool, ToolResult, _convert_to_content+from fastmcp.utilities.components import FastMCPComponent, _convert_set_default_nonefrom fastmcp.utilities.logging import get_logger-from fastmcp.utilities.types import NotSet, NotSetT, get_cached_typeadapter+from fastmcp.utilities.types import (+ FastMCPBaseModel,+ NotSet,+ NotSetT,+ get_cached_typeadapter,+)logger = get_logger(__name__)@@ -193,6 +201,30 @@ class ArgTransform:)+class ArgTransformConfig(FastMCPBaseModel):+ """A model for requesting a single argument transform."""++ name: str | None = Field(default=None, description="The new name for the argument.")+ description: str | None = Field(+ default=None, description="The new description for the argument."+ )+ default: str | int | float | bool | None = Field(+ default=None, description="The new default value for the argument."+ )+ hide: bool = Field(+ default=False, description="Whether to hide the argument from the tool."+ )+ required: Literal[True] | None = Field(+ default=None, description="Whether the argument is required."+ )+ examples: Any | None = Field(default=None, description="Examples of the argument.")++ def to_arg_transform(self) -> ArgTransform:+ """Convert the argument transform to a FastMCP argument transform."""++ return ArgTransform(**self.model_dump(exclude_unset=True)) # pyright: ignore[reportAny]++class TransformedTool(Tool):"""A tool that is transformed from another tool.@@ -798,3 +830,65 @@ class TransformedTool(Tool):return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())+++class ToolTransformConfig(FastMCPComponent):+ """Provides a way to transform a tool."""++ name: str | None = Field(default=None, description="The new name for the tool.")++ title: str | None = Field(+ default=None,+ description="The new title of the tool.",+ )+ description: str | None = Field(+ default=None,+ description="The new description of the tool.",+ )+ tags: Annotated[set[str], BeforeValidator(_convert_set_default_none)] = Field(+ default_factory=set,+ description="The new tags for the tool.",+ )++ enabled: bool = Field(+ default=True,+ description="Whether the tool is enabled.",+ )++ arguments: dict[str, ArgTransformConfig] = Field(+ default_factory=dict,+ description="A dictionary of argument transforms to apply to the tool.",+ )++ def apply(self, tool: Tool) -> TransformedTool:+ """Create a TransformedTool from a provided tool and this transformation configuration."""++ tool_changes = self.model_dump(exclude_unset=True, exclude={"arguments"})++ return TransformedTool.from_tool(+ tool=tool,+ **tool_changes,+ transform_args={k: v.to_arg_transform() for k, v in self.arguments.items()},+ )+++def apply_transformations_to_tools(+ tools: dict[str, Tool],+ transformations: dict[str, ToolTransformConfig],+) -> dict[str, Tool]:+ """Apply a list of transformations to a list of tools. Tools that do not have any transforamtions+ are left unchanged.+ """++ transformed_tools = {}++ for tool_name, tool in tools.items():+ if transformation := transformations.get(tool_name):+ transformed_tools[transformation.name or tool_name] = transformation.apply(+ tool+ )+ continue++ transformed_tools[tool_name] = tool++ return transformed_toolsdiff --git a/src/fastmcp/utilities/mcp_config.py b/src/fastmcp/utilities/mcp_config.pynew file mode 100644index 000000000..3d868bd06--- /dev/null+++ b/src/fastmcp/utilities/mcp_config.py@@ -0,0 +1,26 @@+from fastmcp.mcp_config import MCPConfig+from fastmcp.server.server import FastMCP+++def composite_server_from_mcp_config(+ config: MCPConfig, name_as_prefix: bool = True+) -> FastMCP:+ """A utility function to create a composite server from an MCPConfig."""+ composite_server = FastMCP()++ mount_mcp_config_into_server(config, composite_server, name_as_prefix)++ return composite_server+++def mount_mcp_config_into_server(+ config: MCPConfig,+ server: FastMCP,+ name_as_prefix: bool = True,+) -> None:+ """A utility function to mount the servers from an MCPConfig into a FastMCP server."""+ for name, mcp_server in config.mcpServers.items():+ server.mount(+ prefix=name if name_as_prefix else None,+ server=FastMCP.as_proxy(backend=mcp_server.to_transport()),+ )diff --git a/tests/server/proxy/test_proxy_server.py b/tests/server/proxy/test_proxy_server.pyindex 3aabb3287..dea8d3259 100644--- a/tests/server/proxy/test_proxy_server.py+++ b/tests/server/proxy/test_proxy_server.py@@ -12,6 +12,9 @@ from fastmcp.client import Clientfrom fastmcp.client.transports import FastMCPTransport, StreamableHttpTransportfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.proxy import FastMCPProxy, ProxyClient+from fastmcp.tools.tool_transform import (+ ToolTransformConfig,+)USERS = [{"id": "1", "name": "Alice", "active": True},@@ -118,6 +121,30 @@ class TestTools:assert "error_tool" in toolsassert "tool_without_description" in tools+ async def test_get_transformed_tools(+ self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy+ ):+ """An explicit None description should change the tool description to None."""++ fastmcp_server.add_tool_transformation(+ "add", ToolTransformConfig(name="add_transformed")+ )+ tools = await proxy_server.get_tools()+ assert "add_transformed" in tools+ assert "add" not in tools++ async def test_call_transformed_tools(+ self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy+ ):+ """An explicit None description should change the tool description to None."""++ fastmcp_server.add_tool_transformation(+ "add", ToolTransformConfig(name="add_transformed")+ )+ async with Client(proxy_server) as client:+ result = await client.call_tool("add_transformed", {"a": 1, "b": 2})+ assert result.data == 3+async def test_tool_without_description(self, proxy_server):tools = await proxy_server.get_tools()assert tools["tool_without_description"].description is Nonediff --git a/tests/server/test_tool_transformation.py b/tests/server/test_tool_transformation.pynew file mode 100644index 000000000..7c2095482--- /dev/null+++ b/tests/server/test_tool_transformation.py@@ -0,0 +1,40 @@+from fastmcp import FastMCP+from fastmcp.tools.tool_transform import ToolTransformConfig+++async def test_tool_transformation_in_tool_manager():+ """Test that tool transformations are applied in the tool manager."""+ mcp = FastMCP("Test Server")++ @mcp.tool()+ def echo(message: str) -> str:+ """Echo back the message provided."""+ return message++ mcp.add_tool_transformation("echo", ToolTransformConfig(name="echo_transformed"))++ tools_dict = await mcp._tool_manager.get_tools()+ tools = list(tools_dict.values())+ assert len(tools) == 1+ assert "echo_transformed" in tools_dict+ assert tools_dict["echo_transformed"].name == "echo_transformed"+++async def test_transformed_tool_filtering():+ """Test that tool transformations are applied in the tool manager."""+ mcp = FastMCP("Test Server", include_tags={"enabled_tools"})++ @mcp.tool()+ def echo(message: str) -> str:+ """Echo back the message provided."""+ return message++ tools = list(await mcp._list_tools())+ assert len(tools) == 0++ mcp.add_tool_transformation(+ "echo", ToolTransformConfig(name="echo_transformed", tags={"enabled_tools"})+ )++ tools = list(await mcp._list_tools())+ assert len(tools) == 1diff --git a/tests/utilities/test_mcp_config.py b/tests/test_mcp_config.pysimilarity index 50%rename from tests/utilities/test_mcp_config.pyrename to tests/test_mcp_config.pyindex b0d5822cf..ac7a8cff9 100644--- a/tests/utilities/test_mcp_config.py+++ b/tests/test_mcp_config.py@@ -1,16 +1,31 @@import inspect+import tempfile+from collections.abc import AsyncGeneratorfrom pathlib import Path+from typing import Any++import pytestfrom fastmcp.client.auth.bearer import BearerAuthfrom fastmcp.client.auth.oauth import OAuthClientProviderfrom fastmcp.client.client import Clientfrom fastmcp.client.logging import LogMessagefrom fastmcp.client.transports import (+ MCPConfigTransport,SSETransport,StdioTransport,StreamableHttpTransport,)-from fastmcp.mcp_config import MCPConfig, RemoteMCPServer, StdioMCPServer+from fastmcp.mcp_config import (+ CanonicalMCPConfig,+ CanonicalMCPServerTypes,+ MCPConfig,+ MCPServerTypes,+ RemoteMCPServer,+ StdioMCPServer,+ TransformingStdioMCPServer,+)+from fastmcp.tools.tool import Tool as FastMCPTooldef test_parse_single_stdio_config():@@ -29,6 +44,74 @@ def test_parse_single_stdio_config():assert transport.args == ["hello"]+def test_parse_extra_keys():+ config = {+ "mcpServers": {+ "test_server": {+ "command": "echo",+ "args": ["hello"],+ "leaf_extra": "leaf_extra",+ }+ },+ "root_extra": "root_extra",+ }+ mcp_config = MCPConfig.from_dict(config)++ serialized_mcp_config = mcp_config.to_dict()+ assert serialized_mcp_config["root_extra"] == "root_extra"+ assert (+ serialized_mcp_config["mcpServers"]["test_server"]["leaf_extra"] == "leaf_extra"+ )+++def test_parse_mcpservers_at_root():+ config = {+ "test_server": {+ "command": "echo",+ "args": ["hello"],+ }+ }++ mcp_config = MCPConfig.from_dict(config)++ serialized_mcp_config = mcp_config.model_dump()+ assert serialized_mcp_config["mcpServers"]["test_server"]["command"] == "echo"+ assert serialized_mcp_config["mcpServers"]["test_server"]["args"] == ["hello"]+++def test_parse_mcpservers_discriminator():+ """Test that the MCPConfig discriminator produces StdioMCPServer for a non-transforming server+ and TransformingStdioMCPServer for a transforming server."""++ config = {+ "test_server": {+ "command": "echo",+ "args": ["hello"],+ },+ "test_server_two": {"command": "echo", "args": ["hello"], "tools": {}},+ }++ mcp_config = MCPConfig.from_dict(config)++ test_server: MCPServerTypes = mcp_config.mcpServers["test_server"]+ assert isinstance(test_server, StdioMCPServer)++ test_server_two: MCPServerTypes = mcp_config.mcpServers["test_server_two"]+ assert isinstance(test_server_two, TransformingStdioMCPServer)++ canonical_mcp_config = CanonicalMCPConfig.from_dict(config)++ canonical_test_server: CanonicalMCPServerTypes = canonical_mcp_config.mcpServers[+ "test_server"+ ]+ assert isinstance(canonical_test_server, StdioMCPServer)++ canonical_test_server_two: CanonicalMCPServerTypes = (+ canonical_mcp_config.mcpServers["test_server_two"]+ )+ assert isinstance(canonical_test_server_two, StdioMCPServer)++def test_parse_single_remote_config():config = {"mcpServers": {@@ -244,6 +327,172 @@ async def test_multi_client_with_logging(tmp_path: Path):assert MESSAGES[0].data == "test 42"+async def test_multi_client_with_transforms(tmp_path: Path):+ """+ Tests that transforms are properly applied to the tools.+ """+ server_script = inspect.cleandoc("""+ from fastmcp import FastMCP++ mcp = FastMCP()++ @mcp.tool+ def add(a: int, b: int) -> int:+ return a + b++ if __name__ == '__main__':+ mcp.run()+ """)++ script_path = tmp_path / "test.py"+ script_path.write_text(server_script)++ config = {+ "mcpServers": {+ "test_1": {+ "command": "python",+ "args": [str(script_path)],+ "tools": {+ "add": {+ "name": "transformed_add",+ "arguments": {+ "a": {"name": "transformed_a"},+ "b": {"name": "transformed_b"},+ },+ }+ },+ },+ "test_2": {+ "command": "python",+ "args": [str(script_path)],+ },+ }+ }++ client = Client[MCPConfigTransport](config)++ async with client:+ tools = await client.list_tools()+ tools_by_name = {tool.name: tool for tool in tools}+ assert len(tools) == 2+ assert "test_1_transformed_add" in tools_by_name++ result = await client.call_tool(+ "test_1_transformed_add", {"transformed_a": 1, "transformed_b": 2}+ )+ assert result.data == 3+++async def test_canonical_multi_client_with_transforms(tmp_path: Path):+ """Test that transforms are not applied to servers in a canonical MCPConfig."""+ server_script = inspect.cleandoc("""+ from fastmcp import FastMCP++ mcp = FastMCP()++ @mcp.tool+ def add(a: int, b: int) -> int:+ return a + b++ if __name__ == '__main__':+ mcp.run()+ """)++ script_path = tmp_path / "test.py"+ script_path.write_text(server_script)++ config = CanonicalMCPConfig(+ mcpServers={+ "test_1": {+ "command": "python",+ "args": [str(script_path)],+ "tools": { # <--- Will be ignored as its not valid for a canonical MCPConfig+ "add": {+ "name": "transformed_add",+ "arguments": {+ "a": {"name": "transformed_a"},+ "b": {"name": "transformed_b"},+ },+ }+ },+ },+ "test_2": {+ "command": "python",+ "args": [str(script_path)],+ },+ } # type: ignore[reportUnknownArgumentType]+ )++ client = Client(config)++ async with client:+ tools = await client.list_tools()+ tools_by_name = {tool.name: tool for tool in tools}+ assert len(tools) == 2+ assert "test_1_transformed_add" not in tools_by_name+++async def test_multi_client_transform_with_filtering(tmp_path: Path):+ """+ Tests that tag-based filtering works when using a transforming MCPConfig.+ """+ server_script = inspect.cleandoc("""+ from fastmcp import FastMCP++ mcp = FastMCP()++ @mcp.tool+ def add(a: int, b: int) -> int:+ return a + b++ @mcp.tool+ def subtract(a: int, b: int) -> int:+ return a - b++ if __name__ == '__main__':+ mcp.run()+ """)++ script_path = tmp_path / "test.py"+ script_path.write_text(server_script)++ config = {+ "mcpServers": {+ "test_1": {+ "command": "python",+ "args": [str(script_path)],+ "tools": {+ "add": {+ "name": "transformed_add",+ "tags": ["keep"],+ "arguments": {+ "a": {"name": "transformed_a"},+ "b": {"name": "transformed_b"},+ },+ },+ },+ "include_tags": ["keep"],+ },+ "test_2": {+ "command": "python",+ "args": [str(script_path)],+ },+ }+ }++ client = Client[MCPConfigTransport](config)++ async with client:+ tools = await client.list_tools()+ tools_by_name = {tool.name: tool for tool in tools}+ assert len(tools) == 3+ assert "test_1_transformed_add" in tools_by_name+ assert "test_1_add" not in tools_by_name+ assert "test_1_subtract" not in tools_by_name+ assert "test_2_add" in tools_by_name+ assert "test_2_subtract" in tools_by_name++async def test_multi_client_with_elicitation(tmp_path: Path):"""Tests that elicitation is properly forwarded to the ultimate client.@@ -284,3 +533,34 @@ async def test_multi_client_with_elicitation(tmp_path: Path):async with Client(config, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("test_server_elicit_test", {})assert result.data == 42+++def sample_tool_fn(arg1: int, arg2: str) -> str:+ return f"Hello, world! {arg1} {arg2}"+++def sample_tool() -> FastMCPTool:+ return FastMCPTool.from_function(sample_tool_fn, name="sample_tool")+++async def test_script(tmp_path: Path) -> AsyncGenerator[Path, Any]:+ with tempfile.NamedTemporaryFile() as f:+ f.write(b"""+ from fastmcp import FastMCP++ mcp = FastMCP()++ @mcp.tool+ def fetch(url: str) -> str:++ return f"Hello, world! {url}"++ if __name__ == '__main__':+ mcp.run()+ """)++ yield Path(f.name)++ passdiff --git a/tests/tools/test_tool_manager.py b/tests/tools/test_tool_manager.pyindex 42ef6038e..065d90607 100644--- a/tests/tools/test_tool_manager.py+++ b/tests/tools/test_tool_manager.py@@ -12,6 +12,7 @@ from fastmcp import Context, FastMCPfrom fastmcp.exceptions import NotFoundError, ToolErrorfrom fastmcp.tools import FunctionTool, ToolManagerfrom fastmcp.tools.tool import Tool+from fastmcp.tools.tool_transform import ArgTransformConfig, ToolTransformConfigfrom fastmcp.utilities.tests import caplog_for_fastmcpfrom fastmcp.utilities.types import Image@@ -262,6 +263,52 @@ class TestAddTools:assert result.fn.__name__ == "replacement_fn"+class TestListTools:+ async def test_list_tools_with_transformed_names(self):+ """Test listing tools with transformations."""++ tool_manager = ToolManager()++ def add(a: int, b: int) -> int:+ return a + b++ tool = Tool.from_function(add)+ tool_manager.add_tool(tool)++ tool_manager.add_tool_transformation(+ "add", ToolTransformConfig(name="add_transformed")+ )+ tools = await tool_manager.list_tools()+ tools_by_name = {tool.name: tool for tool in tools}+ assert "add_transformed" in tools_by_name+ assert "add" not in tools_by_name++ async def test_list_tools_with_transforms(self):+ """Test listing tools with transformations."""++ tool_manager = ToolManager()++ def add(a: int, b: int) -> int:+ """Add two numbers."""+ return a + b++ tool = Tool.from_function(add)+ tool_manager.add_tool(tool)++ tool_manager.add_tool_transformation(+ "add",+ ToolTransformConfig(+ name="add_transformed", description=None, tags={"enabled_tools"}+ ),+ )+ tools = await tool_manager.list_tools()+ tools_by_name = {tool.name: tool for tool in tools}+ assert "add_transformed" in tools_by_name+ assert "add" not in tools_by_name+ assert tools_by_name["add_transformed"].description is None+ assert tools_by_name["add_transformed"].tags == {"enabled_tools"}++class TestToolTags:"""Test functionality related to tool tags."""@@ -431,6 +478,39 @@ class TestCallTools:with pytest.raises(NotFoundError, match="Tool 'unknown' not found"):await manager.call_tool("unknown", {"a": 1})+ async def test_call_transformed_tool(self):+ manager = ToolManager()++ def add(a: int, b: int) -> int:+ """Add two numbers."""+ return a + b++ tool = Tool.from_function(add)+ manager.add_tool(tool)++ manager.add_tool_transformation(+ "add",+ ToolTransformConfig(+ name="add_transformed",+ description=None,+ tags={"enabled_tools"},+ arguments={+ "a": ArgTransformConfig(+ name="a_transformed", description=None, default=1+ ),+ "b": ArgTransformConfig(+ name="b_transformed", description=None, default=2+ ),+ },+ ),+ )++ result = await manager.call_tool(+ "add_transformed", {"a_transformed": 1, "b_transformed": 2}+ )+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structured_content == {"result": 3}+async def test_call_tool_with_list_int_input(self):def sum_vals(vals: list[int]) -> int:return sum(vals)