Merge pull request #870 from jlowin/middleware-2

This commit is contained in:
Jeremiah Lowin 2025-06-19 18:15:36 -04:00 committed by GitHub
commit ce8b43f282
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 2601 additions and 882 deletions

View file

@ -78,6 +78,7 @@
"servers/auth/bearer"
]
},
"servers/middleware",
"servers/openapi",
"servers/proxy",
"servers/composition",

View file

@ -3,6 +3,7 @@ title: Tool Transformation
sidebarTitle: Tool Transformation
description: Create enhanced tool variants with modified schemas, argument mappings, and custom behavior.
icon: wand-magic-sparkles
tag: NEW
---
import { VersionBadge } from '/snippets/version-badge.mdx'

View file

@ -193,7 +193,7 @@ def hello():
return "hi"
# Mount directly
main.mount("sub", sub)
main.mount(sub, prefix="sub")
```
## Proxying Servers

421
docs/servers/middleware.mdx Normal file
View file

@ -0,0 +1,421 @@
---
title: MCP Middleware
sidebarTitle: Middleware
description: Add cross-cutting functionality to your MCP server with middleware that can inspect, modify, and respond to all MCP requests and responses.
icon: layer-group
tag: NEW
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.9.0" />
MCP middleware is a powerful concept that allows you to add cross-cutting functionality to your FastMCP server. Unlike traditional web middleware, MCP middleware is designed specifically for the Model Context Protocol, providing hooks for different types of MCP operations like tool calls, resource reads, and prompt requests.
<Tip>
MCP middleware is a FastMCP-specific concept and is not part of the official MCP protocol specification. This middleware system is designed to work with FastMCP servers and may not be compatible with other MCP implementations.
</Tip>
<Warning>
MCP middleware is a brand new concept and may be subject to breaking changes in future versions.
</Warning>
## What is MCP Middleware?
MCP middleware lets you intercept and modify MCP requests and responses as they flow through your server. Think of it as a pipeline where each piece of middleware can inspect what's happening, make changes, and then pass control to the next middleware in the chain.
Common use cases for MCP middleware include:
- **Authentication and Authorization**: Verify client permissions before executing operations
- **Logging and Monitoring**: Track usage patterns and performance metrics
- **Rate Limiting**: Control request frequency per client or operation type
- **Request/Response Transformation**: Modify data before it reaches tools or after it leaves
- **Caching**: Store frequently requested data to improve performance
- **Error Handling**: Provide consistent error responses across your server
## How Middleware Works
FastMCP middleware operates on a pipeline model. When a request comes in, it flows through your middleware in the order they were added to the server. Each middleware can:
1. **Inspect the incoming request** and its context
2. **Modify the request** before passing it to the next middleware or handler
3. **Execute the next middleware/handler** in the chain by calling `call_next()`
4. **Inspect and modify the response** before returning it
5. **Handle errors** that occur during processing
The key insight is that middleware forms a chain where each piece decides whether to continue processing or stop the chain entirely.
If you're familiar with ASGI middleware, the basic structure of FastMCP middleware will feel familiar. At its core, middleware is a callable class that receives a context object containing information about the current JSON-RPC message and a handler function to continue the middleware chain.
It's important to understand that MCP operates on the [JSON-RPC specification](https://spec.modelcontextprotocol.io/specification/basic/transports/). While FastMCP presents requests and responses in a familiar way, these are fundamentally JSON-RPC messages, not HTTP request/response pairs like you might be used to in web applications. FastMCP middleware works with all [transport types](/clients/transports), including local stdio transport and HTTP transports, though not all middleware implementations are compatible across all transports (e.g., middleware that inspects HTTP headers won't work with stdio transport).
The most fundamental way to implement middleware is by overriding the `__call__` method on the `Middleware` base class:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext
class RawMiddleware(Middleware):
async def __call__(self, context: MiddlewareContext, call_next):
# This method receives ALL messages regardless of type
print(f"Raw middleware processing: {context.method}")
result = await call_next(context)
print(f"Raw middleware completed: {context.method}")
return result
```
This gives you complete control over every message that flows through your server, but requires you to handle all message types manually.
## Middleware Hooks
To make it easier for users to target specific types of messages, FastMCP middleware provides a variety of specialized hooks. Instead of implementing the raw `__call__` method, you can override specific hook methods that are called only for certain types of operations, allowing you to target exactly the level of specificity you need for your middleware logic.
### Hook Hierarchy and Execution Order
FastMCP provides multiple hooks that are called with varying levels of specificity. Understanding this hierarchy is crucial for effective middleware design.
When a request comes in, **multiple hooks may be called for the same request**, going from general to specific:
1. **`on_message`** - Called for ALL MCP messages (both requests and notifications)
2. **`on_request` or `on_notification`** - Called based on the message type
3. **Operation-specific hooks** - Called for specific MCP operations like `on_call_tool`
For example, when a client calls a tool, your middleware will receive **three separate hook calls**:
1. First: `on_message` (because it's any MCP message)
2. Second: `on_request` (because tool calls expect responses)
3. Third: `on_call_tool` (because it's specifically a tool execution)
This hierarchy allows you to target your middleware logic with the right level of specificity. Use `on_message` for broad concerns like logging, `on_request` for authentication, and `on_call_tool` for tool-specific logic like performance monitoring.
### Available Hooks
- `on_message`: Called for all MCP messages (requests and notifications)
- `on_request`: Called specifically for MCP requests (that expect responses)
- `on_notification`: Called specifically for MCP notifications (fire-and-forget)
- `on_call_tool`: Called when tools are being executed
- `on_read_resource`: Called when resources are being read
- `on_get_prompt`: Called when prompts are being retrieved
- `on_list_tools`: Called when listing available tools
- `on_list_resources`: Called when listing available resources
- `on_list_resource_templates`: Called when listing resource templates
- `on_list_prompts`: Called when listing available prompts
## Component Access in Middleware
Understanding how to access component information (tools, resources, prompts) in middleware is crucial for building powerful middleware functionality. The access patterns differ significantly between listing operations and execution operations.
### Listing Operations vs Execution Operations
FastMCP middleware handles two types of operations differently:
**Listing Operations** (`on_list_tools`, `on_list_resources`, `on_list_prompts`, etc.):
- Middleware receives **FastMCP component objects** with full metadata
- These objects include FastMCP-specific properties like `tags` that aren't part of the MCP specification
- The result contains complete component information before it's converted to MCP format
- Tags and other metadata are stripped when finally returned to the MCP client
**Execution Operations** (`on_call_tool`, `on_read_resource`, `on_get_prompt`):
- Middleware runs **before** the component is executed
- The middleware result is either the execution result or an error if the component wasn't found
- Component metadata isn't directly available in the hook parameters
### Accessing Component Metadata During Execution
If you need to check component properties (like tags) during execution operations, use the FastMCP server instance available through the context:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.exceptions import ToolError
class TagBasedMiddleware(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
# Access the tool object to check its metadata
if context.fastmcp_context:
try:
tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)
# Check if this tool has a "private" tag
if "private" in tool.tags:
raise ToolError("Access denied: private tool")
# Check if tool is enabled
if not tool.enabled:
raise ToolError("Tool is currently disabled")
except Exception:
# Tool not found or other error - let execution continue
# and handle the error naturally
pass
return await call_next(context)
```
The same pattern works for resources and prompts:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.exceptions import ResourceError, PromptError
class ComponentAccessMiddleware(Middleware):
async def on_read_resource(self, context: MiddlewareContext, call_next):
if context.fastmcp_context:
try:
resource = await context.fastmcp_context.fastmcp.get_resource(context.message.uri)
if "restricted" in resource.tags:
raise ResourceError("Access denied: restricted resource")
except Exception:
pass
return await call_next(context)
async def on_get_prompt(self, context: MiddlewareContext, call_next):
if context.fastmcp_context:
try:
prompt = await context.fastmcp_context.fastmcp.get_prompt(context.message.name)
if not prompt.enabled:
raise PromptError("Prompt is currently disabled")
except Exception:
pass
return await call_next(context)
```
### Working with Listing Results
For listing operations, you can inspect and modify the FastMCP components directly:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext, ListToolsResult
class ListingFilterMiddleware(Middleware):
async def on_list_tools(self, context: MiddlewareContext, call_next):
result = await call_next(context)
# Filter out tools with "private" tag
filtered_tools = {
name: tool for name, tool in result.tools.items()
if "private" not in tool.tags
}
# Return modified result
return ListToolsResult(tools=filtered_tools)
```
This filtering happens before the components are converted to MCP format and returned to the client, so the tags (which are FastMCP-specific) are naturally stripped in the final response.
### Anatomy of a Hook
Every middleware hook follows the same pattern. Let's examine the `on_message` hook to understand the structure:
```python
async def on_message(self, context: MiddlewareContext, call_next):
# 1. Pre-processing: Inspect and optionally modify the request
print(f"Processing {context.method}")
# 2. Chain continuation: Call the next middleware/handler
result = await call_next(context)
# 3. Post-processing: Inspect and optionally modify the response
print(f"Completed {context.method}")
# 4. Return the result (potentially modified)
return result
```
### Hook Parameters
Every hook receives two parameters:
1. **`context: MiddlewareContext`** - Contains information about the current request:
- `context.method` - The MCP method name (e.g., "tools/call")
- `context.source` - Where the request came from ("client" or "server")
- `context.type` - Message type ("request" or "notification")
- `context.message` - The MCP message data
- `context.timestamp` - When the request was received
- `context.fastmcp_context` - FastMCP Context object (if available)
2. **`call_next`** - A function that continues the middleware chain. You **must** call this to proceed, unless you want to stop processing entirely.
### Control Flow
You have complete control over the request flow:
- **Continue processing**: Call `await call_next(context)` to proceed
- **Modify the request**: Change the context before calling `call_next`
- **Modify the response**: Change the result after calling `call_next`
- **Stop the chain**: Don't call `call_next` (rarely needed)
- **Handle errors**: Wrap `call_next` in try/catch blocks
## Creating Middleware
FastMCP middleware is implemented by subclassing the `Middleware` base class and overriding the hooks you need. You only need to implement the hooks that are relevant to your use case.
```python
from fastmcp import FastMCP
from fastmcp.server.middleware import Middleware, MiddlewareContext
class LoggingMiddleware(Middleware):
"""Middleware that logs all MCP operations."""
async def on_message(self, context: MiddlewareContext, call_next):
"""Called for all MCP messages."""
print(f"Processing {context.method} from {context.source}")
result = await call_next(context)
print(f"Completed {context.method}")
return result
# Add middleware to your server
mcp = FastMCP("MyServer")
mcp.add_middleware(LoggingMiddleware())
```
This creates a basic logging middleware that will print information about every request that flows through your server.
## Adding Middleware to Your Server
### Single Middleware
Adding middleware to your server is straightforward:
```python
mcp = FastMCP("MyServer")
mcp.add_middleware(LoggingMiddleware())
```
### Multiple Middleware
Middleware executes in the order it's added to the server. The first middleware added runs first on the way in, and last on the way out:
```python
mcp = FastMCP("MyServer")
mcp.add_middleware(AuthenticationMiddleware("secret-token"))
mcp.add_middleware(PerformanceMiddleware())
mcp.add_middleware(LoggingMiddleware())
```
This creates the following execution flow:
1. AuthenticationMiddleware (pre-processing)
2. PerformanceMiddleware (pre-processing)
3. LoggingMiddleware (pre-processing)
4. Actual tool/resource handler
5. LoggingMiddleware (post-processing)
6. PerformanceMiddleware (post-processing)
7. AuthenticationMiddleware (post-processing)
## Server Composition and Middleware
When using [Server Composition](/servers/composition) with `mount` or `import_server`, middleware behavior follows these rules:
1. **Parent server middleware** runs for all requests, including those routed to mounted servers
2. **Mounted server middleware** only runs for requests handled by that specific server
3. **Middleware order** is preserved within each server
This allows you to create layered middleware architectures where parent servers handle cross-cutting concerns like authentication, while child servers focus on domain-specific middleware.
```python
# Parent server with middleware
parent = FastMCP("Parent")
parent.add_middleware(AuthenticationMiddleware("token"))
# Child server with its own middleware
child = FastMCP("Child")
child.add_middleware(LoggingMiddleware())
@child.tool
def child_tool() -> str:
return "from child"
# Mount the child server
parent.mount(child, prefix="child")
```
When a client calls "child_tool", the request will flow through the parent's authentication middleware first, then route to the child server where it will go through the child's logging middleware.
## Examples
### Authentication Middleware
This middleware checks for a valid authorization token on all requests:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.exceptions import ToolError
class AuthenticationMiddleware(Middleware):
def __init__(self, required_token: str):
self.required_token = required_token
async def on_request(self, context: MiddlewareContext, call_next):
if hasattr(context, 'fastmcp_context') and context.fastmcp_context:
try:
request = context.fastmcp_context.get_http_request()
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise ToolError("Missing or invalid authorization header")
token = auth_header.split(" ", 1)[1]
if token != self.required_token:
raise ToolError("Invalid authentication token")
except Exception:
pass
return await call_next(context)
# Usage
mcp = FastMCP("SecureServer")
mcp.add_middleware(AuthenticationMiddleware("secret-token-123"))
```
### Performance Monitoring Middleware
This middleware tracks how long tools take to execute:
```python
import time
import logging
class PerformanceMiddleware(Middleware):
def __init__(self):
self.logger = logging.getLogger("performance")
async def on_call_tool(self, context: MiddlewareContext, call_next):
tool_name = context.message.name
start_time = time.time()
try:
result = await call_next(context)
execution_time = time.time() - start_time
self.logger.info(
f"Tool {tool_name} completed in {execution_time:.3f}s"
)
return result
except Exception as e:
execution_time = time.time() - start_time
self.logger.error(
f"Tool {tool_name} failed after {execution_time:.3f}s: {e}"
)
raise
```
### Request Transformation Middleware
This middleware adds metadata to tool calls:
```python
class TransformationMiddleware(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
if hasattr(context.message, 'arguments'):
args = context.message.arguments or {}
args['_middleware_timestamp'] = context.timestamp.isoformat()
modified_context = context.copy(
message=context.message.model_copy(update={'arguments': args})
)
else:
modified_context = context
return await call_next(modified_context)
```

View file

@ -13,7 +13,7 @@ from fastmcp.settings import DuplicateBehavior
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
pass
from fastmcp.server.server import MountedServer
logger = get_logger(__name__)
@ -27,6 +27,7 @@ class PromptManager:
mask_error_details: bool | None = None,
):
self._prompts: dict[str, Prompt] = {}
self._mounted_servers: list[MountedServer] = []
self.mask_error_details = mask_error_details or settings.mask_error_details
# Default to "warn" if None is provided
@ -41,15 +42,74 @@ class PromptManager:
self.duplicate_behavior = duplicate_behavior
def get_prompt(self, key: str) -> Prompt:
def mount(self, server: MountedServer) -> None:
"""Adds a mounted server as a source for prompts."""
self._mounted_servers.append(server)
async def _load_prompts(self, *, via_server: bool = False) -> dict[str, Prompt]:
"""
The single, consolidated recursive method for fetching prompts. The 'via_server'
parameter determines the communication path.
- via_server=False: Manager-to-manager path for complete, unfiltered inventory
- via_server=True: Server-to-server path for filtered MCP requests
"""
all_prompts: dict[str, Prompt] = {}
for mounted in self._mounted_servers:
try:
if via_server:
# Use the server-to-server filtered path
child_results = await mounted.server._list_prompts()
else:
# Use the manager-to-manager unfiltered path
child_results = await mounted.server._prompt_manager.list_prompts()
# The combination logic is the same for both paths
child_dict = {p.key: p for p in child_results}
if mounted.prefix:
for prompt in child_dict.values():
prefixed_prompt = prompt.with_key(
f"{mounted.prefix}_{prompt.key}"
)
all_prompts[prefixed_prompt.key] = prefixed_prompt
else:
all_prompts.update(child_dict)
except Exception as e:
# Skip failed mounts silently, matches existing behavior
logger.warning(
f"Failed to get prompts from mounted server '{mounted.prefix}': {e}"
)
continue
# Finally, add local prompts, which always take precedence
all_prompts.update(self._prompts)
return all_prompts
async def has_prompt(self, key: str) -> bool:
"""Check if a prompt exists."""
prompts = await self.get_prompts()
return key in prompts
async def get_prompt(self, key: str) -> Prompt:
"""Get prompt by key."""
if key in self._prompts:
return self._prompts[key]
prompts = await self.get_prompts()
if key in prompts:
return prompts[key]
raise NotFoundError(f"Unknown prompt: {key}")
def get_prompts(self) -> dict[str, Prompt]:
"""Get all registered prompts, indexed by registered key."""
return self._prompts
async def get_prompts(self) -> dict[str, Prompt]:
"""
Gets the complete, unfiltered inventory of all prompts.
"""
return await self._load_prompts(via_server=False)
async def list_prompts(self) -> list[Prompt]:
"""
Lists all prompts, applying protocol filtering.
"""
prompts_dict = await self._load_prompts(via_server=True)
return list(prompts_dict.values())
def add_prompt_from_fn(
self,
@ -71,24 +131,22 @@ class PromptManager:
)
return self.add_prompt(prompt) # type: ignore
def add_prompt(self, prompt: Prompt, key: str | None = None) -> Prompt:
def add_prompt(self, prompt: Prompt) -> Prompt:
"""Add a prompt to the manager."""
key = key or prompt.name
# Check for duplicates
existing = self._prompts.get(key)
existing = self._prompts.get(prompt.key)
if existing:
if self.duplicate_behavior == "warn":
logger.warning(f"Prompt already exists: {key}")
self._prompts[key] = prompt
logger.warning(f"Prompt already exists: {prompt.key}")
self._prompts[prompt.key] = prompt
elif self.duplicate_behavior == "replace":
self._prompts[key] = prompt
self._prompts[prompt.key] = prompt
elif self.duplicate_behavior == "error":
raise ValueError(f"Prompt already exists: {key}")
raise ValueError(f"Prompt already exists: {prompt.key}")
elif self.duplicate_behavior == "ignore":
return existing
else:
self._prompts[key] = prompt
self._prompts[prompt.key] = prompt
return prompt
async def render_prompt(
@ -96,30 +154,48 @@ class PromptManager:
name: str,
arguments: dict[str, Any] | None = None,
) -> GetPromptResult:
"""Render a prompt by name with arguments."""
prompt = self.get_prompt(name)
if not prompt:
raise NotFoundError(f"Unknown prompt: {name}")
"""
Internal API for servers: Finds and renders a prompt, respecting the
filtered protocol path.
"""
# 1. Check local prompts first. The server will have already applied its filter.
if name in self._prompts:
prompt = await self.get_prompt(name)
if not prompt:
raise NotFoundError(f"Unknown prompt: {name}")
try:
messages = await prompt.render(arguments)
return GetPromptResult(description=prompt.description, messages=messages)
try:
messages = await prompt.render(arguments)
return GetPromptResult(
description=prompt.description, messages=messages
)
# Pass through PromptErrors as-is
except PromptError as e:
logger.exception(f"Error rendering prompt {name!r}: {e}")
raise e
# Pass through PromptErrors as-is
except PromptError as e:
logger.exception(f"Error rendering prompt {name!r}: {e}")
raise e
# Handle other exceptions
except Exception as e:
logger.exception(f"Error rendering prompt {name!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise PromptError(f"Error rendering prompt {name!r}")
else:
# Include original error details
raise PromptError(f"Error rendering prompt {name!r}: {e}")
# Handle other exceptions
except Exception as e:
logger.exception(f"Error rendering prompt {name!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise PromptError(f"Error rendering prompt {name!r}") from e
else:
# Include original error details
raise PromptError(f"Error rendering prompt {name!r}: {e}") from e
def has_prompt(self, key: str) -> bool:
"""Check if a prompt exists."""
return key in self._prompts
# 2. Check mounted servers using the filtered protocol path.
for mounted in reversed(self._mounted_servers):
prompt_key = name
if mounted.prefix:
if name.startswith(f"{mounted.prefix}_"):
prompt_key = name.removeprefix(f"{mounted.prefix}_")
else:
continue
try:
return await mounted.server._get_prompt(prompt_key, arguments)
except NotFoundError:
continue
raise NotFoundError(f"Unknown prompt: {name}")

View file

@ -1,9 +1,11 @@
"""Resource manager functionality."""
from __future__ import annotations
import inspect
import warnings
from collections.abc import Callable
from typing import Any
from typing import TYPE_CHECKING, Any
from pydantic import AnyUrl
@ -17,6 +19,9 @@ from fastmcp.resources.template import (
from fastmcp.settings import DuplicateBehavior
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
from fastmcp.server.server import MountedServer
logger = get_logger(__name__)
@ -38,6 +43,7 @@ class ResourceManager:
"""
self._resources: dict[str, Resource] = {}
self._templates: dict[str, ResourceTemplate] = {}
self._mounted_servers: list[MountedServer] = []
self.mask_error_details = mask_error_details or settings.mask_error_details
# Default to "warn" if None is provided
@ -51,6 +57,128 @@ class ResourceManager:
)
self.duplicate_behavior = duplicate_behavior
def mount(self, server: MountedServer) -> None:
"""Adds a mounted server as a source for resources and templates."""
self._mounted_servers.append(server)
async def get_resources(self) -> dict[str, Resource]:
"""Get all registered resources, keyed by URI."""
return await self._load_resources(via_server=False)
async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
"""Get all registered templates, keyed by URI template."""
return await self._load_resource_templates(via_server=False)
async def _load_resources(self, *, via_server: bool = False) -> dict[str, Resource]:
"""
The single, consolidated recursive method for fetching resources. The 'via_server'
parameter determines the communication path.
- via_server=False: Manager-to-manager path for complete, unfiltered inventory
- via_server=True: Server-to-server path for filtered MCP requests
"""
all_resources: dict[str, Resource] = {}
for mounted in self._mounted_servers:
try:
if via_server:
# Use the server-to-server filtered path
child_resources_list = await mounted.server._list_resources()
child_resources = {
resource.key: resource for resource in child_resources_list
}
else:
# Use the manager-to-manager unfiltered path
child_resources = (
await mounted.server._resource_manager.get_resources()
)
# Apply prefix if needed
if mounted.prefix:
from fastmcp.server.server import add_resource_prefix
for uri, resource in child_resources.items():
prefixed_uri = add_resource_prefix(
uri, mounted.prefix, mounted.resource_prefix_format
)
# Create a copy of the resource with the prefixed key
prefixed_resource = resource.with_key(prefixed_uri)
all_resources[prefixed_uri] = prefixed_resource
else:
all_resources.update(child_resources)
except Exception as e:
# Skip failed mounts silently, matches existing behavior
logger.warning(
f"Failed to get resources from mounted server '{mounted.prefix}': {e}"
)
continue
# Finally, add local resources, which always take precedence
all_resources.update(self._resources)
return all_resources
async def _load_resource_templates(
self, *, via_server: bool = False
) -> dict[str, ResourceTemplate]:
"""
The single, consolidated recursive method for fetching templates. The 'via_server'
parameter determines the communication path.
- via_server=False: Manager-to-manager path for complete, unfiltered inventory
- via_server=True: Server-to-server path for filtered MCP requests
"""
all_templates: dict[str, ResourceTemplate] = {}
for mounted in self._mounted_servers:
try:
if via_server:
# Use the server-to-server filtered path
child_templates = await mounted.server._list_resource_templates()
else:
# Use the manager-to-manager unfiltered path
child_templates = (
await mounted.server._resource_manager.list_resource_templates()
)
child_dict = {template.key: template for template in child_templates}
# Apply prefix if needed
if mounted.prefix:
from fastmcp.server.server import add_resource_prefix
for uri_template, template in child_dict.items():
prefixed_uri_template = add_resource_prefix(
uri_template, mounted.prefix, mounted.resource_prefix_format
)
# Create a copy of the template with the prefixed key
prefixed_template = template.with_key(prefixed_uri_template)
all_templates[prefixed_uri_template] = prefixed_template
else:
all_templates.update(child_dict)
except Exception as e:
# Skip failed mounts silently, matches existing behavior
logger.warning(
f"Failed to get templates from mounted server '{mounted.prefix}': {e}"
)
continue
# Finally, add local templates, which always take precedence
all_templates.update(self._templates)
return all_templates
async def list_resources(self) -> list[Resource]:
"""
Lists all resources, applying protocol filtering.
"""
resources_dict = await self._load_resources(via_server=True)
return list(resources_dict.values())
async def list_resource_templates(self) -> list[ResourceTemplate]:
"""
Lists all templates, applying protocol filtering.
"""
templates_dict = await self._load_resource_templates(via_server=True)
return list(templates_dict.values())
def add_resource_or_template_from_fn(
self,
fn: Callable[..., Any],
@ -139,35 +267,26 @@ class ResourceManager:
)
return self.add_resource(resource)
def add_resource(self, resource: Resource, key: str | None = None) -> Resource:
def add_resource(self, resource: Resource) -> Resource:
"""Add a resource to the manager.
Args:
resource: A Resource instance to add
key: Optional URI to use as the storage key (if different from resource.uri)
resource: A Resource instance to add. The resource's .key attribute
will be used as the storage key. To overwrite it, call
Resource.with_key() before calling this method.
"""
storage_key = key or str(resource.uri)
logger.debug(
"Adding resource",
extra={
"uri": resource.uri,
"storage_key": storage_key,
"type": type(resource).__name__,
"resource_name": resource.name,
},
)
existing = self._resources.get(storage_key)
existing = self._resources.get(resource.key)
if existing:
if self.duplicate_behavior == "warn":
logger.warning(f"Resource already exists: {storage_key}")
self._resources[storage_key] = resource
logger.warning(f"Resource already exists: {resource.key}")
self._resources[resource.key] = resource
elif self.duplicate_behavior == "replace":
self._resources[storage_key] = resource
self._resources[resource.key] = resource
elif self.duplicate_behavior == "error":
raise ValueError(f"Resource already exists: {storage_key}")
raise ValueError(f"Resource already exists: {resource.key}")
elif self.duplicate_behavior == "ignore":
return existing
self._resources[storage_key] = resource
self._resources[resource.key] = resource
return resource
def add_template_from_fn(
@ -197,52 +316,47 @@ class ResourceManager:
)
return self.add_template(template)
def add_template(
self, template: ResourceTemplate, key: str | None = None
) -> ResourceTemplate:
def add_template(self, template: ResourceTemplate) -> ResourceTemplate:
"""Add a template to the manager.
Args:
template: A ResourceTemplate instance to add
key: Optional URI template to use as the storage key (if different from template.uri_template)
template: A ResourceTemplate instance to add. The template's .key attribute
will be used as the storage key. To overwrite it, call
ResourceTemplate.with_key() before calling this method.
Returns:
The added template. If a template with the same URI already exists,
returns the existing template.
"""
uri_template_str = str(template.uri_template)
storage_key = key or uri_template_str
logger.debug(
"Adding template",
extra={
"uri_template": uri_template_str,
"storage_key": storage_key,
"type": type(template).__name__,
"template_name": template.name,
},
)
existing = self._templates.get(storage_key)
existing = self._templates.get(template.key)
if existing:
if self.duplicate_behavior == "warn":
logger.warning(f"Template already exists: {storage_key}")
self._templates[storage_key] = template
logger.warning(f"Template already exists: {template.key}")
self._templates[template.key] = template
elif self.duplicate_behavior == "replace":
self._templates[storage_key] = template
self._templates[template.key] = template
elif self.duplicate_behavior == "error":
raise ValueError(f"Template already exists: {storage_key}")
raise ValueError(f"Template already exists: {template.key}")
elif self.duplicate_behavior == "ignore":
return existing
self._templates[storage_key] = template
self._templates[template.key] = template
return template
def has_resource(self, uri: AnyUrl | str) -> bool:
async def has_resource(self, uri: AnyUrl | str) -> bool:
"""Check if a resource exists."""
uri_str = str(uri)
if uri_str in self._resources:
# First check concrete resources (local and mounted)
resources = await self.get_resources()
if uri_str in resources:
return True
for template_key in self._templates.keys():
# Then check templates (local and mounted) only if not found in concrete resources
templates = await self.get_resource_templates()
for template_key in templates.keys():
if match_uri_template(uri_str, template_key):
return True
return False
async def get_resource(self, uri: AnyUrl | str) -> Resource:
@ -257,12 +371,14 @@ class ResourceManager:
uri_str = str(uri)
logger.debug("Getting resource", extra={"uri": uri_str})
# First check concrete resources
if resource := self._resources.get(uri_str):
# First check concrete resources (local and mounted)
resources = await self.get_resources()
if resource := resources.get(uri_str):
return resource
# Then check templates - use the utility function to match against storage keys
for storage_key, template in self._templates.items():
# Then check templates (local and mounted) - use the utility function to match against storage keys
templates = await self.get_resource_templates()
for storage_key, template in templates.items():
# Try to match against the storage key (which might be a custom key)
if params := match_uri_template(uri_str, storage_key):
try:
@ -289,31 +405,88 @@ class ResourceManager:
raise NotFoundError(f"Unknown resource: {uri_str}")
async def read_resource(self, uri: AnyUrl | str) -> str | bytes:
"""Read a resource contents."""
resource = await self.get_resource(uri)
"""
Internal API for servers: Finds and reads a resource, respecting the
filtered protocol path.
"""
uri_str = str(uri)
try:
return await resource.read()
# 1. Check local resources first. The server will have already applied its filter.
if uri_str in self._resources:
resource = await self.get_resource(uri_str)
if not resource:
raise NotFoundError(f"Resource {uri_str!r} not found")
# raise ResourceErrors as-is
except ResourceError as e:
logger.error(f"Error reading resource {uri!r}: {e}")
raise e
try:
return await resource.read()
# Handle other exceptions
except Exception as e:
logger.error(f"Error reading resource {uri!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise ResourceError(f"Error reading resource {uri!r}") from e
else:
# Include original error details
raise ResourceError(f"Error reading resource {uri!r}: {e}") from e
# raise ResourceErrors as-is
except ResourceError as e:
logger.exception(f"Error reading resource {uri_str!r}: {e}")
raise e
def get_resources(self) -> dict[str, Resource]:
"""Get all registered resources, keyed by URI."""
return self._resources
# Handle other exceptions
except Exception as e:
logger.exception(f"Error reading resource {uri_str!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise ResourceError(f"Error reading resource {uri_str!r}") from e
else:
# Include original error details
raise ResourceError(
f"Error reading resource {uri_str!r}: {e}"
) from e
def get_templates(self) -> dict[str, ResourceTemplate]:
"""Get all registered templates, keyed by URI template."""
return self._templates
# 1b. Check local templates if not found in concrete resources
for key, template in self._templates.items():
if params := match_uri_template(uri_str, key):
try:
resource = await template.create_resource(uri_str, params=params)
return await resource.read()
except ResourceError as e:
logger.exception(
f"Error reading resource from template {uri_str!r}: {e}"
)
raise e
except Exception as e:
logger.exception(
f"Error reading resource from template {uri_str!r}: {e}"
)
if self.mask_error_details:
raise ResourceError(
f"Error reading resource from template {uri_str!r}"
) from e
else:
raise ResourceError(
f"Error reading resource from template {uri_str!r}: {e}"
) from e
# 2. Check mounted servers using the filtered protocol path.
from fastmcp.server.server import has_resource_prefix, remove_resource_prefix
for mounted in reversed(self._mounted_servers):
key = uri_str
try:
if mounted.prefix:
if has_resource_prefix(
key,
mounted.prefix,
mounted.resource_prefix_format,
):
key = remove_resource_prefix(
key,
mounted.prefix,
mounted.resource_prefix_format,
)
else:
continue
try:
result = await mounted.server._read_resource(key)
return result[0].content
except NotFoundError:
continue
except NotFoundError:
continue
raise NotFoundError(f"Resource {uri_str!r} not found.")

View file

@ -62,6 +62,9 @@ class ResourceTemplate(FastMCPComponent):
description="JSON schema for function parameters"
)
def __repr__(self) -> str:
return f"{self.__class__.__name__}(uri_template={self.uri_template!r}, name={self.name!r}, description={self.description!r}, tags={self.tags})"
@staticmethod
def from_function(
fn: Callable[..., Any],
@ -128,6 +131,19 @@ class ResourceTemplate(FastMCPComponent):
}
return MCPResourceTemplate(**kwargs | overrides)
@classmethod
def from_mcp_template(cls, mcp_template: MCPResourceTemplate) -> ResourceTemplate:
"""Creates a FastMCP ResourceTemplate from a raw MCP ResourceTemplate object."""
# Note: This creates a simple ResourceTemplate instance. For function-based templates,
# the original function is lost, which is expected for remote templates.
return cls(
uri_template=mcp_template.uriTemplate,
name=mcp_template.name,
description=mcp_template.description,
mime_type=mcp_template.mimeType or "text/plain",
parameters={}, # Remote templates don't have local parameters
)
@property
def key(self) -> str:
"""

View file

@ -8,6 +8,7 @@ from dataclasses import dataclass
from mcp import LoggingLevel
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.server.lowlevel.server import request_ctx
from mcp.shared.context import RequestContext
from mcp.types import (
CreateMessageResult,
@ -95,8 +96,14 @@ class Context:
@property
def request_context(self) -> RequestContext:
"""Access to the underlying request context."""
return self.fastmcp._mcp_server.request_context
"""Access to the underlying request context.
If called outside of a request context, this will raise a ValueError.
"""
try:
return request_ctx.get()
except LookupError:
raise ValueError("Context is not available outside of a request")
async def report_progress(
self, progress: float, total: float | None = None, message: str | None = None

View file

@ -0,0 +1,236 @@
from __future__ import annotations
import logging
from collections.abc import Awaitable
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
Protocol,
TypeVar,
runtime_checkable,
)
import mcp.types as mt
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.tools.tool import Tool
if TYPE_CHECKING:
from fastmcp.server.context import Context
logger = logging.getLogger(__name__)
T = TypeVar("T")
R = TypeVar("R", covariant=True)
@runtime_checkable
class CallNext(Protocol[T, R]):
def __call__(self, context: MiddlewareContext[T]) -> Awaitable[R]: ...
ServerResultT = TypeVar(
"ServerResultT",
bound=mt.EmptyResult
| mt.InitializeResult
| mt.CompleteResult
| mt.GetPromptResult
| mt.ListPromptsResult
| mt.ListResourcesResult
| mt.ListResourceTemplatesResult
| mt.ReadResourceResult
| mt.CallToolResult
| mt.ListToolsResult,
)
@dataclass(kw_only=True)
class CallToolResult:
content: list[mt.Content]
isError: bool = False
@dataclass(kw_only=True)
class ListToolsResult:
tools: dict[str, Tool]
@dataclass(kw_only=True)
class ListResourcesResult:
resources: list[Resource]
@dataclass(kw_only=True)
class ListResourceTemplatesResult:
resource_templates: list[ResourceTemplate]
@dataclass(kw_only=True)
class ListPromptsResult:
prompts: list[Prompt]
@runtime_checkable
class ServerResultProtocol(Protocol[ServerResultT]):
root: ServerResultT
@dataclass(kw_only=True, frozen=True)
class MiddlewareContext(Generic[T]):
"""
Unified context for all middleware operations.
"""
message: T
fastmcp_context: Context | None = None
# Common metadata
source: Literal["client", "server"] = "client"
type: Literal["request", "notification"] = "request"
method: str | None = None
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
def copy(self, **kwargs: Any) -> MiddlewareContext[T]:
return replace(self, **kwargs)
def make_middleware_wrapper(
middleware: Middleware, call_next: CallNext[T, R]
) -> CallNext[T, R]:
"""Create a wrapper that applies a single middleware to a context. The
closure bakes in the middleware and call_next function, so it can be
passed to other functions that expect a call_next function."""
async def wrapper(context: MiddlewareContext[T]) -> R:
return await middleware(context, call_next)
return wrapper
class Middleware:
"""Base class for FastMCP middleware with dispatching hooks."""
async def __call__(
self,
context: MiddlewareContext[T],
call_next: CallNext[T, Any],
) -> Any:
"""Main entry point that orchestrates the pipeline."""
handler_chain = await self._dispatch_handler(
context,
call_next=call_next,
)
return await handler_chain(context)
async def _dispatch_handler(
self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]
) -> CallNext[Any, Any]:
"""Builds a chain of handlers for a given message."""
handler = call_next
match context.method:
case "tools/call":
handler = partial(self.on_call_tool, call_next=handler)
case "resources/read":
handler = partial(self.on_read_resource, call_next=handler)
case "prompts/get":
handler = partial(self.on_get_prompt, call_next=handler)
case "tools/list":
handler = partial(self.on_list_tools, call_next=handler)
case "resources/list":
handler = partial(self.on_list_resources, call_next=handler)
case "resources/templates/list":
handler = partial(self.on_list_resource_templates, call_next=handler)
case "prompts/list":
handler = partial(self.on_list_prompts, call_next=handler)
match context.type:
case "request":
handler = partial(self.on_request, call_next=handler)
case "notification":
handler = partial(self.on_notification, call_next=handler)
handler = partial(self.on_message, call_next=handler)
return handler
async def on_message(
self,
context: MiddlewareContext[Any],
call_next: CallNext[Any, Any],
) -> Any:
return await call_next(context)
async def on_request(
self,
context: MiddlewareContext[mt.Request],
call_next: CallNext[mt.Request, Any],
) -> Any:
return await call_next(context)
async def on_notification(
self,
context: MiddlewareContext[mt.Notification],
call_next: CallNext[mt.Notification, Any],
) -> Any:
return await call_next(context)
async def on_call_tool(
self,
context: MiddlewareContext[mt.CallToolRequestParams],
call_next: CallNext[mt.CallToolRequestParams, mt.CallToolResult],
) -> mt.CallToolResult:
return await call_next(context)
async def on_read_resource(
self,
context: MiddlewareContext[mt.ReadResourceRequestParams],
call_next: CallNext[mt.ReadResourceRequestParams, mt.ReadResourceResult],
) -> mt.ReadResourceResult:
return await call_next(context)
async def on_get_prompt(
self,
context: MiddlewareContext[mt.GetPromptRequestParams],
call_next: CallNext[mt.GetPromptRequestParams, mt.GetPromptResult],
) -> mt.GetPromptResult:
return await call_next(context)
async def on_list_tools(
self,
context: MiddlewareContext[mt.ListToolsRequest],
call_next: CallNext[mt.ListToolsRequest, ListToolsResult],
) -> ListToolsResult:
return await call_next(context)
async def on_list_resources(
self,
context: MiddlewareContext[mt.ListResourcesRequest],
call_next: CallNext[mt.ListResourcesRequest, ListResourcesResult],
) -> ListResourcesResult:
return await call_next(context)
async def on_list_resource_templates(
self,
context: MiddlewareContext[mt.ListResourceTemplatesRequest],
call_next: CallNext[
mt.ListResourceTemplatesRequest, ListResourceTemplatesResult
],
) -> ListResourceTemplatesResult:
return await call_next(context)
async def on_list_prompts(
self,
context: MiddlewareContext[mt.ListPromptsRequest],
call_next: CallNext[mt.ListPromptsRequest, ListPromptsResult],
) -> ListPromptsResult:
return await call_next(context)

View file

@ -4,7 +4,6 @@ from typing import TYPE_CHECKING, Any, cast
from urllib.parse import quote
import mcp.types
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.shared.exceptions import McpError
from mcp.types import (
METHOD_NOT_FOUND,
@ -17,10 +16,14 @@ from pydantic.networks import AnyUrl
from fastmcp.client import Client
from fastmcp.exceptions import NotFoundError, ResourceError, ToolError
from fastmcp.prompts import Prompt, PromptMessage
from fastmcp.prompts.prompt import PromptArgument
from fastmcp.prompts.prompt_manager import PromptManager
from fastmcp.resources import Resource, ResourceTemplate
from fastmcp.resources.resource_manager import ResourceManager
from fastmcp.server.context import Context
from fastmcp.server.server import FastMCP
from fastmcp.tools.tool import Tool
from fastmcp.tools.tool_manager import ToolManager
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import MCPContent
@ -30,18 +33,197 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
class ProxyToolManager(ToolManager):
"""A ToolManager that sources its tools from a remote client in addition to local and mounted tools."""
def __init__(self, client: Client, **kwargs):
super().__init__(**kwargs)
self.client = client
async def get_tools(self) -> dict[str, Tool]:
"""Gets the unfiltered tool inventory including local, mounted, and proxy tools."""
# First get local and mounted tools from parent
all_tools = await super().get_tools()
# Then add proxy tools, but don't overwrite existing ones
try:
async with self.client:
client_tools = await self.client.list_tools()
for tool in client_tools:
if tool.name not in all_tools:
all_tools[tool.name] = ProxyTool.from_mcp_tool(
self.client, tool
)
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
pass # No tools available from proxy
else:
raise e
return all_tools
async def list_tools(self) -> list[Tool]:
"""Gets the filtered list of tools including local, mounted, and proxy tools."""
tools_dict = await self.get_tools()
return list(tools_dict.values())
async def call_tool(self, key: str, arguments: dict[str, Any]) -> list[MCPContent]:
"""Calls a tool, trying local/mounted first, then proxy if not found."""
try:
# First try local and mounted tools
return await super().call_tool(key, arguments)
except NotFoundError:
# If not found locally, try proxy
async with self.client:
return await self.client.call_tool(key, arguments)
class ProxyResourceManager(ResourceManager):
"""A ResourceManager that sources its resources from a remote client in addition to local and mounted resources."""
def __init__(self, client: Client, **kwargs):
super().__init__(**kwargs)
self.client = client
async def get_resources(self) -> dict[str, Resource]:
"""Gets the unfiltered resource inventory including local, mounted, and proxy resources."""
# First get local and mounted resources from parent
all_resources = await super().get_resources()
# Then add proxy resources, but don't overwrite existing ones
try:
async with self.client:
client_resources = await self.client.list_resources()
for resource in client_resources:
if str(resource.uri) not in all_resources:
all_resources[str(resource.uri)] = (
ProxyResource.from_mcp_resource(self.client, resource)
)
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
pass # No resources available from proxy
else:
raise e
return all_resources
async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
"""Gets the unfiltered template inventory including local, mounted, and proxy templates."""
# First get local and mounted templates from parent
all_templates = await super().get_resource_templates()
# Then add proxy templates, but don't overwrite existing ones
try:
async with self.client:
client_templates = await self.client.list_resource_templates()
for template in client_templates:
if template.uriTemplate not in all_templates:
all_templates[template.uriTemplate] = (
ProxyTemplate.from_mcp_template(self.client, template)
)
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
pass # No templates available from proxy
else:
raise e
return all_templates
async def list_resources(self) -> list[Resource]:
"""Gets the filtered list of resources including local, mounted, and proxy resources."""
resources_dict = await self.get_resources()
return list(resources_dict.values())
async def list_resource_templates(self) -> list[ResourceTemplate]:
"""Gets the filtered list of templates including local, mounted, and proxy templates."""
templates_dict = await self.get_resource_templates()
return list(templates_dict.values())
async def read_resource(self, uri: AnyUrl | str) -> str | bytes:
"""Reads a resource, trying local/mounted first, then proxy if not found."""
try:
# First try local and mounted resources
return await super().read_resource(uri)
except NotFoundError:
# If not found locally, try proxy
async with self.client:
result = await self.client.read_resource(uri)
if isinstance(result[0], TextResourceContents):
return result[0].text
elif isinstance(result[0], BlobResourceContents):
return result[0].blob
else:
raise ResourceError(f"Unsupported content type: {type(result[0])}")
class ProxyPromptManager(PromptManager):
"""A PromptManager that sources its prompts from a remote client in addition to local and mounted prompts."""
def __init__(self, client: Client, **kwargs):
super().__init__(**kwargs)
self.client = client
async def get_prompts(self) -> dict[str, Prompt]:
"""Gets the unfiltered prompt inventory including local, mounted, and proxy prompts."""
# First get local and mounted prompts from parent
all_prompts = await super().get_prompts()
# Then add proxy prompts, but don't overwrite existing ones
try:
async with self.client:
client_prompts = await self.client.list_prompts()
for prompt in client_prompts:
if prompt.name not in all_prompts:
all_prompts[prompt.name] = ProxyPrompt.from_mcp_prompt(
self.client, prompt
)
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
pass # No prompts available from proxy
else:
raise e
return all_prompts
async def list_prompts(self) -> list[Prompt]:
"""Gets the filtered list of prompts including local, mounted, and proxy prompts."""
prompts_dict = await self.get_prompts()
return list(prompts_dict.values())
async def render_prompt(
self,
name: str,
arguments: dict[str, Any] | None = None,
) -> GetPromptResult:
"""Renders a prompt, trying local/mounted first, then proxy if not found."""
try:
# First try local and mounted prompts
return await super().render_prompt(name, arguments)
except NotFoundError:
# If not found locally, try proxy
async with self.client:
result = await self.client.get_prompt(name, arguments)
return result
class ProxyTool(Tool):
"""
A Tool that represents and executes a tool on a remote server.
"""
def __init__(self, client: Client, **kwargs):
super().__init__(**kwargs)
self._client = client
@classmethod
async def from_client(cls, client: Client, tool: mcp.types.Tool) -> ProxyTool:
def from_mcp_tool(cls, client: Client, mcp_tool: mcp.types.Tool) -> ProxyTool:
"""Factory method to create a ProxyTool from a raw MCP tool schema."""
return cls(
client=client,
name=tool.name,
description=tool.description,
parameters=tool.inputSchema,
name=mcp_tool.name,
description=mcp_tool.description,
parameters=mcp_tool.inputSchema,
annotations=mcp_tool.annotations,
)
async def run(
@ -49,8 +231,8 @@ class ProxyTool(Tool):
arguments: dict[str, Any],
context: Context | None = None,
) -> list[MCPContent]:
# the client context manager will swallow any exceptions inside a TaskGroup
# so we return the raw result and raise an exception ourselves
"""Executes the tool by making a call through the client."""
# This is where the remote execution logic lives.
async with self._client:
result = await self._client.call_tool_mcp(
name=self.name,
@ -62,6 +244,10 @@ class ProxyTool(Tool):
class ProxyResource(Resource):
"""
A Resource that represents and reads a resource from a remote server.
"""
_client: Client
_value: str | bytes | None = None
@ -71,18 +257,20 @@ class ProxyResource(Resource):
self._value = _value
@classmethod
async def from_client(
cls, client: Client, resource: mcp.types.Resource
def from_mcp_resource(
cls, client: Client, mcp_resource: mcp.types.Resource
) -> ProxyResource:
"""Factory method to create a ProxyResource from a raw MCP resource schema."""
return cls(
client=client,
uri=resource.uri,
name=resource.name,
description=resource.description,
mime_type=resource.mimeType,
uri=mcp_resource.uri,
name=mcp_resource.name,
description=mcp_resource.description,
mime_type=mcp_resource.mimeType or "text/plain",
)
async def read(self) -> str | bytes:
"""Read the resource content from the remote server."""
if self._value is not None:
return self._value
@ -97,20 +285,26 @@ class ProxyResource(Resource):
class ProxyTemplate(ResourceTemplate):
"""
A ResourceTemplate that represents and creates resources from a remote server template.
"""
def __init__(self, client: Client, **kwargs):
super().__init__(**kwargs)
self._client = client
@classmethod
async def from_client(
cls, client: Client, template: mcp.types.ResourceTemplate
def from_mcp_template(
cls, client: Client, mcp_template: mcp.types.ResourceTemplate
) -> ProxyTemplate:
"""Factory method to create a ProxyTemplate from a raw MCP template schema."""
return cls(
client=client,
uri_template=template.uriTemplate,
name=template.name,
description=template.description,
parameters={},
uri_template=mcp_template.uriTemplate,
name=mcp_template.name,
description=mcp_template.description,
mime_type=mcp_template.mimeType or "text/plain",
parameters={}, # Remote templates don't have local parameters
)
async def create_resource(
@ -119,6 +313,7 @@ class ProxyTemplate(ResourceTemplate):
params: dict[str, Any],
context: Context | None = None,
) -> ProxyResource:
"""Create a resource from the template by calling the remote server."""
# don't use the provided uri, because it may not be the same as the
# uri_template on the remote server.
# quote params to ensure they are valid for the uri_template
@ -146,6 +341,10 @@ class ProxyTemplate(ResourceTemplate):
class ProxyPrompt(Prompt):
"""
A Prompt that represents and renders a prompt from a remote server.
"""
_client: Client
def __init__(self, client: Client, **kwargs):
@ -153,139 +352,50 @@ class ProxyPrompt(Prompt):
self._client = client
@classmethod
async def from_client(cls, client: Client, prompt: mcp.types.Prompt) -> ProxyPrompt:
def from_mcp_prompt(
cls, client: Client, mcp_prompt: mcp.types.Prompt
) -> ProxyPrompt:
"""Factory method to create a ProxyPrompt from a raw MCP prompt schema."""
arguments = [
PromptArgument(
name=arg.name,
description=arg.description,
required=arg.required or False,
)
for arg in mcp_prompt.arguments or []
]
return cls(
client=client,
name=prompt.name,
description=prompt.description,
arguments=[a.model_dump() for a in prompt.arguments or []],
name=mcp_prompt.name,
description=mcp_prompt.description,
arguments=arguments,
)
async def render(self, arguments: dict[str, Any]) -> list[PromptMessage]:
"""Render the prompt by making a call through the client."""
async with self._client:
result = await self._client.get_prompt(self.name, arguments)
return result.messages
class FastMCPProxy(FastMCP):
"""
A FastMCP server that acts as a proxy to a remote MCP-compliant server.
It uses specialized managers that fulfill requests via an HTTP client.
"""
def __init__(self, client: Client, **kwargs):
"""
Initializes the proxy server.
Args:
client: The FastMCP client connected to the backend server.
**kwargs: Additional settings for the FastMCP server.
"""
super().__init__(**kwargs)
self.client = client
async def get_tools(self) -> dict[str, Tool]:
tools = await super().get_tools()
async with self.client:
try:
client_tools = await self.client.list_tools()
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
client_tools = []
else:
raise e
for tool in client_tools:
# don't overwrite tools defined in the server
if tool.name not in tools:
tool_proxy = await ProxyTool.from_client(self.client, tool)
tools[tool_proxy.name] = tool_proxy
return tools
async def get_resources(self) -> dict[str, Resource]:
resources = await super().get_resources()
async with self.client:
try:
client_resources = await self.client.list_resources()
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
client_resources = []
else:
raise e
for resource in client_resources:
# don't overwrite resources defined in the server
if str(resource.uri) not in resources:
resource_proxy = await ProxyResource.from_client(
self.client, resource
)
resources[str(resource_proxy.uri)] = resource_proxy
return resources
async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
templates = await super().get_resource_templates()
async with self.client:
try:
client_templates = await self.client.list_resource_templates()
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
client_templates = []
else:
raise e
for template in client_templates:
# don't overwrite templates defined in the server
if template.uriTemplate not in templates:
template_proxy = await ProxyTemplate.from_client(
self.client, template
)
templates[template_proxy.uri_template] = template_proxy
return templates
async def get_prompts(self) -> dict[str, Prompt]:
prompts = await super().get_prompts()
async with self.client:
try:
client_prompts = await self.client.list_prompts()
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
client_prompts = []
else:
raise e
for prompt in client_prompts:
# don't overwrite prompts defined in the server
if prompt.name not in prompts:
prompt_proxy = await ProxyPrompt.from_client(self.client, prompt)
prompts[prompt_proxy.name] = prompt_proxy
return prompts
async def _call_tool(self, key: str, arguments: dict[str, Any]) -> list[MCPContent]:
try:
result = await super()._call_tool(key, arguments)
return result
except NotFoundError:
async with self.client:
result = await self.client.call_tool(key, arguments)
return result
async def _read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
try:
result = await super()._read_resource(uri)
return result
except NotFoundError:
async with self.client:
resource = await self.client.read_resource(uri)
if isinstance(resource[0], TextResourceContents):
content = resource[0].text
elif isinstance(resource[0], BlobResourceContents):
content = resource[0].blob
else:
raise ValueError(f"Unsupported content type: {type(resource[0])}")
return [
ReadResourceContents(content=content, mime_type=resource[0].mimeType)
]
async def _get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
try:
result = await super()._get_prompt(name, arguments)
return result
except NotFoundError:
async with self.client:
result = await self.client.get_prompt(name, arguments)
return result
# Replace the default managers with our specialized proxy managers.
self._tool_manager = ProxyToolManager(client=self.client)
self._resource_manager = ProxyResourceManager(client=self.client)
self._prompt_manager = ProxyPromptManager(client=self.client)

View file

@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Generic, Literal, cast, overload
import anyio
import httpx
import mcp.types
import uvicorn
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.server.lowlevel.server import LifespanResultT, NotificationOptions
@ -34,7 +35,7 @@ from mcp.types import Resource as MCPResource
from mcp.types import ResourceTemplate as MCPResourceTemplate
from mcp.types import Tool as MCPTool
from pydantic import AnyUrl
from starlette.middleware import Middleware
from starlette.middleware import Middleware as ASGIMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Route
@ -53,6 +54,7 @@ from fastmcp.server.http import (
create_sse_app,
create_streamable_http_app,
)
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.settings import Settings
from fastmcp.tools import ToolManager
from fastmcp.tools.tool import FunctionTool, Tool
@ -115,6 +117,7 @@ class FastMCP(Generic[LifespanResultT]):
*,
version: str | None = None,
auth: OAuthProvider | None = None,
middleware: list[Middleware] | None = None,
lifespan: (
Callable[
[FastMCP[LifespanResultT]],
@ -155,7 +158,6 @@ class FastMCP(Generic[LifespanResultT]):
self._cache = TimedCache(
expiration=datetime.timedelta(seconds=cache_expiration_seconds or 0)
)
self._mounted_servers: list[MountedServer] = []
self._additional_http_routes: list[BaseRoute] = []
self._tool_manager = ToolManager(
duplicate_behavior=on_duplicate_tools,
@ -196,6 +198,8 @@ class FastMCP(Generic[LifespanResultT]):
self.include_tags = include_tags
self.exclude_tags = exclude_tags
self.middleware = middleware or []
# Set up MCP protocol handlers
self._setup_handlers()
self.dependencies = dependencies or fastmcp.settings.server_dependencies
@ -319,30 +323,23 @@ class FastMCP(Generic[LifespanResultT]):
self._mcp_server.read_resource()(self._mcp_read_resource)
self._mcp_server.get_prompt()(self._mcp_get_prompt)
async def _apply_middleware(
self,
context: MiddlewareContext[Any],
call_next: Callable[[MiddlewareContext[Any]], Awaitable[Any]],
) -> Any:
"""Builds and executes the middleware chain."""
chain = call_next
for mw in reversed(self.middleware):
chain = partial(mw, call_next=chain)
return await chain(context)
def add_middleware(self, middleware: Middleware) -> None:
self.middleware.append(middleware)
async def get_tools(self) -> dict[str, Tool]:
"""Get all registered tools, indexed by registered key."""
if (tools := self._cache.get("tools")) is self._cache.NOT_FOUND:
tools: dict[str, Tool] = {}
# iterate such that new mounts overwrite older ones
for mounted_server in self._mounted_servers:
try:
server_tools = await mounted_server.server.get_tools()
# Apply prefix to each tool key if prefix exists and is not empty
if mounted_server.prefix:
for tool in server_tools.values():
tool = tool.with_key(f"{mounted_server.prefix}_{tool.key}")
tools[tool.key] = tool
else:
tools.update(server_tools)
except Exception as e:
logger.warning(
f"Failed to get tools from mounted server '{mounted_server.prefix}': {e}"
)
continue
tools.update(self._tool_manager.get_tools())
self._cache.set("tools", tools)
return tools
return await self._tool_manager.get_tools()
async def get_tool(self, key: str) -> Tool:
tools = await self.get_tools()
@ -352,34 +349,7 @@ class FastMCP(Generic[LifespanResultT]):
async def get_resources(self) -> dict[str, Resource]:
"""Get all registered resources, indexed by registered key."""
if (resources := self._cache.get("resources")) is self._cache.NOT_FOUND:
resources: dict[str, Resource] = {}
# iterate such that new mounts overwrite older ones
for mounted_server in self._mounted_servers:
try:
server_resources = await mounted_server.server.get_resources()
# Apply prefix to each resource key if prefix exists
if mounted_server.prefix:
for resource in server_resources.values():
resource = resource.with_key(
add_resource_prefix(
resource.key,
mounted_server.prefix,
self.resource_prefix_format,
)
)
resources[resource.key] = resource
else:
resources.update(server_resources)
except Exception as e:
logger.warning(
f"Failed to get resources from mounted server '{mounted_server.prefix}': {e}"
)
continue
resources.update(self._resource_manager.get_resources())
self._cache.set("resources", resources)
return resources
return await self._resource_manager.get_resources()
async def get_resource(self, key: str) -> Resource:
resources = await self.get_resources()
@ -389,39 +359,7 @@ class FastMCP(Generic[LifespanResultT]):
async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
"""Get all registered resource templates, indexed by registered key."""
if (
templates := self._cache.get("resource_templates")
) is self._cache.NOT_FOUND:
templates: dict[str, ResourceTemplate] = {}
# iterate such that new mounts overwrite older ones
for mounted_server in self._mounted_servers:
try:
server_templates = (
await mounted_server.server.get_resource_templates()
)
# Apply prefix to each template key if prefix exists
if mounted_server.prefix:
for template in server_templates.values():
template = template.with_key(
add_resource_prefix(
template.key,
mounted_server.prefix,
self.resource_prefix_format,
)
)
templates[template.key] = template
else:
templates.update(server_templates)
except Exception as e:
logger.warning(
"Failed to get resource templates from mounted server "
f"'{mounted_server.prefix}': {e}"
)
continue
templates.update(self._resource_manager.get_templates())
self._cache.set("resource_templates", templates)
return templates
return await self._resource_manager.get_resource_templates()
async def get_resource_template(self, key: str) -> ResourceTemplate:
templates = await self.get_resource_templates()
@ -433,31 +371,7 @@ class FastMCP(Generic[LifespanResultT]):
"""
List all available prompts.
"""
if (prompts := self._cache.get("prompts")) is self._cache.NOT_FOUND:
prompts: dict[str, Prompt] = {}
# iterate such that new mounts overwrite older ones
for mounted_server in self._mounted_servers:
try:
server_prompts = await mounted_server.server.get_prompts()
# Apply prefix to each prompt key if prefix exists
if mounted_server.prefix:
for prompt in server_prompts.values():
prompt = prompt.with_key(
f"{mounted_server.prefix}_{prompt.key}"
)
prompts[prompt.key] = prompt
else:
prompts.update(server_prompts)
except Exception as e:
logger.warning(
f"Failed to get prompts from mounted server '{mounted_server.prefix}': {e}"
)
continue
prompts.update(self._prompt_manager.get_prompts())
self._cache.set("prompts", prompts)
return prompts
return await self._prompt_manager.get_prompts()
async def get_prompt(self, key: str) -> Prompt:
prompts = await self.get_prompts()
@ -510,59 +424,165 @@ class FastMCP(Generic[LifespanResultT]):
return decorator
async def _mcp_list_tools(self) -> list[MCPTool]:
logger.debug("Handler called: list_tools")
with fastmcp.server.context.Context(fastmcp=self):
tools = await self._list_tools()
return [tool.to_mcp_tool(name=tool.key) for tool in tools]
async def _list_tools(self) -> list[Tool]:
"""
List all available tools, in the format expected by the low-level MCP
server.
"""
tools = await self.get_tools()
mcp_tools: list[MCPTool] = []
for key, tool in tools.items():
if self._should_enable_component(tool):
mcp_tools.append(tool.to_mcp_tool(name=key))
async def _handler(
context: MiddlewareContext[mcp.types.ListToolsRequest],
) -> list[Tool]:
tools = await self._tool_manager.list_tools() # type: ignore[reportPrivateUsage]
return mcp_tools
mcp_tools: list[Tool] = []
for tool in tools:
if self._should_enable_component(tool):
mcp_tools.append(tool)
return mcp_tools
with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
# Create the middleware context.
mw_context = MiddlewareContext(
message=mcp.types.ListToolsRequest(method="tools/list"),
source="client",
type="request",
method="tools/list",
fastmcp_context=fastmcp_ctx,
)
# Apply the middleware chain.
return await self._apply_middleware(mw_context, _handler)
async def _mcp_list_resources(self) -> list[MCPResource]:
logger.debug("Handler called: list_resources")
with fastmcp.server.context.Context(fastmcp=self):
resources = await self._list_resources()
return [
resource.to_mcp_resource(uri=resource.key) for resource in resources
]
async def _list_resources(self) -> list[Resource]:
"""
List all available resources, in the format expected by the low-level MCP
server.
"""
resources = await self.get_resources()
mcp_resources: list[MCPResource] = []
for key, resource in resources.items():
if self._should_enable_component(resource):
mcp_resources.append(resource.to_mcp_resource(uri=key))
return mcp_resources
async def _handler(
context: MiddlewareContext[dict[str, Any]],
) -> list[Resource]:
resources = await self._resource_manager.list_resources() # type: ignore[reportPrivateUsage]
mcp_resources: list[Resource] = []
for resource in resources:
if self._should_enable_component(resource):
mcp_resources.append(resource)
return mcp_resources
with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
# Create the middleware context.
mw_context = MiddlewareContext(
message={}, # List resources doesn't have parameters
source="client",
type="request",
method="resources/list",
fastmcp_context=fastmcp_ctx,
)
# Apply the middleware chain.
return await self._apply_middleware(mw_context, _handler)
async def _mcp_list_resource_templates(self) -> list[MCPResourceTemplate]:
logger.debug("Handler called: list_resource_templates")
with fastmcp.server.context.Context(fastmcp=self):
templates = await self._list_resource_templates()
return [
template.to_mcp_template(uriTemplate=template.key)
for template in templates
]
async def _list_resource_templates(self) -> list[ResourceTemplate]:
"""
List all available resource templates, in the format expected by the low-level
MCP server.
List all available resource templates, in the format expected by the low-level MCP
server.
"""
templates = await self.get_resource_templates()
mcp_templates: list[MCPResourceTemplate] = []
for key, template in templates.items():
if self._should_enable_component(template):
mcp_templates.append(template.to_mcp_template(uriTemplate=key))
return mcp_templates
async def _handler(
context: MiddlewareContext[dict[str, Any]],
) -> list[ResourceTemplate]:
templates = await self._resource_manager.list_resource_templates()
mcp_templates: list[ResourceTemplate] = []
for template in templates:
if self._should_enable_component(template):
mcp_templates.append(template)
return mcp_templates
with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
# Create the middleware context.
mw_context = MiddlewareContext(
message={}, # List resource templates doesn't have parameters
source="client",
type="request",
method="resources/templates/list",
fastmcp_context=fastmcp_ctx,
)
# Apply the middleware chain.
return await self._apply_middleware(mw_context, _handler)
async def _mcp_list_prompts(self) -> list[MCPPrompt]:
logger.debug("Handler called: list_prompts")
with fastmcp.server.context.Context(fastmcp=self):
prompts = await self._list_prompts()
return [prompt.to_mcp_prompt(name=prompt.key) for prompt in prompts]
async def _list_prompts(self) -> list[Prompt]:
"""
List all available prompts, in the format expected by the low-level MCP
server.
"""
prompts = await self.get_prompts()
mcp_prompts: list[MCPPrompt] = []
for key, prompt in prompts.items():
if self._should_enable_component(prompt):
mcp_prompts.append(prompt.to_mcp_prompt(name=key))
return mcp_prompts
async def _handler(
context: MiddlewareContext[mcp.types.ListPromptsRequest],
) -> list[Prompt]:
prompts = await self._prompt_manager.list_prompts() # type: ignore[reportPrivateUsage]
mcp_prompts: list[Prompt] = []
for prompt in prompts:
if self._should_enable_component(prompt):
mcp_prompts.append(prompt)
return mcp_prompts
with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
# Create the middleware context.
mw_context = MiddlewareContext(
message=mcp.types.ListPromptsRequest(method="prompts/list"),
source="client",
type="request",
method="prompts/list",
fastmcp_context=fastmcp_ctx,
)
# Apply the middleware chain.
return await self._apply_middleware(mw_context, _handler)
async def _mcp_call_tool(
self, key: str, arguments: dict[str, Any]
@ -579,56 +599,40 @@ class FastMCP(Generic[LifespanResultT]):
Returns:
List of MCP Content objects containing the tool results
"""
logger.debug("Call tool: %s with %s", key, arguments)
logger.debug("Handler called: call_tool %s with %s", key, arguments)
# Create and use context for the entire call
with fastmcp.server.context.Context(fastmcp=self):
try:
return await self._call_tool(key, arguments)
except DisabledError:
# convert to NotFoundError to avoid leaking tool presence
raise NotFoundError(f"Unknown tool: {key}")
except NotFoundError:
# standardize NotFound message
raise NotFoundError(f"Unknown tool: {key}")
async def _call_tool(self, key: str, arguments: dict[str, Any]) -> list[MCPContent]:
"""
Call a tool with raw MCP arguments. FastMCP subclasses should override
this method, not _mcp_call_tool.
Args:
key: The name of the tool to call arguments: Arguments to pass to
the tool
Returns:
List of MCP Content objects containing the tool results
Applies this server's middleware and delegates the filtered call to the manager.
"""
# Get tool, checking first from our tools, then from the mounted servers
if self._tool_manager.has_tool(key):
tool = self._tool_manager.get_tool(key)
async def _handler(
context: MiddlewareContext[mcp.types.CallToolRequestParams],
) -> list[MCPContent]:
tool = await self._tool_manager.get_tool(context.message.name)
if not self._should_enable_component(tool):
raise DisabledError(f"Tool {key!r} is disabled")
return await self._tool_manager.call_tool(key, arguments)
raise NotFoundError(f"Unknown tool: {context.message.name!r}")
# Check mounted servers to see if they have the tool
# iterate such that new mounts take precedence over older ones
for mounted_server in reversed(self._mounted_servers):
tool_key = key
try:
# If server has a prefix, check if key matches and strip prefix
if mounted_server.prefix:
if tool_key.startswith(f"{mounted_server.prefix}_"):
tool_key = tool_key.removeprefix(f"{mounted_server.prefix}_")
else:
continue
return await mounted_server.server._call_tool(tool_key, arguments)
except NotFoundError:
# Tool not found on this server, try the next one
continue
return await self._tool_manager.call_tool(
key=context.message.name, arguments=context.message.arguments or {}
)
raise NotFoundError(f"Unknown tool: {key!r}")
mw_context = MiddlewareContext(
message=mcp.types.CallToolRequestParams(name=key, arguments=arguments),
source="client",
type="request",
method="tools/call",
fastmcp_context=fastmcp.server.dependencies.get_context(),
)
return await self._apply_middleware(mw_context, _handler)
async def _mcp_read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
"""
@ -636,7 +640,7 @@ class FastMCP(Generic[LifespanResultT]):
Delegates to _read_resource, which should be overridden by FastMCP subclasses.
"""
logger.debug("Read resource: %s", uri)
logger.debug("Handler called: read_resource %s", uri)
with fastmcp.server.context.Context(fastmcp=self):
try:
@ -650,45 +654,38 @@ class FastMCP(Generic[LifespanResultT]):
async def _read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
"""
Read a resource by URI, in the format expected by the low-level MCP
server.
Applies this server's middleware and delegates the filtered call to the manager.
"""
if self._resource_manager.has_resource(uri):
resource = await self._resource_manager.get_resource(uri)
async def _handler(
context: MiddlewareContext[mcp.types.ReadResourceRequestParams],
) -> list[ReadResourceContents]:
resource = await self._resource_manager.get_resource(context.message.uri)
if not self._should_enable_component(resource):
raise DisabledError(f"Resource {str(uri)!r} is disabled")
content = await self._resource_manager.read_resource(uri)
raise NotFoundError(f"Unknown resource: {str(context.message.uri)!r}")
content = await self._resource_manager.read_resource(context.message.uri)
return [
ReadResourceContents(
content=content,
mime_type=resource.mime_type,
)
]
# Convert string URI to AnyUrl if needed
if isinstance(uri, str):
uri_param = AnyUrl(uri)
else:
# iterate such that new mounts take precedence over older ones
for mounted_server in reversed(self._mounted_servers):
resource_uri = uri
try:
if mounted_server.prefix:
# If server has a prefix, check if URI matches and strip prefix
if has_resource_prefix(
str(resource_uri),
mounted_server.prefix,
self.resource_prefix_format,
):
resource_uri = remove_resource_prefix(
str(resource_uri),
mounted_server.prefix,
self.resource_prefix_format,
)
else:
continue
return await mounted_server.server._mcp_read_resource(resource_uri)
except NotFoundError:
# Resource not found on this server, try the next one
continue
else:
raise NotFoundError(f"Unknown resource: {uri}")
uri_param = uri
mw_context = MiddlewareContext(
message=mcp.types.ReadResourceRequestParams(uri=uri_param),
source="client",
type="request",
method="resources/read",
fastmcp_context=fastmcp.server.dependencies.get_context(),
)
return await self._apply_middleware(mw_context, _handler)
async def _mcp_get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
@ -698,7 +695,7 @@ class FastMCP(Generic[LifespanResultT]):
Delegates to _get_prompt, which should be overridden by FastMCP subclasses.
"""
logger.debug("Get prompt: %s with %s", name, arguments)
logger.debug("Handler called: get_prompt %s with %s", name, arguments)
with fastmcp.server.context.Context(fastmcp=self):
try:
@ -713,45 +710,29 @@ class FastMCP(Generic[LifespanResultT]):
async def _get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
"""Handle MCP 'getPrompt' requests.
Args:
name: The name of the prompt to render
arguments: Arguments to pass to the prompt
Returns:
GetPromptResult containing the rendered prompt messages
"""
logger.debug("Get prompt: %s with %s", name, arguments)
Applies this server's middleware and delegates the filtered call to the manager.
"""
# Get prompt, checking first from our prompts, then from the mounted servers
if self._prompt_manager.has_prompt(name):
prompt = self._prompt_manager.get_prompt(name)
async def _handler(
context: MiddlewareContext[mcp.types.GetPromptRequestParams],
) -> GetPromptResult:
prompt = await self._prompt_manager.get_prompt(context.message.name)
if not self._should_enable_component(prompt):
raise DisabledError(f"Prompt {name!r} is disabled")
return await self._prompt_manager.render_prompt(name, arguments)
raise NotFoundError(f"Unknown prompt: {context.message.name!r}")
# Check mounted servers to see if they have the prompt
# iterate such that new mounts take precedence over older ones
for mounted_server in reversed(self._mounted_servers):
prompt_name = name
try:
if mounted_server.prefix:
# If server has a prefix, check if name matches and strip prefix
if prompt_name.startswith(f"{mounted_server.prefix}_"):
prompt_name = prompt_name.removeprefix(
f"{mounted_server.prefix}_"
)
else:
continue
return await mounted_server.server._mcp_get_prompt(
prompt_name, arguments
)
except NotFoundError:
# Prompt not found on this server, try the next one
continue
return await self._prompt_manager.render_prompt(
name=context.message.name, arguments=context.message.arguments
)
raise NotFoundError(f"Unknown prompt: {name}")
mw_context = MiddlewareContext(
message=mcp.types.GetPromptRequestParams(name=name, arguments=arguments),
source="client",
type="request",
method="prompts/get",
fastmcp_context=fastmcp.server.dependencies.get_context(),
)
return await self._apply_middleware(mw_context, _handler)
def add_tool(self, tool: Tool) -> None:
"""Add a tool to the server.
@ -919,23 +900,23 @@ class FastMCP(Generic[LifespanResultT]):
enabled=enabled,
)
def add_resource(self, resource: Resource, key: str | None = None) -> None:
def add_resource(self, resource: Resource) -> None:
"""Add a resource to the server.
Args:
resource: A Resource instance to add
"""
self._resource_manager.add_resource(resource, key=key)
self._resource_manager.add_resource(resource)
self._cache.clear()
def add_template(self, template: ResourceTemplate, key: str | None = None) -> None:
def add_template(self, template: ResourceTemplate) -> None:
"""Add a resource template to the server.
Args:
template: A ResourceTemplate instance to add
"""
self._resource_manager.add_template(template, key=key)
self._resource_manager.add_template(template)
def add_resource_fn(
self,
@ -1278,7 +1259,7 @@ class FastMCP(Generic[LifespanResultT]):
log_level: str | None = None,
path: str | None = None,
uvicorn_config: dict[str, Any] | None = None,
middleware: list[Middleware] | None = None,
middleware: list[ASGIMiddleware] | None = None,
) -> None:
"""Run the server using HTTP transport.
@ -1349,7 +1330,7 @@ class FastMCP(Generic[LifespanResultT]):
self,
path: str | None = None,
message_path: str | None = None,
middleware: list[Middleware] | None = None,
middleware: list[ASGIMiddleware] | None = None,
) -> StarletteWithLifespan:
"""
Create a Starlette app for the SSE server.
@ -1379,7 +1360,7 @@ class FastMCP(Generic[LifespanResultT]):
def streamable_http_app(
self,
path: str | None = None,
middleware: list[Middleware] | None = None,
middleware: list[ASGIMiddleware] | None = None,
) -> StarletteWithLifespan:
"""
Create a Starlette app for the StreamableHTTP server.
@ -1400,7 +1381,7 @@ class FastMCP(Generic[LifespanResultT]):
def http_app(
self,
path: str | None = None,
middleware: list[Middleware] | None = None,
middleware: list[ASGIMiddleware] | None = None,
json_response: bool | None = None,
stateless_http: bool | None = None,
transport: Literal["streamable-http", "sse"] = "streamable-http",
@ -1584,11 +1565,16 @@ class FastMCP(Generic[LifespanResultT]):
if as_proxy and not isinstance(server, FastMCPProxy):
server = FastMCPProxy(Client(transport=FastMCPTransport(server)))
# Delegate mounting to all three managers
mounted_server = MountedServer(
server=server,
prefix=prefix,
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)
self._cache.clear()
async def import_server(
@ -1682,10 +1668,8 @@ class FastMCP(Generic[LifespanResultT]):
# Import tools from the server
for key, tool in (await server.get_tools()).items():
if prefix:
tool_key = f"{prefix}_{key}"
else:
tool_key = key
self._tool_manager.add_tool(tool, key=tool_key)
tool = tool.with_key(f"{prefix}_{key}")
self._tool_manager.add_tool(tool)
# Import resources and templates from the server
for key, resource in (await server.get_resources()).items():
@ -1693,35 +1677,27 @@ class FastMCP(Generic[LifespanResultT]):
resource_key = add_resource_prefix(
key, prefix, self.resource_prefix_format
)
else:
resource_key = key
self._resource_manager.add_resource(resource, key=resource_key)
resource = resource.with_key(resource_key)
self._resource_manager.add_resource(resource)
for key, template in (await server.get_resource_templates()).items():
if prefix:
template_key = add_resource_prefix(
key, prefix, self.resource_prefix_format
)
else:
template_key = key
self._resource_manager.add_template(template, key=template_key)
template = template.with_key(template_key)
self._resource_manager.add_template(template)
# Import prompts from the server
for key, prompt in (await server.get_prompts()).items():
if prefix:
prompt_key = f"{prefix}_{key}"
else:
prompt_key = key
self._prompt_manager.add_prompt(prompt, key=prompt_key)
prompt = prompt.with_key(f"{prefix}_{key}")
self._prompt_manager.add_prompt(prompt)
if prefix:
logger.info(f"Imported server {server.name} with prefix '{prefix}'")
logger.debug(f"Imported tools with prefix '{prefix}_'")
logger.debug(f"Imported resources and templates with prefix '{prefix}/'")
logger.debug(f"Imported prompts with prefix '{prefix}_'")
logger.debug(f"Imported server {server.name} with prefix '{prefix}'")
else:
logger.info(f"Imported server {server.name}")
logger.debug("Imported tools, resources, templates, and prompts")
logger.debug(f"Imported server {server.name}")
self._cache.clear()
@ -1882,6 +1858,7 @@ class FastMCP(Generic[LifespanResultT]):
class MountedServer:
prefix: str | None
server: FastMCP[Any]
resource_prefix_format: Literal["protocol", "path"] | None = None
def add_resource_prefix(

View file

@ -1,4 +1,4 @@
from __future__ import annotations as _annotations
from __future__ import annotations
import warnings
from collections.abc import Callable
@ -14,7 +14,7 @@ from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import MCPContent
if TYPE_CHECKING:
pass
from fastmcp.server.server import MountedServer
logger = get_logger(__name__)
@ -28,6 +28,7 @@ class ToolManager:
mask_error_details: bool | None = None,
):
self._tools: dict[str, Tool] = {}
self._mounted_servers: list[MountedServer] = []
self.mask_error_details = mask_error_details or settings.mask_error_details
# Default to "warn" if None is provided
@ -42,23 +43,72 @@ class ToolManager:
self.duplicate_behavior = duplicate_behavior
def has_tool(self, key: str) -> bool:
def mount(self, server: MountedServer) -> None:
"""Adds a mounted server as a source for tools."""
self._mounted_servers.append(server)
async def _load_tools(self, *, via_server: bool = False) -> dict[str, Tool]:
"""
The single, consolidated recursive method for fetching tools. The 'via_server'
parameter determines the communication path.
- via_server=False: Manager-to-manager path for complete, unfiltered inventory
- via_server=True: Server-to-server path for filtered MCP requests
"""
all_tools: dict[str, Tool] = {}
for mounted in self._mounted_servers:
try:
if via_server:
# Use the server-to-server filtered path
child_results = await mounted.server._list_tools()
else:
# Use the manager-to-manager unfiltered path
child_results = await mounted.server._tool_manager.list_tools()
# The combination logic is the same for both paths
child_dict = {t.key: t for t in child_results}
if mounted.prefix:
for tool in child_dict.values():
prefixed_tool = tool.with_key(f"{mounted.prefix}_{tool.key}")
all_tools[prefixed_tool.key] = prefixed_tool
else:
all_tools.update(child_dict)
except Exception as e:
# Skip failed mounts silently, matches existing behavior
logger.warning(
f"Failed to get tools from mounted server '{mounted.prefix}': {e}"
)
continue
# Finally, add local tools, which always take precedence
all_tools.update(self._tools)
return all_tools
async def has_tool(self, key: str) -> bool:
"""Check if a tool exists."""
return key in self._tools
tools = await self.get_tools()
return key in tools
def get_tool(self, key: str) -> Tool:
async def get_tool(self, key: str) -> Tool:
"""Get tool by key."""
if key in self._tools:
return self._tools[key]
raise NotFoundError(f"Unknown tool: {key}")
tools = await self.get_tools()
if key in tools:
return tools[key]
raise NotFoundError(f"Tool {key!r} not found")
def get_tools(self) -> dict[str, Tool]:
"""Get all registered tools, indexed by registered key."""
return self._tools
async def get_tools(self) -> dict[str, Tool]:
"""
Gets the complete, unfiltered inventory of all tools.
"""
return await self._load_tools(via_server=False)
def list_tools(self) -> list[Tool]:
"""List all registered tools."""
return list(self.get_tools().values())
async def list_tools(self) -> list[Tool]:
"""
Lists all tools, applying protocol filtering.
"""
tools_dict = await self._load_tools(via_server=True)
return list(tools_dict.values())
def add_tool_from_fn(
self,
@ -89,22 +139,21 @@ class ToolManager:
)
return self.add_tool(tool)
def add_tool(self, tool: Tool, key: str | None = None) -> Tool:
def add_tool(self, tool: Tool) -> Tool:
"""Register a tool with the server."""
key = key or tool.name
existing = self._tools.get(key)
existing = self._tools.get(tool.key)
if existing:
if self.duplicate_behavior == "warn":
logger.warning(f"Tool already exists: {key}")
self._tools[key] = tool
logger.warning(f"Tool already exists: {tool.key}")
self._tools[tool.key] = tool
elif self.duplicate_behavior == "replace":
self._tools[key] = tool
self._tools[tool.key] = tool
elif self.duplicate_behavior == "error":
raise ValueError(f"Tool already exists: {key}")
raise ValueError(f"Tool already exists: {tool.key}")
elif self.duplicate_behavior == "ignore":
return existing
else:
self._tools[key] = tool
self._tools[tool.key] = tool
return tool
def remove_tool(self, key: str) -> None:
@ -119,28 +168,48 @@ class ToolManager:
if key in self._tools:
del self._tools[key]
else:
raise NotFoundError(f"Unknown tool: {key}")
raise NotFoundError(f"Tool {key!r} not found")
async def call_tool(self, key: str, arguments: dict[str, Any]) -> list[MCPContent]:
"""Call a tool by name with arguments."""
tool = self.get_tool(key)
if not tool:
raise NotFoundError(f"Unknown tool: {key}")
"""
Internal API for servers: Finds and calls a tool, respecting the
filtered protocol path.
"""
# 1. Check local tools first. The server will have already applied its filter.
if key in self._tools:
tool = await self.get_tool(key)
if not tool:
raise NotFoundError(f"Tool {key!r} not found")
try:
return await tool.run(arguments)
try:
return await tool.run(arguments)
# raise ToolErrors as-is
except ToolError as e:
logger.exception(f"Error calling tool {key!r}: {e}")
raise e
# raise ToolErrors as-is
except ToolError as e:
logger.exception(f"Error calling tool {key!r}: {e}")
raise e
# Handle other exceptions
except Exception as e:
logger.exception(f"Error calling tool {key!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise ToolError(f"Error calling tool {key!r}") from e
else:
# Include original error details
raise ToolError(f"Error calling tool {key!r}: {e}") from e
# Handle other exceptions
except Exception as e:
logger.exception(f"Error calling tool {key!r}: {e}")
if self.mask_error_details:
# Mask internal details
raise ToolError(f"Error calling tool {key!r}") from e
else:
# Include original error details
raise ToolError(f"Error calling tool {key!r}: {e}") from e
# 2. Check mounted servers using the filtered protocol path.
for mounted in reversed(self._mounted_servers):
tool_key = key
if mounted.prefix:
if key.startswith(f"{mounted.prefix}_"):
tool_key = key.removeprefix(f"{mounted.prefix}_")
else:
continue
try:
return await mounted.server._call_tool(tool_key, arguments)
except NotFoundError:
continue
raise NotFoundError(f"Tool {key!r} not found.")

View file

@ -833,7 +833,12 @@ class TestInferTransport:
transport = infer_transport(config)
assert isinstance(transport, MCPConfigTransport)
assert isinstance(transport.transport, FastMCPTransport)
assert len(cast(FastMCP, transport.transport.server)._mounted_servers) == 2
assert (
len(
cast(FastMCP, transport.transport.server)._tool_manager._mounted_servers
)
== 2
)
def test_infer_fastmcp_server(self, fastmcp_server):
"""FastMCP server instances should infer to FastMCPTransport."""

View file

@ -99,7 +99,7 @@ async def test_import_server_with_legacy_prefixes():
await main_server.import_server("sub", sub_server) # type: ignore[arg-type]
# Check that the resource is prefixed using the legacy format
resources = main_server._resource_manager.get_resources()
resources = await main_server.get_resources()
# In legacy format, the key would be "sub+resource://test"
assert "sub+resource://test" in resources

View file

@ -10,7 +10,7 @@ from fastmcp.prompts.prompt_manager import PromptManager
class TestPromptManager:
def test_add_prompt(self):
async def test_add_prompt(self):
"""Test adding a prompt to the manager."""
def fn() -> str:
@ -20,9 +20,9 @@ class TestPromptManager:
prompt = Prompt.from_function(fn)
added = manager.add_prompt(prompt)
assert added == prompt
assert manager.get_prompt("fn") == prompt
assert await manager.get_prompt("fn") == prompt
def test_add_duplicate_prompt(self, caplog):
async def test_add_duplicate_prompt(self, caplog):
"""Test adding the same prompt twice."""
def fn() -> str:
@ -35,7 +35,7 @@ class TestPromptManager:
assert first == second
assert "Prompt already exists" in caplog.text
def test_disable_warn_on_duplicate_prompts(self, caplog):
async def test_disable_warn_on_duplicate_prompts(self, caplog):
"""Test disabling warning on duplicate prompts."""
def fn() -> str:
@ -48,7 +48,7 @@ class TestPromptManager:
assert first == second
assert "Prompt already exists" not in caplog.text
def test_warn_on_duplicate_prompts(self, caplog):
async def test_warn_on_duplicate_prompts(self, caplog):
"""Test warning on duplicate prompts."""
manager = PromptManager(duplicate_behavior="warn")
@ -62,9 +62,9 @@ class TestPromptManager:
assert "Prompt already exists: test_prompt" in caplog.text
# Should have the prompt
assert manager.get_prompt("test_prompt") is not None
assert await manager.get_prompt("test_prompt") is not None
def test_error_on_duplicate_prompts(self):
async def test_error_on_duplicate_prompts(self):
"""Test error on duplicate prompts."""
manager = PromptManager(duplicate_behavior="error")
@ -78,7 +78,7 @@ class TestPromptManager:
with pytest.raises(ValueError, match="Prompt already exists: test_prompt"):
manager.add_prompt(prompt)
def test_replace_duplicate_prompts(self):
async def test_replace_duplicate_prompts(self):
"""Test replacing duplicate prompts."""
manager = PromptManager(duplicate_behavior="replace")
@ -95,12 +95,12 @@ class TestPromptManager:
manager.add_prompt(prompt2)
# Should have replaced with the new prompt
prompt = manager.get_prompt("test_prompt")
prompt = await manager.get_prompt("test_prompt")
assert prompt is not None
assert isinstance(prompt, FunctionPrompt)
assert prompt.fn.__name__ == "replacement_fn"
def test_ignore_duplicate_prompts(self):
async def test_ignore_duplicate_prompts(self):
"""Test ignoring duplicate prompts."""
manager = PromptManager(duplicate_behavior="ignore")
@ -117,7 +117,7 @@ class TestPromptManager:
result = manager.add_prompt(prompt2)
# Should keep the original
prompt = manager.get_prompt("test_prompt")
prompt = await manager.get_prompt("test_prompt")
assert prompt is not None
assert isinstance(prompt, FunctionPrompt)
assert prompt.fn.__name__ == "original_fn"
@ -125,7 +125,7 @@ class TestPromptManager:
assert isinstance(result, FunctionPrompt)
assert result.fn.__name__ == "original_fn"
def test_get_prompts(self):
async def test_get_prompts(self):
"""Test retrieving all prompts."""
def fn1() -> str:
@ -139,7 +139,7 @@ class TestPromptManager:
prompt2 = Prompt.from_function(fn2)
manager.add_prompt(prompt1)
manager.add_prompt(prompt2)
prompts = manager.get_prompts()
prompts = await manager.get_prompts()
assert len(prompts) == 2
assert prompts["fn1"] == prompt1
assert prompts["fn2"] == prompt2
@ -270,7 +270,7 @@ class TestRenderPrompt:
class TestPromptTags:
"""Test functionality related to prompt tags."""
def test_add_prompt_with_tags(self):
async def test_add_prompt_with_tags(self):
"""Test adding a prompt with tags."""
def greeting() -> str:
@ -280,11 +280,11 @@ class TestPromptTags:
prompt = Prompt.from_function(greeting, tags={"greeting", "simple"})
manager.add_prompt(prompt)
prompt = manager.get_prompt("greeting")
prompt = await manager.get_prompt("greeting")
assert prompt is not None
assert prompt.tags == {"greeting", "simple"}
def test_add_prompt_with_empty_tags(self):
async def test_add_prompt_with_empty_tags(self):
"""Test adding a prompt with empty tags."""
def greeting() -> str:
@ -294,11 +294,11 @@ class TestPromptTags:
prompt = Prompt.from_function(greeting, tags=set())
manager.add_prompt(prompt)
prompt = manager.get_prompt("greeting")
prompt = await manager.get_prompt("greeting")
assert prompt is not None
assert prompt.tags == set()
def test_add_prompt_with_none_tags(self):
async def test_add_prompt_with_none_tags(self):
"""Test adding a prompt with None tags."""
def greeting() -> str:
@ -308,11 +308,11 @@ class TestPromptTags:
prompt = Prompt.from_function(greeting, tags=None)
manager.add_prompt(prompt)
prompt = manager.get_prompt("greeting")
prompt = await manager.get_prompt("greeting")
assert prompt is not None
assert prompt.tags == set()
def test_list_prompts_with_tags(self):
async def test_list_prompts_with_tags(self):
"""Test listing prompts with specific tags."""
def greeting() -> str:
@ -332,13 +332,12 @@ class TestPromptTags:
)
# Filter prompts by tags
simple_prompts = [
p for p in manager.get_prompts().values() if "simple" in p.tags
]
prompts = await manager.get_prompts()
simple_prompts = [p for p in prompts.values() if "simple" in p.tags]
assert len(simple_prompts) == 2
assert {p.name for p in simple_prompts} == {"greeting", "summary"}
nlp_prompts = [p for p in manager.get_prompts().values() if "nlp" in p.tags]
nlp_prompts = [p for p in prompts.values() if "nlp" in p.tags]
assert len(nlp_prompts) == 1
assert nlp_prompts[0].name == "summary"

View file

@ -33,7 +33,7 @@ def temp_file():
class TestResourceManager:
"""Test ResourceManager functionality."""
def test_add_resource(self, temp_file: Path):
async def test_add_resource(self, temp_file: Path):
"""Test adding a resource."""
manager = ResourceManager()
file_url = "file://test-resource"
@ -45,10 +45,11 @@ class TestResourceManager:
added = manager.add_resource(resource)
assert added == resource
# Get the actual key from the resource manager
assert len(manager.get_resources()) == 1
assert resource in manager.get_resources().values()
resources = await manager.get_resources()
assert len(resources) == 1
assert resource in resources.values()
def test_add_duplicate_resource(self, temp_file: Path):
async def test_add_duplicate_resource(self, temp_file: Path):
"""Test adding the same resource twice."""
manager = ResourceManager()
file_url = "file://test-resource"
@ -61,10 +62,11 @@ class TestResourceManager:
second = manager.add_resource(resource)
assert first == second
# Check the resource is there
assert len(manager.get_resources()) == 1
assert resource in manager.get_resources().values()
resources = await manager.get_resources()
assert len(resources) == 1
assert resource in resources.values()
def test_warn_on_duplicate_resources(self, temp_file: Path, caplog):
async def test_warn_on_duplicate_resources(self, temp_file: Path, caplog):
"""Test warning on duplicate resources."""
manager = ResourceManager(duplicate_behavior="warn")
@ -80,10 +82,11 @@ class TestResourceManager:
assert "Resource already exists" in caplog.text
# Should have the resource
assert len(manager.get_resources()) == 1
assert resource in manager.get_resources().values()
resources = await manager.get_resources()
assert len(resources) == 1
assert resource in resources.values()
def test_disable_warn_on_duplicate_resources(self, temp_file: Path, caplog):
async def test_disable_warn_on_duplicate_resources(self, temp_file: Path, caplog):
"""Test disabling warning on duplicate resources."""
manager = ResourceManager(duplicate_behavior="ignore")
resource = FileResource(
@ -95,7 +98,7 @@ class TestResourceManager:
manager.add_resource(resource)
assert "Resource already exists" not in caplog.text
def test_error_on_duplicate_resources(self, temp_file: Path):
async def test_error_on_duplicate_resources(self, temp_file: Path):
"""Test error on duplicate resources."""
manager = ResourceManager(duplicate_behavior="error")
@ -110,7 +113,7 @@ class TestResourceManager:
with pytest.raises(ValueError, match="Resource already exists"):
manager.add_resource(resource)
def test_replace_duplicate_resources(self, temp_file: Path):
async def test_replace_duplicate_resources(self, temp_file: Path):
"""Test replacing duplicate resources."""
manager = ResourceManager(duplicate_behavior="replace")
@ -131,11 +134,12 @@ class TestResourceManager:
manager.add_resource(resource2)
# Should have replaced with the new resource
resources = list(manager.get_resources().values())
assert len(resources) == 1
assert resources[0].name == "replacement"
resources = await manager.get_resources()
resource_list = list(resources.values())
assert len(resource_list) == 1
assert resource_list[0].name == "replacement"
def test_ignore_duplicate_resources(self, temp_file: Path):
async def test_ignore_duplicate_resources(self, temp_file: Path):
"""Test ignoring duplicate resources."""
manager = ResourceManager(duplicate_behavior="ignore")
@ -156,13 +160,14 @@ class TestResourceManager:
result = manager.add_resource(resource2)
# Should keep the original
resources = list(manager.get_resources().values())
assert len(resources) == 1
assert resources[0].name == "original"
resources = await manager.get_resources()
resource_list = list(resources.values())
assert len(resource_list) == 1
assert resource_list[0].name == "original"
# Result should be the original resource
assert result.name == "original"
def test_warn_on_duplicate_templates(self, caplog):
async def test_warn_on_duplicate_templates(self, caplog):
"""Test warning on duplicate templates."""
manager = ResourceManager(duplicate_behavior="warn")
@ -180,9 +185,10 @@ class TestResourceManager:
assert "Template already exists" in caplog.text
# Should have the template
assert manager.get_templates() == {"test://{id}": template}
templates = await manager.get_resource_templates()
assert templates == {"test://{id}": template}
def test_error_on_duplicate_templates(self):
async def test_error_on_duplicate_templates(self):
"""Test error on duplicate templates."""
manager = ResourceManager(duplicate_behavior="error")
@ -200,7 +206,7 @@ class TestResourceManager:
with pytest.raises(ValueError, match="Template already exists"):
manager.add_template(template)
def test_replace_duplicate_templates(self):
async def test_replace_duplicate_templates(self):
"""Test replacing duplicate templates."""
manager = ResourceManager(duplicate_behavior="replace")
@ -226,11 +232,12 @@ class TestResourceManager:
manager.add_template(template2)
# Should have replaced with the new template
templates = list(manager.get_templates().values())
templates_dict = await manager.get_resource_templates()
templates = list(templates_dict.values())
assert len(templates) == 1
assert templates[0].name == "replacement"
def test_ignore_duplicate_templates(self):
async def test_ignore_duplicate_templates(self):
"""Test ignoring duplicate templates."""
manager = ResourceManager(duplicate_behavior="ignore")
@ -256,7 +263,8 @@ class TestResourceManager:
result = manager.add_template(template2)
# Should keep the original
templates = list(manager.get_templates().values())
templates_dict = await manager.get_resource_templates()
templates = list(templates_dict.values())
assert len(templates) == 1
assert templates[0].name == "original"
# Result should be the original template
@ -299,7 +307,7 @@ class TestResourceManager:
with pytest.raises(NotFoundError, match="Unknown resource"):
await manager.get_resource(AnyUrl("unknown://test"))
def test_get_resources(self, temp_file: Path):
async def test_get_resources(self, temp_file: Path):
"""Test retrieving all resources."""
manager = ResourceManager()
file_url1 = "file://test-resource1"
@ -316,7 +324,7 @@ class TestResourceManager:
)
manager.add_resource(resource1)
manager.add_resource(resource2)
resources = manager.get_resources()
resources = await manager.get_resources()
assert len(resources) == 2
values = list(resources.values())
assert resource1 in values
@ -326,7 +334,7 @@ class TestResourceManager:
class TestResourceTags:
"""Test functionality related to resource tags."""
def test_add_resource_with_tags(self, temp_file: Path):
async def test_add_resource_with_tags(self, temp_file: Path):
"""Test adding a resource with tags."""
manager = ResourceManager()
resource = FileResource(
@ -338,11 +346,12 @@ class TestResourceTags:
manager.add_resource(resource)
# Check that tags are preserved
resources = list(manager.get_resources().values())
resources_dict = await manager.get_resources()
resources = list(resources_dict.values())
assert len(resources) == 1
assert resources[0].tags == {"weather", "data"}
def test_add_function_resource_with_tags(self):
async def test_add_function_resource_with_tags(self):
"""Test adding a function resource with tags."""
manager = ResourceManager()
@ -359,11 +368,12 @@ class TestResourceTags:
)
manager.add_resource(resource)
resources = list(manager.get_resources().values())
resources_dict = await manager.get_resources()
resources = list(resources_dict.values())
assert len(resources) == 1
assert resources[0].tags == {"sample", "test", "data"}
def test_add_template_with_tags(self):
async def test_add_template_with_tags(self):
"""Test adding a resource template with tags."""
manager = ResourceManager()
@ -379,11 +389,12 @@ class TestResourceTags:
)
manager.add_template(template)
templates = list(manager.get_templates().values())
templates_dict = await manager.get_resource_templates()
templates = list(templates_dict.values())
assert len(templates) == 1
assert templates[0].tags == {"users", "template", "data"}
def test_filter_resources_by_tags(self, temp_file: Path):
async def test_filter_resources_by_tags(self, temp_file: Path):
"""Test filtering resources by tags."""
manager = ResourceManager()
@ -392,7 +403,7 @@ class TestResourceTags:
uri=FileUrl("file://weather-data"),
name="weather_data",
path=temp_file,
tags={"weather", "external"},
tags={"weather", "data"},
)
async def get_user_data():
@ -401,8 +412,10 @@ class TestResourceTags:
resource2 = FunctionResource(
uri=AnyUrl("data://users"),
name="user_data",
description="User data resource",
mime_type="text/plain",
fn=get_user_data,
tags={"users", "internal"},
tags={"users", "data"},
)
async def get_system_data():
@ -411,26 +424,25 @@ class TestResourceTags:
resource3 = FunctionResource(
uri=AnyUrl("data://system"),
name="system_data",
description="System data resource",
mime_type="text/plain",
fn=get_system_data,
tags={"system", "internal"},
tags={"system", "admin"},
)
manager.add_resource(resource1)
manager.add_resource(resource2)
manager.add_resource(resource3)
# Filter resources by tags
internal_resources = [
r for r in manager.get_resources().values() if "internal" in r.tags
]
assert len(internal_resources) == 2
assert {r.name for r in internal_resources} == {"user_data", "system_data"}
# Filter by tags
resources_dict = await manager.get_resources()
data_resources = [r for r in resources_dict.values() if "data" in r.tags]
assert len(data_resources) == 2
assert {r.name for r in data_resources} == {"weather_data", "user_data"}
external_resources = [
r for r in manager.get_resources().values() if "external" in r.tags
]
assert len(external_resources) == 1
assert external_resources[0].name == "weather_data"
admin_resources = [r for r in resources_dict.values() if "admin" in r.tags]
assert len(admin_resources) == 1
assert admin_resources[0].name == "system_data"
class TestCustomResourceKeys:
@ -452,7 +464,9 @@ class TestCustomResourceKeys:
fn=get_data,
)
manager.add_resource(resource, key=custom_key)
# Use with_key to create a new resource with the custom key
resource_with_custom_key = resource.with_key(custom_key)
manager.add_resource(resource_with_custom_key)
# Resource should be accessible via custom key
assert custom_key in manager._resources
@ -477,7 +491,9 @@ class TestCustomResourceKeys:
name="test_template",
)
manager.add_template(template, key=custom_key)
# Use with_key to create a new template with the custom key
template_with_custom_key = template.with_key(custom_key)
manager.add_template(template_with_custom_key)
# Template should be accessible via custom key
assert custom_key in manager._templates
@ -502,7 +518,9 @@ class TestCustomResourceKeys:
fn=get_data,
)
manager.add_resource(resource, key=custom_key)
# Use with_key to create a new resource with the custom key
resource_with_custom_key = resource.with_key(custom_key)
manager.add_resource(resource_with_custom_key)
# Should be retrievable by the custom key
retrieved = await manager.get_resource(custom_key)
@ -529,7 +547,9 @@ class TestCustomResourceKeys:
name="custom_greeter",
)
manager.add_template(template, key=custom_key)
# Use with_key to create a new template with the custom key
template_with_custom_key = template.with_key(custom_key)
manager.add_template(template_with_custom_key)
# Using a URI that matches the custom key pattern
resource = await manager.get_resource("custom://greet/world")

View file

@ -405,6 +405,7 @@ class TestMatchUriTemplate:
("test://a/b/c", None),
("test://a/x/b", {"x": "x"}),
("test://a/x/y/b", None),
("test://a/1-2/b", {"x": "1-2"}),
],
)
def test_match_uri_template_single_param(

View file

View file

@ -0,0 +1,567 @@
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import mcp.types
import pytest
from fastmcp import Client, FastMCP
from fastmcp.server.context import Context
from fastmcp.server.middleware import Middleware, MiddlewareContext
@dataclass
class Recording:
# the hook is the name of the hook that was called, e.g. "on_list_tools"
hook: str
context: MiddlewareContext
result: mcp.types.ServerResult | None
class RecordingMiddleware(Middleware):
"""A middleware that automatically records all method calls."""
def __init__(self, name: str | None = None):
super().__init__()
self.calls: list[Recording] = []
self.name = name
def __getattribute__(self, name: str) -> Callable:
"""Dynamically create recording methods for any on_* method."""
if name.startswith("on_"):
async def record_and_call(
context: MiddlewareContext, call_next: Callable
) -> Any:
result = await call_next(context)
self.calls.append(Recording(hook=name, context=context, result=result))
return result
return record_and_call
return super().__getattribute__(name)
def get_calls(
self, method: str | None = None, hook: str | None = None
) -> list[Recording]:
"""
Get all recorded calls for a specific method or hook.
Args:
method: The method to filter by (e.g. "tools/list")
hook: The hook to filter by (e.g. "on_list_tools")
Returns:
A list of recorded calls.
"""
calls = []
for recording in self.calls:
if method and hook:
if recording.context.method == method and recording.hook == hook:
calls.append(recording)
elif method:
if recording.context.method == method:
calls.append(recording)
elif hook:
if recording.hook == hook:
calls.append(recording)
else:
calls.append(recording)
return calls
def assert_called(
self, hook: str | None = None, method: str | None = None, times: int = 1
) -> bool:
"""Assert that a hook was called a specific number of times."""
calls = self.get_calls(hook=hook, method=method)
actual_times = len(calls)
identifier = dict(hook=hook, method=method)
assert actual_times == times, (
f"Expected {times} calls for {identifier}, "
f"but was called {actual_times} times"
)
return True
def assert_not_called(self, hook: str | None = None, method: str | None = None):
"""Assert that a hook was not called."""
calls = self.get_calls(hook=hook, method=method)
assert len(calls) == 0, f"Expected {hook!r} to not be called"
return True
def reset(self):
"""Clear all recorded calls."""
self.calls.clear()
@pytest.fixture
def recording_middleware():
"""Fixture that provides a recording middleware instance."""
middleware = RecordingMiddleware(name="recording_middleware")
yield middleware
@pytest.fixture
def mcp_server(recording_middleware):
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
@mcp.resource("resource://test")
def test_resource() -> str:
return "test resource"
@mcp.resource("resource://test-template/{x}")
def test_resource_with_path(x: int) -> str:
return f"test resource with {x}"
@mcp.prompt
def test_prompt(x: str) -> str:
return f"test prompt with {x}"
@mcp.tool
async def progress_tool(context: Context) -> None:
await context.report_progress(progress=1, total=10, message="test")
@mcp.tool
async def log_tool(context: Context) -> None:
await context.info(message="test log")
@mcp.tool
async def sample_tool(context: Context) -> None:
await context.sample("hello")
mcp.add_middleware(recording_middleware)
# Register progress handler
@mcp._mcp_server.progress_notification()
async def handle_progress(
progress_token: str | int,
progress: float,
total: float | None,
message: str | None,
):
print("HI")
return mcp
class TestMiddlewareHooks:
async def test_call_tool(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.call_tool("add", {"a": 1, "b": 2})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="tools/call", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_call_tool", times=1)
async def test_read_resource(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.read_resource("resource://test")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
async def test_read_resource_template(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.read_resource("resource://test-template/1")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
async def test_get_prompt(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.get_prompt("test_prompt", {"x": "test"})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="prompts/get", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_get_prompt", times=1)
async def test_list_tools(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.list_tools()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="tools/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_list_tools", times=1)
async def test_list_resources(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.list_resources()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_list_resources", times=1)
async def test_list_resource_templates(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.list_resource_templates()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(
method="resources/templates/list", times=3
)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(
hook="on_list_resource_templates", times=1
)
async def test_list_prompts(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
async with Client(mcp_server) as client:
await client.list_prompts()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="prompts/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_list_prompts", times=1)
class TestNestedMiddlewareHooks:
@pytest.fixture
@staticmethod
def nested_middleware():
return RecordingMiddleware(name="nested_middleware")
@pytest.fixture
def nested_mcp_server(self, nested_middleware: RecordingMiddleware):
mcp = FastMCP(name="Nested MCP")
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
@mcp.resource("resource://test")
def test_resource() -> str:
return "test resource"
@mcp.resource("resource://test-template/{x}")
def test_resource_with_path(x: int) -> str:
return f"test resource with {x}"
@mcp.prompt
def test_prompt(x: str) -> str:
return f"test prompt with {x}"
@mcp.tool
async def progress_tool(context: Context) -> None:
await context.report_progress(progress=1, total=10, message="test")
@mcp.tool
async def log_tool(context: Context) -> None:
await context.info(message="test log")
@mcp.tool
async def sample_tool(context: Context) -> None:
await context.sample("hello")
mcp.add_middleware(nested_middleware)
return mcp
async def test_call_tool_on_parent_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.call_tool("add", {"a": 1, "b": 2})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="tools/call", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_call_tool", times=1)
assert nested_middleware.assert_called(times=0)
async def test_call_tool_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.call_tool("nested_add", {"a": 1, "b": 2})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="tools/call", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_call_tool", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="tools/call", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_call_tool", times=1)
async def test_read_resource_on_parent_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.read_resource("resource://test")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
assert nested_middleware.assert_called(times=0)
async def test_read_resource_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.read_resource("resource://nested/test")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="resources/read", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_read_resource", times=1)
async def test_read_resource_template_on_parent_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.read_resource("resource://test-template/1")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
assert nested_middleware.assert_called(times=0)
async def test_read_resource_template_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.read_resource("resource://nested/test-template/1")
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/read", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_read_resource", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="resources/read", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_read_resource", times=1)
async def test_get_prompt_on_parent_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.get_prompt("test_prompt", {"x": "test"})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="prompts/get", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_get_prompt", times=1)
assert nested_middleware.assert_called(times=0)
async def test_get_prompt_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.get_prompt("nested_test_prompt", {"x": "test"})
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="prompts/get", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_get_prompt", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="prompts/get", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_get_prompt", times=1)
async def test_list_tools_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.list_tools()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="tools/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_list_tools", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="tools/list", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_list_tools", times=1)
async def test_list_resources_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.list_resources()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(method="resources/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(hook="on_list_resources", times=1)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(method="resources/list", times=3)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(hook="on_list_resources", times=1)
async def test_list_resource_templates_on_nested_server(
self,
mcp_server: FastMCP,
nested_mcp_server: FastMCP,
recording_middleware: RecordingMiddleware,
nested_middleware: RecordingMiddleware,
):
mcp_server.mount(nested_mcp_server, prefix="nested")
async with Client(mcp_server) as client:
await client.list_resource_templates()
assert recording_middleware.assert_called(times=3)
assert recording_middleware.assert_called(
method="resources/templates/list", times=3
)
assert recording_middleware.assert_called(hook="on_message", times=1)
assert recording_middleware.assert_called(hook="on_request", times=1)
assert recording_middleware.assert_called(
hook="on_list_resource_templates", times=1
)
assert nested_middleware.assert_called(times=3)
assert nested_middleware.assert_called(
method="resources/templates/list", times=3
)
assert nested_middleware.assert_called(hook="on_message", times=1)
assert nested_middleware.assert_called(hook="on_request", times=1)
assert nested_middleware.assert_called(
hook="on_list_resource_templates", times=1
)
class TestProxyServer:
async def test_call_tool(
self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware
):
# proxy server will have its tools listed as well as called in order to
# run the `should_enable_component` hook prior to the call.
proxy_server = FastMCP.as_proxy(mcp_server, name="Proxy Server")
async with Client(proxy_server) as client:
await client.call_tool("add", {"a": 1, "b": 2})
assert recording_middleware.assert_called(times=6)
assert recording_middleware.assert_called(method="tools/call", times=3)
assert recording_middleware.assert_called(method="tools/list", times=3)
assert recording_middleware.assert_called(hook="on_message", times=2)
assert recording_middleware.assert_called(hook="on_request", times=2)
assert recording_middleware.assert_called(hook="on_call_tool", times=1)
assert recording_middleware.assert_called(hook="on_list_tools", times=1)

View file

@ -136,7 +136,7 @@ def api_client(fastapi_app: FastAPI) -> AsyncClient:
@pytest.fixture
async def fastmcp_openapi_server_with_all_types(
async def fastmcp_openapi_server(
fastapi_app: FastAPI, api_client: httpx.AsyncClient
) -> FastMCPOpenAPI:
openapi_spec = fastapi_app.openapi()
@ -213,13 +213,11 @@ class TestTools:
assert len(await server.get_resources()) == 0
assert len(await server.get_resource_templates()) == 0
async def test_list_tools(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
):
async def test_list_tools(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, tools exclude GET methods
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
tools = await client.list_tools()
assert len(tools) == 2
@ -254,13 +252,13 @@ class TestTools:
async def test_call_create_user_tool(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""
The tool created by the OpenAPI server should be the same as the original
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
tool_response = await client.call_tool(
"create_user_users_post", {"name": "David", "active": False}
)
@ -274,7 +272,7 @@ class TestTools:
assert len(response.json()) == 4
# Check that the user was created via MCP
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
user_response = await client.read_resource("resource://get_user_users/4")
response_text = user_response[0].text # type: ignore[attr-defined]
user = json.loads(response_text)
@ -282,13 +280,13 @@ class TestTools:
async def test_call_update_user_name_tool(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""
The tool created by the OpenAPI server should be the same as the original
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
tool_response = await client.call_tool(
"update_user_name_users",
{"user_id": 1, "name": "XYZ"},
@ -303,7 +301,7 @@ class TestTools:
assert expected_data in response.json()
# Check that the user was updated via MCP
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
user_response = await client.read_resource("resource://get_user_users/1")
response_text = user_response[0].text # type: ignore[attr-defined]
user = json.loads(response_text)
@ -335,13 +333,11 @@ class TestTools:
class TestResources:
async def test_list_resources(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
):
async def test_list_resources(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, resources exclude GET methods without parameters
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resources = await client.list_resources()
assert len(resources) == 4
assert resources[0].uri == AnyUrl("resource://get_users_users_get")
@ -349,7 +345,7 @@ class TestResources:
async def test_get_resource(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
@ -360,7 +356,7 @@ class TestResources:
json_users = TypeAdapter(list[User]).dump_python(
sorted(users_db.values(), key=lambda x: x.id)
)
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
"resource://get_users_users_get"
)
@ -372,11 +368,11 @@ class TestResources:
async def test_get_bytes_resource(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""Test reading a resource that returns bytes."""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
"resource://ping_bytes_ping_bytes_get"
)
@ -385,23 +381,23 @@ class TestResources:
async def test_get_str_resource(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""Test reading a resource that returns a string."""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource("resource://ping_ping_get")
assert resource_response[0].text == "pong" # type: ignore[attr-defined]
class TestResourceTemplates:
async def test_list_resource_templates(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""
By default, resource templates exclude GET methods without parameters
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_templates = await client.list_resource_templates()
assert len(resource_templates) == 2
assert resource_templates[0].name == "get_user_users"
@ -416,7 +412,7 @@ class TestResourceTemplates:
async def test_get_resource_template(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
@ -424,7 +420,7 @@ class TestResourceTemplates:
The resource template created by the OpenAPI server should be the same as the original
"""
user_id = 2
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
f"resource://get_user_users/{user_id}"
)
@ -437,7 +433,7 @@ class TestResourceTemplates:
async def test_get_resource_template_multi_param(
self,
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
@ -446,7 +442,7 @@ class TestResourceTemplates:
"""
user_id = 2
is_active = True
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
f"resource://get_user_active_state_users/{is_active}/{user_id}"
)
@ -459,13 +455,11 @@ class TestResourceTemplates:
class TestPrompts:
async def test_list_prompts(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
):
async def test_list_prompts(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, there are no prompts.
"""
async with Client(fastmcp_openapi_server_with_all_types) as client:
async with Client(fastmcp_openapi_server) as client:
prompts = await client.list_prompts()
assert len(prompts) == 0
@ -474,11 +468,11 @@ class TestTagTransfer:
"""Tests for transferring tags from OpenAPI routes to MCP objects."""
async def test_tags_transferred_to_tools(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""Test that tags from OpenAPI routes are correctly transferred to Tools."""
# Get internal tools directly (not the public API which returns MCP.Content)
tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()
tools = await fastmcp_openapi_server._tool_manager.list_tools()
# Find the create_user and update_user_name tools
create_user_tool = next(
@ -502,13 +496,12 @@ class TestTagTransfer:
assert len(update_user_tool.tags) == 2
async def test_tags_transferred_to_resources(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""Test that tags from OpenAPI routes are correctly transferred to Resources."""
# Get internal resources directly
resources = list(
fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
)
resources_dict = await fastmcp_openapi_server._resource_manager.get_resources()
resources = list(resources_dict.values())
# Find the get_users resource
get_users_resource = next(
@ -523,13 +516,14 @@ class TestTagTransfer:
assert len(get_users_resource.tags) == 2
async def test_tags_transferred_to_resource_templates(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""Test that tags from OpenAPI routes are correctly transferred to ResourceTemplates."""
# Get internal resource templates directly
templates = list(
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await fastmcp_openapi_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
# Find the get_user template
get_user_template = next(
@ -544,13 +538,14 @@ class TestTagTransfer:
assert len(get_user_template.tags) == 2
async def test_tags_preserved_in_resources_created_from_templates(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""Test that tags are preserved when creating resources from templates."""
# Get internal resource templates directly
templates = list(
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await fastmcp_openapi_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
# Find the get_user template
get_user_template = next(
@ -1167,7 +1162,7 @@ class TestDescriptionPropagation:
return httpx.AsyncClient(transport=transport, base_url="http://test")
@pytest.fixture
async def simple_server_with_all_types(self, simple_openapi_spec, mock_client):
async def simple_mcp_server(self, simple_openapi_spec, mock_client):
"""Create a FastMCPOpenAPI server with the simple test spec."""
return FastMCPOpenAPI(
openapi_spec=simple_openapi_spec,
@ -1179,11 +1174,11 @@ class TestDescriptionPropagation:
# --- RESOURCE TESTS ---
async def test_resource_includes_route_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a Resource includes the route description."""
resources = list(
simple_server_with_all_types._resource_manager.get_resources().values()
(await simple_mcp_server._resource_manager.get_resources()).values()
)
list_resource = next((r for r in resources if r.name == "listItems"), None)
@ -1193,11 +1188,11 @@ class TestDescriptionPropagation:
)
async def test_resource_includes_response_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a Resource includes the response description."""
resources = list(
simple_server_with_all_types._resource_manager.get_resources().values()
(await simple_mcp_server._resource_manager.get_resources()).values()
)
list_resource = next((r for r in resources if r.name == "listItems"), None)
@ -1207,11 +1202,11 @@ class TestDescriptionPropagation:
)
async def test_resource_includes_response_model_fields(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a Resource description includes response model field descriptions."""
resources = list(
simple_server_with_all_types._resource_manager.get_resources().values()
(await simple_mcp_server._resource_manager.get_resources()).values()
)
list_resource = next((r for r in resources if r.name == "listItems"), None)
@ -1230,12 +1225,13 @@ class TestDescriptionPropagation:
# --- RESOURCE TEMPLATE TESTS ---
async def test_template_includes_route_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a ResourceTemplate includes the route description."""
templates = list(
simple_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await simple_mcp_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
get_template = next((t for t in templates if t.name == "getItem"), None)
assert get_template is not None, "getItem template wasn't created"
@ -1244,12 +1240,13 @@ class TestDescriptionPropagation:
)
async def test_template_includes_function_docstring(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a ResourceTemplate includes the function docstring."""
templates = list(
simple_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await simple_mcp_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
get_template = next((t for t in templates if t.name == "getItem"), None)
assert get_template is not None, "getItem template wasn't created"
@ -1258,12 +1255,13 @@ class TestDescriptionPropagation:
)
async def test_template_includes_path_parameter_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a ResourceTemplate includes path parameter descriptions."""
templates = list(
simple_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await simple_mcp_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
get_template = next((t for t in templates if t.name == "getItem"), None)
assert get_template is not None, "getItem template wasn't created"
@ -1272,12 +1270,13 @@ class TestDescriptionPropagation:
)
async def test_template_includes_query_parameter_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a ResourceTemplate includes query parameter descriptions."""
templates = list(
simple_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await simple_mcp_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
get_template = next((t for t in templates if t.name == "getItem"), None)
assert get_template is not None, "getItem template wasn't created"
@ -1286,12 +1285,13 @@ class TestDescriptionPropagation:
)
async def test_template_parameter_schema_includes_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a ResourceTemplate's parameter schema includes parameter descriptions."""
templates = list(
simple_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await simple_mcp_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
get_template = next((t for t in templates if t.name == "getItem"), None)
assert get_template is not None, "getItem template wasn't created"
@ -1311,9 +1311,10 @@ class TestDescriptionPropagation:
# --- TOOL TESTS ---
async def test_tool_includes_route_description(self, simple_server_with_all_types):
async def test_tool_includes_route_description(self, simple_mcp_server: FastMCP):
"""Test that a Tool includes the route description."""
tools = simple_server_with_all_types._tool_manager.list_tools()
tools_dict = await simple_mcp_server._tool_manager.get_tools()
tools = list(tools_dict.values())
create_tool = next((t for t in tools if t.name == "createItem"), None)
assert create_tool is not None, "createItem tool wasn't created"
@ -1321,9 +1322,10 @@ class TestDescriptionPropagation:
"Route description missing from Tool"
)
async def test_tool_includes_function_docstring(self, simple_server_with_all_types):
async def test_tool_includes_function_docstring(self, simple_mcp_server: FastMCP):
"""Test that a Tool includes the function docstring."""
tools = simple_server_with_all_types._tool_manager.list_tools()
tools_dict = await simple_mcp_server._tool_manager.get_tools()
tools = list(tools_dict.values())
create_tool = next((t for t in tools if t.name == "createItem"), None)
assert create_tool is not None, "createItem tool wasn't created"
@ -1333,10 +1335,11 @@ class TestDescriptionPropagation:
)
async def test_tool_parameter_schema_includes_property_description(
self, simple_server_with_all_types
self, simple_mcp_server: FastMCP
):
"""Test that a Tool's parameter schema includes property descriptions from request model."""
tools = simple_server_with_all_types._tool_manager.list_tools()
tools_dict = await simple_mcp_server._tool_manager.get_tools()
tools = list(tools_dict.values())
create_tool = next((t for t in tools if t.name == "createItem"), None)
assert create_tool is not None, "createItem tool wasn't created"
@ -1356,9 +1359,9 @@ class TestDescriptionPropagation:
# --- CLIENT API TESTS ---
async def test_client_api_resource_description(self, simple_server_with_all_types):
async def test_client_api_resource_description(self, simple_mcp_server: FastMCP):
"""Test that Resource descriptions are accessible via the client API."""
async with Client(simple_server_with_all_types) as client:
async with Client(simple_mcp_server) as client:
resources = await client.list_resources()
list_resource = next((r for r in resources if r.name == "listItems"), None)
@ -1370,9 +1373,9 @@ class TestDescriptionPropagation:
"Route description missing in Resource from client API"
)
async def test_client_api_template_description(self, simple_server_with_all_types):
async def test_client_api_template_description(self, simple_mcp_server: FastMCP):
"""Test that ResourceTemplate descriptions are accessible via the client API."""
async with Client(simple_server_with_all_types) as client:
async with Client(simple_mcp_server) as client:
templates = await client.list_resource_templates()
get_template = next((t for t in templates if t.name == "getItem"), None)
@ -1384,9 +1387,9 @@ class TestDescriptionPropagation:
"Route description missing in ResourceTemplate from client API"
)
async def test_client_api_tool_description(self, simple_server_with_all_types):
async def test_client_api_tool_description(self, simple_mcp_server: FastMCP):
"""Test that Tool descriptions are accessible via the client API."""
async with Client(simple_server_with_all_types) as client:
async with Client(simple_mcp_server) as client:
tools = await client.list_tools()
create_tool = next((t for t in tools if t.name == "createItem"), None)
@ -1398,9 +1401,9 @@ class TestDescriptionPropagation:
"Function docstring missing in Tool from client API"
)
async def test_client_api_tool_parameter_schema(self, simple_server_with_all_types):
async def test_client_api_tool_parameter_schema(self, simple_mcp_server: FastMCP):
"""Test that Tool parameter schemas are accessible via the client API."""
async with Client(simple_server_with_all_types) as client:
async with Client(simple_mcp_server) as client:
tools = await client.list_tools()
create_tool = next((t for t in tools if t.name == "createItem"), None)
@ -1533,22 +1536,26 @@ class TestFastAPIDescriptionPropagation:
# Debug: print all components created
print("\nDEBUG - Resources created:")
for name, resource in server._resource_manager.get_resources().items():
resources_dict = await server._resource_manager.get_resources()
for name, resource in resources_dict.items():
print(f" Resource: {name}, Name attribute: {resource.name}")
print("\nDEBUG - Templates created:")
for name, template in server._resource_manager.get_templates().items():
templates_dict = await server._resource_manager.get_resource_templates()
for name, template in templates_dict.items():
print(f" Template: {name}, Name attribute: {template.name}")
print("\nDEBUG - Tools created:")
for tool in server._tool_manager.list_tools():
tools = await server._tool_manager.list_tools()
for tool in tools:
print(f" Tool: {tool.name}")
return server
async def test_resource_includes_function_docstring(self, fastapi_server):
async def test_resource_includes_function_docstring(self, fastapi_server: FastMCP):
"""Test that a Resource includes the function docstring."""
resources = list(fastapi_server._resource_manager.get_resources().values())
resources_dict = await fastapi_server._resource_manager.get_resources()
resources = list(resources_dict.values())
# Now checking for the get_items operation ID rather than list_items
list_resource = next((r for r in resources if "items_get" in r.name), None)
@ -1559,13 +1566,16 @@ class TestFastAPIDescriptionPropagation:
"Function docstring missing from Resource"
)
async def test_resource_includes_response_model_fields(self, fastapi_server):
async def test_resource_includes_response_model_fields(
self, fastapi_server: FastMCP
):
"""Test that a Resource description includes basic response information.
Note: FastAPI doesn't reliably include Pydantic field descriptions in the OpenAPI schema,
so we can only check for basic response information being present.
"""
resources = list(fastapi_server._resource_manager.get_resources().values())
resources_dict = await fastapi_server._resource_manager.get_resources()
resources = list(resources_dict.values())
list_resource = next((r for r in resources if "items_get" in r.name), None)
assert list_resource is not None, "GET /items resource wasn't created"
@ -1579,9 +1589,10 @@ class TestFastAPIDescriptionPropagation:
# We've already verified in TestDescriptionPropagation that when descriptions
# are present in the OpenAPI schema, they are properly included in the component description
async def test_template_includes_function_docstring(self, fastapi_server):
async def test_template_includes_function_docstring(self, fastapi_server: FastMCP):
"""Test that a ResourceTemplate includes the function docstring."""
templates = list(fastapi_server._resource_manager.get_templates().values())
templates_dict = await fastapi_server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
get_template = next((t for t in templates if "get_item_items" in t.name), None)
assert get_template is not None, "GET /items/{item_id} template wasn't created"
@ -1590,13 +1601,16 @@ class TestFastAPIDescriptionPropagation:
"Function docstring missing from ResourceTemplate"
)
async def test_template_includes_path_parameter_description(self, fastapi_server):
async def test_template_includes_path_parameter_description(
self, fastapi_server: FastMCP
):
"""Test that a ResourceTemplate includes path parameter descriptions.
Note: Currently, FastAPI parameter descriptions using Annotated[type, Field(description=...)]
are not properly propagated to the OpenAPI schema. The parameters appear but without the description.
"""
templates = list(fastapi_server._resource_manager.get_templates().values())
templates_dict = await fastapi_server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
get_template = next((t for t in templates if "get_item_items" in t.name), None)
assert get_template is not None, "GET /items/{item_id} template wasn't created"
@ -1610,13 +1624,16 @@ class TestFastAPIDescriptionPropagation:
"item_id parameter missing from ResourceTemplate description"
)
async def test_template_includes_query_parameter_description(self, fastapi_server):
async def test_template_includes_query_parameter_description(
self, fastapi_server: FastMCP
):
"""Test that a ResourceTemplate includes query parameter descriptions.
Note: Currently, FastAPI parameter descriptions using Annotated[type, Field(description=...)]
are not properly propagated to the OpenAPI schema. The parameters appear but without the description.
"""
templates = list(fastapi_server._resource_manager.get_templates().values())
templates_dict = await fastapi_server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
get_template = next((t for t in templates if "get_item_items" in t.name), None)
assert get_template is not None, "GET /items/{item_id} template wasn't created"
@ -1630,9 +1647,12 @@ class TestFastAPIDescriptionPropagation:
"fields parameter missing from ResourceTemplate description"
)
async def test_template_parameter_schema_includes_description(self, fastapi_server):
async def test_template_parameter_schema_includes_description(
self, fastapi_server: FastMCP
):
"""Test that a ResourceTemplate's parameter schema includes parameter descriptions."""
templates = list(fastapi_server._resource_manager.get_templates().values())
templates_dict = await fastapi_server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
get_template = next((t for t in templates if "get_item_items" in t.name), None)
assert get_template is not None, "GET /items/{item_id} template wasn't created"
@ -1650,9 +1670,10 @@ class TestFastAPIDescriptionPropagation:
in get_template.parameters["properties"]["item_id"]["description"]
), "Path parameter description incorrect in schema"
async def test_tool_includes_function_docstring(self, fastapi_server):
async def test_tool_includes_function_docstring(self, fastapi_server: FastMCP):
"""Test that a Tool includes the function docstring."""
tools = fastapi_server._tool_manager.list_tools()
tools_dict = await fastapi_server._tool_manager.get_tools()
tools = list(tools_dict.values())
create_tool = next(
(t for t in tools if "create_item_items_post" == t.name), None
)
@ -1664,7 +1685,7 @@ class TestFastAPIDescriptionPropagation:
)
async def test_tool_parameter_schema_includes_property_description(
self, fastapi_server
self, fastapi_server: FastMCP
):
"""Test that a Tool's parameter schema includes property descriptions from request model.
@ -1672,7 +1693,8 @@ class TestFastAPIDescriptionPropagation:
may not be consistently propagated into the FastAPI OpenAPI schema and thus not into the tool's
parameter schema.
"""
tools = fastapi_server._tool_manager.list_tools()
tools_dict = await fastapi_server._tool_manager.get_tools()
tools = list(tools_dict.values())
create_tool = next(
(t for t in tools if "create_item_items_post" == t.name), None
)
@ -1686,7 +1708,7 @@ class TestFastAPIDescriptionPropagation:
)
# We don't test for the description field content as it may not be consistently propagated
async def test_client_api_resource_description(self, fastapi_server):
async def test_client_api_resource_description(self, fastapi_server: FastMCP):
"""Test that Resource descriptions are accessible via the client API."""
async with Client(fastapi_server) as client:
resources = await client.list_resources()
@ -1700,7 +1722,7 @@ class TestFastAPIDescriptionPropagation:
"Function docstring missing in Resource from client API"
)
async def test_client_api_template_description(self, fastapi_server):
async def test_client_api_template_description(self, fastapi_server: FastMCP):
"""Test that ResourceTemplate descriptions are accessible via the client API."""
async with Client(fastapi_server) as client:
templates = await client.list_resource_templates()
@ -1716,7 +1738,7 @@ class TestFastAPIDescriptionPropagation:
"Function docstring missing in ResourceTemplate from client API"
)
async def test_client_api_tool_description(self, fastapi_server):
async def test_client_api_tool_description(self, fastapi_server: FastMCP):
"""Test that Tool descriptions are accessible via the client API."""
async with Client(fastapi_server) as client:
tools = await client.list_tools()
@ -1732,7 +1754,7 @@ class TestFastAPIDescriptionPropagation:
"Function docstring missing in Tool from client API"
)
async def test_client_api_tool_parameter_schema(self, fastapi_server):
async def test_client_api_tool_parameter_schema(self, fastapi_server: FastMCP):
"""Test that Tool parameter schemas are accessible via the client API."""
async with Client(fastapi_server) as client:
tools = await client.list_tools()
@ -1755,11 +1777,9 @@ class TestFastAPIDescriptionPropagation:
class TestReprMethods:
"""Tests for the custom __repr__ methods of OpenAPI objects."""
async def test_openapi_tool_repr(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
):
async def test_openapi_tool_repr(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""Test that OpenAPITool's __repr__ method works without recursion errors."""
tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()
tools = await fastmcp_openapi_server._tool_manager.list_tools()
tool = next(iter(tools))
# Verify repr doesn't cause recursion and contains expected elements
@ -1769,13 +1789,10 @@ class TestReprMethods:
assert "method=" in tool_repr
assert "path=" in tool_repr
async def test_openapi_resource_repr(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
):
async def test_openapi_resource_repr(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""Test that OpenAPIResource's __repr__ method works without recursion errors."""
resources = list(
fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
)
resources_dict = await fastmcp_openapi_server._resource_manager.get_resources()
resources = list(resources_dict.values())
resource = next(iter(resources))
# Verify repr doesn't cause recursion and contains expected elements
@ -1786,12 +1803,13 @@ class TestReprMethods:
assert "path=" in resource_repr
async def test_openapi_resource_template_repr(
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""Test that OpenAPIResourceTemplate's __repr__ method works without recursion errors."""
templates = list(
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
templates_dict = (
await fastmcp_openapi_server._resource_manager.get_resource_templates()
)
templates = list(templates_dict.values())
template = next(iter(templates))
# Verify repr doesn't cause recursion and contains expected elements
@ -1836,7 +1854,7 @@ class TestEnumHandling:
)
# Get the tools from the server
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
# Find the read_item tool
read_item_tool = next((t for t in tools if t.name == "read_item_items"), None)
@ -1929,7 +1947,7 @@ class TestRouteMapWildcard:
)
# All operations should be mapped to tools
tools = mcp._tool_manager.list_tools()
tools = await mcp._tool_manager.list_tools()
tool_names = {tool.name for tool in tools}
# Check that all 4 operations became tools
@ -2007,11 +2025,11 @@ class TestRouteMapTags:
)
# Check that admin-tagged routes are tools
tools = server._tool_manager.get_tools()
tool_names = {t.name for t in tools.values()}
tools_dict = await server._tool_manager.get_tools()
tool_names = {t.name for t in tools_dict.values()}
resources = server._resource_manager.get_resources()
resource_names = {r.name for r in resources.values()}
resources_dict = await server._resource_manager.get_resources()
resource_names = {r.name for r in resources_dict.values()}
# Routes with "admin" tag should be tools
assert "createUser" in tool_names
@ -2040,11 +2058,11 @@ class TestRouteMapTags:
)
# Check that internal-tagged routes are excluded
resources = server._resource_manager.get_resources()
resource_names = {r.name for r in resources.values()}
resources_dict = await server._resource_manager.get_resources()
resource_names = {r.name for r in resources_dict.values()}
tools = server._tool_manager.get_tools()
tool_names = {t.name for t in tools.values()}
tools_dict = await server._tool_manager.get_tools()
tool_names = {t.name for t in tools_dict.values()}
# Internal-tagged route should be excluded
assert "getAdminStats" not in resource_names
@ -2075,11 +2093,11 @@ class TestRouteMapTags:
route_maps=route_maps,
)
tools = server._tool_manager.get_tools()
tool_names = {t.name for t in tools.values()}
tools_dict = await server._tool_manager.get_tools()
tool_names = {t.name for t in tools_dict.values()}
resources = server._resource_manager.get_resources()
resource_names = {r.name for r in resources.values()}
resources_dict = await server._resource_manager.get_resources()
resource_names = {r.name for r in resources_dict.values()}
# Only createUser has both "users" AND "admin" tags
assert "createUser" in tool_names
@ -2110,11 +2128,11 @@ class TestRouteMapTags:
route_maps=route_maps,
)
tools = server._tool_manager.get_tools()
tool_names = {t.name for t in tools.values()}
tools_dict = await server._tool_manager.get_tools()
tool_names = {t.name for t in tools_dict.values()}
resources = server._resource_manager.get_resources()
resource_names = {r.name for r in resources.values()}
resources_dict = await server._resource_manager.get_resources()
resource_names = {r.name for r in resources_dict.values()}
# Only getAdminStats matches both /admin/ pattern AND "admin" tag
assert "getAdminStats" in tool_names
@ -2140,8 +2158,8 @@ class TestRouteMapTags:
route_maps=route_maps,
)
tools = server._tool_manager.get_tools()
tool_names = {t.name for t in tools.values()}
tools_dict = await server._tool_manager.get_tools()
tool_names = {t.name for t in tools_dict.values()}
# All routes should be tools since empty tags matches everything
expected_tools = {
@ -2246,18 +2264,18 @@ class TestMCPNames:
)
# Check tools use custom names
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
tool_names = {tool.name for tool in tools}
assert "admin_create_user" in tool_names
# Check resource templates use custom names
templates = list(server._resource_manager.get_templates().values())
template_names = {template.name for template in templates}
templates_dict = await server._resource_manager.get_resource_templates()
template_names = {template.name for template in templates_dict.values()}
assert "user_detail" in template_names
# Check resources use custom names
resources = list(server._resource_manager.get_resources().values())
resource_names = {resource.name for resource in resources}
resources_dict = await server._resource_manager.get_resources()
resource_names = {resource.name for resource in resources_dict.values()}
assert "user_list" in resource_names
async def test_mcp_names_fallback_to_operation_id_short(
@ -2276,14 +2294,14 @@ class TestMCPNames:
route_maps=GET_ROUTE_MAPS,
)
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
tool_names = {tool.name for tool in tools}
templates = list(server._resource_manager.get_templates().values())
template_names = {template.name for template in templates}
templates_dict = await server._resource_manager.get_resource_templates()
template_names = {template.name for template in templates_dict.values()}
resources = list(server._resource_manager.get_resources().values())
resource_names = {resource.name for resource in resources}
resources_dict = await server._resource_manager.get_resources()
resource_names = {resource.name for resource in resources_dict.values()}
# Custom mapped name should be used
assert "custom_user_list" in resource_names
@ -2300,9 +2318,11 @@ class TestMCPNames:
route_maps=GET_ROUTE_MAPS,
)
resources = list(server._resource_manager.get_resources().values())
resources_dict = await server._resource_manager.get_resources()
resource_names = {
resource.name for resource in resources if resource.name is not None
resource.name
for resource in resources_dict.values()
if resource.name is not None
}
# Special chars and spaces should be slugified
@ -2330,14 +2350,14 @@ class TestMCPNames:
# Check all component types
all_names = []
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
all_names.extend(tool.name for tool in tools)
resources = list(server._resource_manager.get_resources().values())
all_names.extend(resource.name for resource in resources)
resources_dict = await server._resource_manager.get_resources()
all_names.extend(resource.name for resource in resources_dict.values())
templates = list(server._resource_manager.get_templates().values())
all_names.extend(template.name for template in templates)
templates_dict = await server._resource_manager.get_resource_templates()
all_names.extend(template.name for template in templates_dict.values())
# All names should be 56 characters or less
for name in all_names:
@ -2363,7 +2383,7 @@ class TestMCPNames:
mcp_names=mcp_names,
)
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
tool_names = {tool.name for tool in tools}
assert "openapi_user_list" in tool_names
@ -2395,7 +2415,7 @@ class TestMCPNames:
mcp_names=mcp_names,
)
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
tool_names = {tool.name for tool in tools}
assert "fastapi_create_user" in tool_names
@ -2419,9 +2439,11 @@ class TestMCPNames:
route_maps=GET_ROUTE_MAPS,
)
resources = list(server._resource_manager.get_resources().values())
resources_dict = await server._resource_manager.get_resources()
resource_names = {
resource.name for resource in resources if resource.name is not None
resource.name
for resource in resources_dict.values()
if resource.name is not None
}
# Find the resource that should have the custom name
@ -2496,7 +2518,7 @@ class TestRouteMapMCPTags:
)
# Get the POST tool
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
create_user_tool = next((t for t in tools if "create_user" in t.name), None)
assert create_user_tool is not None, "create_user tool not found"
@ -2530,7 +2552,8 @@ class TestRouteMapMCPTags:
)
# Get the resource
resources = list(server._resource_manager.get_resources().values())
resources_dict = await server._resource_manager.get_resources()
resources = list(resources_dict.values())
get_users_resource = next((r for r in resources if "get_users" in r.name), None)
assert get_users_resource is not None, "get_users resource not found"
@ -2564,7 +2587,8 @@ class TestRouteMapMCPTags:
)
# Get the resource template
templates = list(server._resource_manager.get_templates().values())
templates_dict = await server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
get_user_template = next((t for t in templates if "get_user" in t.name), None)
assert get_user_template is not None, "get_user template not found"
@ -2610,21 +2634,23 @@ class TestRouteMapMCPTags:
)
# Check tool tags
tools = server._tool_manager.list_tools()
tools = await server._tool_manager.list_tools()
create_tool = next((t for t in tools if "create_user" in t.name), None)
assert create_tool is not None
assert "write-operation" in create_tool.tags
assert "mutation" in create_tool.tags
# Check resource template tags
templates = list(server._resource_manager.get_templates().values())
templates_dict = await server._resource_manager.get_resource_templates()
templates = list(templates_dict.values())
detail_template = next((t for t in templates if "get_user" in t.name), None)
assert detail_template is not None
assert "detail" in detail_template.tags
assert "single-item" in detail_template.tags
# Check resource tags
resources = list(server._resource_manager.get_resources().values())
resources_dict = await server._resource_manager.get_resources()
resources = list(resources_dict.values())
list_resource = next((r for r in resources if "get_users" in r.name), None)
assert list_resource is not None
assert "list" in list_resource.tags

View file

@ -25,7 +25,7 @@ async def test_import_basic_functionality():
assert "sub_tool" in sub_app._tool_manager._tools
# Verify the original tool still exists in the sub-app
tool = main_app._tool_manager.get_tool("sub_sub_tool")
tool = await main_app._tool_manager.get_tool("sub_sub_tool")
assert tool is not None
assert tool.name == "sub_tool"
assert isinstance(tool, FunctionTool)
@ -203,7 +203,7 @@ async def test_tool_custom_name_preserved_when_imported():
await main_app.import_server(api_app, "api")
# Check that the tool is accessible by its prefixed name
tool = main_app._tool_manager.get_tool("api_get_data")
tool = await main_app._tool_manager.get_tool("api_get_data")
assert tool is not None
# Check that the function name is preserved
@ -239,7 +239,7 @@ async def test_first_level_importing_with_custom_name():
await service_app.import_server(provider_app, "provider")
# Tool is accessible in the service app with the first prefix
tool = service_app._tool_manager.get_tool("provider_compute")
tool = await service_app._tool_manager.get_tool("provider_compute")
assert tool is not None
assert isinstance(tool, FunctionTool)
assert tool.fn.__name__ == "calculate_value"
@ -259,7 +259,7 @@ async def test_nested_importing_preserves_prefixes():
await main_app.import_server(service_app, "service")
# Tool is accessible in the main app with both prefixes
tool = main_app._tool_manager.get_tool("service_provider_compute")
tool = await main_app._tool_manager.get_tool("service_provider_compute")
assert tool is not None

View file

@ -71,7 +71,8 @@ class TestBasicMount:
# Mount without deprecated parameters
main_app.mount(api_app, "api")
async def test_mount_with_no_prefix(self):
@pytest.mark.parametrize("prefix", ["", None])
async def test_mount_with_no_prefix(self, prefix):
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@ -80,7 +81,7 @@ class TestBasicMount:
return "This is from the sub app"
# Mount with empty prefix but without deprecated separators
main_app.mount(sub_app, prefix="")
main_app.mount(sub_app, prefix=prefix)
tools = await main_app.get_tools()
# With empty prefix, the tool should keep its original name
@ -861,7 +862,7 @@ class TestAsProxyKwarg:
sub = FastMCP("Sub")
mcp.mount(sub, "sub")
assert mcp._mounted_servers[0].server is sub
assert mcp._tool_manager._mounted_servers[0].server is sub
async def test_as_proxy_false(self):
mcp = FastMCP("Main")
@ -869,7 +870,7 @@ class TestAsProxyKwarg:
mcp.mount(sub, "sub", as_proxy=False)
assert mcp._mounted_servers[0].server is sub
assert mcp._tool_manager._mounted_servers[0].server is sub
async def test_as_proxy_true(self):
mcp = FastMCP("Main")
@ -877,8 +878,8 @@ class TestAsProxyKwarg:
mcp.mount(sub, "sub", as_proxy=True)
assert mcp._mounted_servers[0].server is not sub
assert isinstance(mcp._mounted_servers[0].server, FastMCPProxy)
assert mcp._tool_manager._mounted_servers[0].server is not sub
assert isinstance(mcp._tool_manager._mounted_servers[0].server, FastMCPProxy)
async def test_as_proxy_defaults_true_if_lifespan(self):
@asynccontextmanager
@ -890,8 +891,8 @@ class TestAsProxyKwarg:
mcp.mount(sub, "sub")
assert mcp._mounted_servers[0].server is not sub
assert isinstance(mcp._mounted_servers[0].server, FastMCPProxy)
assert mcp._tool_manager._mounted_servers[0].server is not sub
assert isinstance(mcp._tool_manager._mounted_servers[0].server, FastMCPProxy)
async def test_as_proxy_ignored_for_proxy_mounts_default(self):
mcp = FastMCP("Main")
@ -900,7 +901,7 @@ class TestAsProxyKwarg:
mcp.mount(sub_proxy, "sub")
assert mcp._mounted_servers[0].server is sub_proxy
assert mcp._tool_manager._mounted_servers[0].server is sub_proxy
async def test_as_proxy_ignored_for_proxy_mounts_false(self):
mcp = FastMCP("Main")
@ -909,7 +910,7 @@ class TestAsProxyKwarg:
mcp.mount(sub_proxy, "sub", as_proxy=False)
assert mcp._mounted_servers[0].server is sub_proxy
assert mcp._tool_manager._mounted_servers[0].server is sub_proxy
async def test_as_proxy_ignored_for_proxy_mounts_true(self):
mcp = FastMCP("Main")
@ -918,7 +919,7 @@ class TestAsProxyKwarg:
mcp.mount(sub_proxy, "sub", as_proxy=True)
assert mcp._mounted_servers[0].server is sub_proxy
assert mcp._tool_manager._mounted_servers[0].server is sub_proxy
async def test_as_proxy_mounts_still_have_live_link(self):
mcp = FastMCP("Main")
@ -949,11 +950,14 @@ class TestAsProxyKwarg:
def hello():
return "hi"
mcp.mount(sub, "sub", as_proxy=True)
mcp.mount(sub, as_proxy=True)
assert lifespan_check == []
async with Client(mcp) as client:
await client.call_tool("sub_hello", {})
await client.call_tool("hello", {})
assert lifespan_check == ["start"]
assert len(lifespan_check) > 0
# in the present implementation the sub server will be invoked 3 times
# to call its tool
assert lifespan_check == ["start", "start", "start"]

View file

@ -56,8 +56,8 @@ async def test_resource_prefix_format_in_import_server():
await main_server_protocol.import_server(server, "sub")
# Check that the resources are prefixed correctly
path_resources = main_server_path._resource_manager.get_resources()
protocol_resources = main_server_protocol._resource_manager.get_resources()
path_resources = await main_server_path._resource_manager.get_resources()
protocol_resources = await main_server_protocol._resource_manager.get_resources()
# Path format should be resource://sub/test
assert "resource://sub/test" in path_resources

View file

@ -282,7 +282,7 @@ class TestToolDecorator:
return x * 2
# Verify the tags were set correctly
tools = mcp._tool_manager.list_tools()
tools = await mcp._tool_manager.list_tools()
assert len(tools) == 1
assert tools[0].tags == {"example", "test-tag"}

View file

@ -22,7 +22,8 @@ async def test_tool_annotations_in_tool_manager():
return message
# Check internal tool objects directly
tools = mcp._tool_manager.list_tools()
tools_dict = await mcp._tool_manager.get_tools()
tools = list(tools_dict.values())
assert len(tools) == 1
assert tools[0].annotations is not None
assert tools[0].annotations.title == "Echo Tool"
@ -124,7 +125,8 @@ async def test_direct_tool_annotations_in_tool_manager():
return {"modified": True, **data}
# Check internal tool objects directly
tools = mcp._tool_manager.list_tools()
tools_dict = await mcp._tool_manager.get_tools()
tools = list(tools_dict.values())
assert len(tools) == 1
assert tools[0].annotations is not None
assert tools[0].annotations.title == "Direct Tool"
@ -183,7 +185,8 @@ async def test_add_tool_method_annotations():
mcp.add_tool(tool)
# Check internal tool objects directly
tools = mcp._tool_manager.list_tools()
tools_dict = await mcp._tool_manager.get_tools()
tools = list(tools_dict.values())
assert len(tools) == 1
assert tools[0].annotations is not None
assert tools[0].annotations.title == "Create Item"

View file

@ -19,9 +19,10 @@ async def test_tool_exclude_args_in_tool_manager():
pass
return message
tools = mcp._tool_manager.list_tools()
tools_dict = await mcp._tool_manager.get_tools()
tools = list(tools_dict.values())
assert len(tools) == 1
assert "state" not in echo.parameters["properties"]
assert "state" not in tools[0].parameters["properties"]
async def test_tool_exclude_args_without_default_value_raises_error():
@ -60,7 +61,8 @@ async def test_add_tool_method_exclude_args():
mcp.add_tool(tool)
# Check internal tool objects directly
tools = mcp._tool_manager.list_tools()
tools_dict = await mcp._tool_manager.get_tools()
tools = list(tools_dict.values())
assert len(tools) == 1
assert "state" not in tools[0].parameters["properties"]

View file

@ -17,7 +17,7 @@ from fastmcp.utilities.types import Image
class TestAddTools:
def test_basic_function(self):
async def test_basic_function(self):
"""Test registering and running a basic function."""
def add(a: int, b: int) -> int:
@ -28,7 +28,7 @@ class TestAddTools:
tool = Tool.from_function(add)
manager.add_tool(tool)
tool = manager.get_tool("add")
tool = await manager.get_tool("add")
assert tool is not None
assert tool.name == "add"
assert tool.description == "Add two numbers."
@ -46,13 +46,13 @@ class TestAddTools:
tool = Tool.from_function(fetch_data)
manager.add_tool(tool)
tool = manager.get_tool("fetch_data")
tool = await manager.get_tool("fetch_data")
assert tool is not None
assert tool.name == "fetch_data"
assert tool.description == "Fetch data from URL."
assert tool.parameters["properties"]["url"]["type"] == "string"
def test_pydantic_model_function(self):
async def test_pydantic_model_function(self):
"""Test registering a function that takes a Pydantic model."""
class UserInput(BaseModel):
@ -67,7 +67,7 @@ class TestAddTools:
tool = Tool.from_function(create_user)
manager.add_tool(tool)
tool = manager.get_tool("create_user")
tool = await manager.get_tool("create_user")
assert tool is not None
assert tool.name == "create_user"
assert tool.description == "Create a new user."
@ -75,7 +75,7 @@ class TestAddTools:
assert "age" in tool.parameters["$defs"]["UserInput"]["properties"]
assert "flag" in tool.parameters["properties"]
def test_callable_object(self):
async def test_callable_object(self):
class Adder:
"""Adds two numbers."""
@ -87,7 +87,7 @@ class TestAddTools:
tool = Tool.from_function(Adder())
manager.add_tool(tool)
tool = manager.get_tool("Adder")
tool = await manager.get_tool("Adder")
assert tool is not None
assert tool.name == "Adder"
assert tool.description == "Adds two numbers."
@ -95,7 +95,7 @@ class TestAddTools:
assert tool.parameters["properties"]["x"]["type"] == "integer"
assert tool.parameters["properties"]["y"]["type"] == "integer"
def test_async_callable_object(self):
async def test_async_callable_object(self):
class Adder:
"""Adds two numbers."""
@ -107,7 +107,7 @@ class TestAddTools:
tool = Tool.from_function(Adder())
manager.add_tool(tool)
tool = manager.get_tool("Adder")
tool = await manager.get_tool("Adder")
assert tool is not None
assert tool.name == "Adder"
assert tool.description == "Adds two numbers."
@ -123,7 +123,7 @@ class TestAddTools:
tool = Tool.from_function(image_tool)
manager.add_tool(tool)
tool = manager.get_tool("image_tool")
tool = await manager.get_tool("image_tool")
result = await tool.run({"data": "test.png"})
assert tool.parameters["properties"]["data"]["type"] == "string"
assert isinstance(result[0], ImageContent)
@ -148,7 +148,7 @@ class TestAddTools:
tool = Tool.from_function(lambda x: x)
manager.add_tool(tool)
def test_remove_tool_successfully(self):
async def test_remove_tool_successfully(self):
"""Test removing an added tool by key."""
manager = ToolManager()
@ -157,19 +157,19 @@ class TestAddTools:
tool = Tool.from_function(add)
manager.add_tool(tool)
assert manager.get_tool("add") is not None
assert await manager.get_tool("add") is not None
manager.remove_tool("add")
with pytest.raises(NotFoundError):
manager.get_tool("add")
await manager.get_tool("add")
def test_remove_tool_missing_key(self):
"""Test removing a tool that does not exist raises NotFoundError."""
manager = ToolManager()
with pytest.raises(NotFoundError, match=f"Unknown tool: {'missing'}"):
with pytest.raises(NotFoundError, match="Tool 'missing' not found"):
manager.remove_tool("missing")
def test_warn_on_duplicate_tools(self, caplog):
async def test_warn_on_duplicate_tools(self, caplog):
"""Test warning on duplicate tools."""
manager = ToolManager(duplicate_behavior="warn")
@ -183,7 +183,7 @@ class TestAddTools:
assert "Tool already exists: test_tool" in caplog.text
# Should have the tool
assert manager.get_tool("test_tool") is not None
assert await manager.get_tool("test_tool") is not None
def test_disable_warn_on_duplicate_tools(self, caplog):
"""Test disabling warning on duplicate tools."""
@ -213,7 +213,7 @@ class TestAddTools:
tool2 = Tool.from_function(test_fn, name="test_tool")
manager.add_tool(tool2)
def test_replace_duplicate_tools(self):
async def test_replace_duplicate_tools(self):
"""Test replacing duplicate tools."""
manager = ToolManager(duplicate_behavior="replace")
@ -229,12 +229,12 @@ class TestAddTools:
manager.add_tool(result)
# Should have replaced with the new tool
tool = manager.get_tool("test_tool")
tool = await manager.get_tool("test_tool")
assert tool is not None
assert isinstance(tool, FunctionTool)
assert tool.fn.__name__ == "replacement_fn"
def test_ignore_duplicate_tools(self):
async def test_ignore_duplicate_tools(self):
"""Test ignoring duplicate tools."""
manager = ToolManager(duplicate_behavior="ignore")
@ -250,7 +250,7 @@ class TestAddTools:
manager.add_tool(result)
# Should keep the original
tool = manager.get_tool("test_tool")
tool = await manager.get_tool("test_tool")
assert tool is not None
assert isinstance(tool, FunctionTool)
assert tool.fn.__name__ == "original_fn"
@ -262,7 +262,7 @@ class TestAddTools:
class TestToolTags:
"""Test functionality related to tool tags."""
def test_add_tool_with_tags(self):
async def test_add_tool_with_tags(self):
"""Test adding tags to a tool."""
def example_tool(x: int) -> int:
@ -274,11 +274,11 @@ class TestToolTags:
manager.add_tool(tool)
assert tool.tags == {"math", "utility"}
tool = manager.get_tool("example_tool")
tool = await manager.get_tool("example_tool")
assert tool is not None
assert tool.tags == {"math", "utility"}
def test_add_tool_with_empty_tags(self):
async def test_add_tool_with_empty_tags(self):
"""Test adding a tool with empty tags set."""
def example_tool(x: int) -> int:
@ -291,7 +291,7 @@ class TestToolTags:
assert tool.tags == set()
def test_add_tool_with_none_tags(self):
async def test_add_tool_with_none_tags(self):
"""Test adding a tool with None tags."""
def example_tool(x: int) -> int:
@ -304,7 +304,7 @@ class TestToolTags:
assert tool.tags == set()
def test_list_tools_with_tags(self):
async def test_list_tools_with_tags(self):
"""Test listing tools with specific tags."""
def math_tool(x: int) -> int:
@ -328,12 +328,16 @@ class TestToolTags:
manager.add_tool(tool3)
# Check if we can filter by tags when listing tools
math_tools = [tool for tool in manager.list_tools() if "math" in tool.tags]
math_tools = [
tool for tool in (await manager.get_tools()).values() if "math" in tool.tags
]
assert len(math_tools) == 2
assert {tool.name for tool in math_tools} == {"math_tool", "mixed_tool"}
utility_tools = [
tool for tool in manager.list_tools() if "utility" in tool.tags
tool
for tool in (await manager.get_tools()).values()
if "utility" in tool.tags
]
assert len(utility_tools) == 2
assert {tool.name for tool in utility_tools} == {"string_tool", "mixed_tool"}
@ -416,7 +420,7 @@ class TestCallTools:
async def test_call_unknown_tool(self):
manager = ToolManager()
with pytest.raises(NotFoundError, match="Unknown tool: unknown"):
with pytest.raises(NotFoundError, match="Tool 'unknown' not found"):
await manager.call_tool("unknown", {"a": 1})
async def test_call_tool_with_list_int_input(self):
@ -728,7 +732,7 @@ class TestContextHandling:
class TestCustomToolNames:
"""Test adding tools with custom names that differ from their function names."""
def test_add_tool_with_custom_name(self):
async def test_add_tool_with_custom_name(self):
"""Test adding a tool with a custom name parameter using add_tool_from_fn."""
def original_fn(x: int) -> int:
@ -739,15 +743,15 @@ class TestCustomToolNames:
manager.add_tool(tool)
# The tool is stored under the custom name and its .name is also set to custom_name
assert manager.get_tool("custom_name") is not None
assert await manager.get_tool("custom_name") is not None
assert tool.name == "custom_name"
assert isinstance(tool, FunctionTool)
assert tool.fn.__name__ == "original_fn"
# The tool should not be accessible via its original function name
with pytest.raises(NotFoundError, match="Unknown tool: original_fn"):
manager.get_tool("original_fn")
with pytest.raises(NotFoundError, match="Tool 'original_fn' not found"):
await manager.get_tool("original_fn")
def test_add_tool_object_with_custom_key(self):
async def test_add_tool_object_with_custom_key(self):
"""Test adding a Tool object with a custom key using add_tool()."""
def fn(x: int) -> int:
@ -756,16 +760,17 @@ class TestCustomToolNames:
# Create a tool with a specific name
tool = Tool.from_function(fn, name="my_tool")
manager = ToolManager()
# Store it under a different name
manager.add_tool(tool, key="proxy_tool")
# Use with_key to create a new tool with the custom key
tool_with_custom_key = tool.with_key("proxy_tool")
manager.add_tool(tool_with_custom_key)
# The tool is accessible under the key
stored = manager.get_tool("proxy_tool")
stored = await manager.get_tool("proxy_tool")
assert stored is not None
# But the tool's .name is unchanged
assert stored.name == "my_tool"
# The tool is not accessible under its original name
with pytest.raises(NotFoundError, match="Unknown tool: my_tool"):
manager.get_tool("my_tool")
with pytest.raises(NotFoundError, match="Tool 'my_tool' not found"):
await manager.get_tool("my_tool")
async def test_call_tool_with_custom_name(self):
"""Test calling a tool added with a custom name."""
@ -783,10 +788,10 @@ class TestCustomToolNames:
assert result[0].text == "15" # type: ignore[attr-defined]
# Original name should not be registered
with pytest.raises(NotFoundError, match="Unknown tool: multiply"):
with pytest.raises(NotFoundError, match="Tool 'multiply' not found"):
await manager.call_tool("multiply", {"a": 5, "b": 3})
def test_replace_tool_keeps_original_name(self):
async def test_replace_tool_keeps_original_name(self):
"""Test that replacing a tool with "replace" keeps the original name."""
def original_fn(x: int) -> int:
@ -808,7 +813,7 @@ class TestCustomToolNames:
manager.add_tool(replacement_tool)
# The tool object should have been replaced
stored_tool = manager.get_tool("test_tool")
stored_tool = await manager.get_tool("test_tool")
assert stored_tool is not None
assert stored_tool == replacement_tool