mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-28 10:18:08 +02:00
Add transform system for modifying components in provider chains (#2836)
* Consolidate tool transformation logic into TransformingProvider
Tool transformations were previously scattered across LocalProvider,
ProxyProvider, and MCPConfig. This consolidates all transformation
logic into TransformingProvider via with_transforms(tool_transforms={...}).
- Add tool_transforms parameter to TransformingProvider
- Add tool_transforms to Provider.with_transforms()
- Remove transformation storage from LocalProvider and ProxyProvider
- Remove add_tool_transformation() and remove_tool_transformation() from FastMCP
- Add tool_transforms parameter to factory methods (from_openapi, from_fastapi, create_proxy)
- Update tests to use new patterns
* Fix: reject tool lookups by pre-transform name
* Add collision validation for tool_transforms and fix docstring examples
- Validate duplicate target names in tool_transforms raise ValueError
- Fix docstring examples to use arguments/ArgTransformConfig (not args/ArgTransform)
- Add test for collision validation
* Add server-level tool transform APIs and fix task registration
- Add AggregateProvider to present multiple providers as one
- Add _get_root_provider() to apply server-level transforms uniformly
- Fix _docket_lifespan to use root provider (ensures renamed tools
register with correct keys for background execution)
- Add tool_transforms kwarg to __init__ (non-deprecated)
- Add add_tool_transform(), remove_tool_transform(), tool_transforms property
- Deprecate old API names (tool_transformations, add_tool_transformation, etc.)
- Update tests to use new API
* Add graceful degradation for provider errors in AggregateProvider
* Match original behavior: parallel queries with DEBUG logging
* Refactor transforms to middleware-style call_next pattern
Replaces the ad-hoc transformation system with a unified Transform
abstraction using the same call_next pattern as server middleware.
Key changes:
- New src/fastmcp/server/transforms/ module with Transform base class
- Namespace, ToolTransform, Visibility all implement the same interface
- Transforms compose via functools.partial chain building
- Visibility is now just the first transform in provider._transforms
- Server-level transforms apply after provider aggregation
- Task registration now applies full transform chain
Removes TransformingProvider, _BoundTransform, ComponentSource protocol.
User-facing API unchanged: mount(), add_transform(), enable/disable all
work as before.
* Add comprehensive transforms and visibility documentation
New docs/servers/providers/transforms.mdx covering:
- Mental model for middleware-style transform pattern
- Built-in transforms (Namespace, ToolTransform)
- Server vs provider-level transforms and ordering
- Tool modification (immediate vs deferred)
- Custom transform creation
New docs/servers/visibility.mdx covering:
- Enable/disable API for runtime visibility control
- Keys and tags for targeting components
- Allowlist mode with only=True
- Server vs provider visibility layering
Updates existing docs to reference new pages and simplifies
redundant content. Visibility is documented as a user feature,
not as an implementation detail.
* Restructure transforms docs and delete tool-transformation pattern
* Cleanup: simplify get_tasks and remove unused Provider.get_component
* Update loq
* Update loq limits and add loq note to AGENTS.md
* Deprecate add_tool_transformation and tool_transformations param
* Address PR review feedback: remove redundant imports, fix path reference
* Add missing imports to code examples in v3-features.mdx
This commit is contained in:
parent
1b723f302d
commit
07d89c4038
38 changed files with 2973 additions and 2076 deletions
|
|
@ -24,7 +24,7 @@ class Provider:
|
|||
Providers support:
|
||||
- **Lifecycle management**: `async def lifespan()` for setup/teardown
|
||||
- **Visibility control**: `enable()` / `disable()` with keys, tags, and allowlist mode
|
||||
- **Transformation chaining**: `provider.with_transforms(namespace=..., tool_renames=...)`
|
||||
- **Transform stacking**: `provider.add_transform(Namespace(...))`, `provider.add_transform(ToolTransform(...))`
|
||||
|
||||
### LocalProvider
|
||||
|
||||
|
|
@ -82,6 +82,7 @@ Features:
|
|||
```python
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.providers import FastMCPProvider
|
||||
from fastmcp.server.transforms import Namespace
|
||||
|
||||
main = FastMCP("Main")
|
||||
sub = FastMCP("Sub")
|
||||
|
|
@ -91,34 +92,67 @@ def greet(name: str) -> str:
|
|||
return f"Hello, {name}!"
|
||||
|
||||
# Mount with namespace
|
||||
main.add_provider(FastMCPProvider(sub).with_namespace("sub"))
|
||||
provider = FastMCPProvider(sub)
|
||||
provider.add_transform(Namespace("sub"))
|
||||
main.add_provider(provider)
|
||||
# Tool accessible as "sub_greet"
|
||||
```
|
||||
|
||||
### TransformingProvider
|
||||
### Transforms
|
||||
|
||||
`TransformingProvider` (`src/fastmcp/server/providers/transforming.py`) wraps any provider to apply namespace prefixes and tool renames. Usually accessed via `provider.with_transforms()`.
|
||||
Transforms modify components (tools, resources, prompts) as they flow from providers to clients. They use a middleware pattern where each transform receives a `call_next` callable to continue the chain.
|
||||
|
||||
**Built-in transforms** (`src/fastmcp/server/transforms/`):
|
||||
|
||||
- `Namespace` - adds prefixes to names (`tool` → `api_tool`) and path segments to URIs (`data://x` → `data://api/x`)
|
||||
- `ToolTransform` - modifies tool schemas (rename, description, tags, argument transforms)
|
||||
- `Visibility` - filters components by key or tag (backs `enable()`/`disable()` API)
|
||||
|
||||
```python
|
||||
provider = SomeProvider().with_transforms(
|
||||
namespace="api",
|
||||
tool_renames={"verbose_tool_name": "short"}
|
||||
)
|
||||
from fastmcp.server.transforms import Namespace, ToolTransform
|
||||
from fastmcp.tools.tool_transform import ToolTransformConfig
|
||||
|
||||
provider = SomeProvider()
|
||||
provider.add_transform(Namespace("api"))
|
||||
provider.add_transform(ToolTransform({
|
||||
"api_verbose_tool_name": ToolTransformConfig(name="short")
|
||||
}))
|
||||
|
||||
# Stacking composes transformations
|
||||
provider = (
|
||||
SomeProvider()
|
||||
.with_transforms(namespace="api")
|
||||
.with_transforms(tool_renames={"api_foo": "bar"})
|
||||
)
|
||||
# "foo" → "api_foo" → "bar"
|
||||
# "foo" → "api_foo" (namespace) → "short" (rename)
|
||||
```
|
||||
|
||||
**Custom transforms** subclass `Transform` and override needed methods:
|
||||
|
||||
```python
|
||||
from collections.abc import Sequence
|
||||
from fastmcp.server.transforms import Transform, ListToolsNext, GetToolNext
|
||||
from fastmcp.tools import Tool
|
||||
|
||||
class TagFilter(Transform):
|
||||
def __init__(self, required_tags: set[str]):
|
||||
self.required_tags = required_tags
|
||||
|
||||
async def list_tools(self, call_next: ListToolsNext) -> Sequence[Tool]:
|
||||
tools = await call_next() # Get tools from downstream
|
||||
return [t for t in tools if t.tags & self.required_tags]
|
||||
|
||||
async def get_tool(self, name: str, call_next: GetToolNext) -> Tool | None:
|
||||
tool = await call_next(name)
|
||||
return tool if tool and tool.tags & self.required_tags else None
|
||||
```
|
||||
|
||||
Transforms apply at two levels:
|
||||
- **Provider-level**: `provider.add_transform()` - affects only that provider's components
|
||||
- **Server-level**: `server.add_transform()` - affects all components from all providers
|
||||
|
||||
Documentation: `docs/servers/providers/transforms.mdx`, `docs/servers/visibility.mdx`
|
||||
|
||||
---
|
||||
|
||||
## Visibility System
|
||||
|
||||
Components can be dynamically enabled/disabled at runtime using the visibility system (`src/fastmcp/utilities/visibility.py`).
|
||||
Components can be dynamically enabled/disabled at runtime using the visibility system (`src/fastmcp/server/transforms/visibility.py`).
|
||||
|
||||
```python
|
||||
mcp = FastMCP("Server")
|
||||
|
|
@ -385,6 +419,19 @@ mcp.disable(tags={"internal"})
|
|||
|
||||
The `tool_serializer` parameter on `FastMCP` is deprecated. Return `ToolResult` for explicit serialization control.
|
||||
|
||||
### Tool Transformation Methods
|
||||
|
||||
`add_tool_transformation()`, `remove_tool_transformation()`, and `tool_transformations` constructor parameter are deprecated. Use `add_transform(ToolTransform({...}))` instead:
|
||||
|
||||
```python
|
||||
# Deprecated
|
||||
mcp.add_tool_transformation("name", config)
|
||||
|
||||
# New
|
||||
from fastmcp.server.transforms import ToolTransform
|
||||
mcp.add_transform(ToolTransform({"name": config}))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Breaking Changes
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue