Merge branch 'main' into settings

This commit is contained in:
Jeremiah Lowin 2025-06-10 12:02:39 -04:00
commit 6dc2bd7ca2
46 changed files with 3662 additions and 328 deletions

20
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,20 @@
version: 2
updates:
- package-ecosystem: "uv"
directory: "/"
schedule:
interval: "daily"
labels:
- "dependencies"
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
labels:
- "dependencies"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
labels:
- "dependencies"

10
.github/release.yml vendored
View file

@ -7,6 +7,12 @@ changelog:
- title: New Features 🎉
labels:
- feature
exclude:
labels:
- breaking change
- title: Enhancements 🔧
labels:
- enhancement
exclude:
labels:
@ -27,6 +33,10 @@ changelog:
labels:
- documentation
- title: Dependencies 📦
labels:
- dependencies
- title: Other Changes 🦾
labels:
- "*"

View file

@ -17,7 +17,7 @@ jobs:
fetch-depth: 0
- name: "Install uv"
uses: astral-sh/setup-uv@v3
uses: astral-sh/setup-uv@v6
- name: Build
run: uv build

View file

@ -32,7 +32,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: "uv.lock"

View file

@ -37,7 +37,7 @@ jobs:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: "uv.lock"

View file

@ -4,6 +4,8 @@
# FastMCP v2 🚀
<strong>The fast, Pythonic way to build MCP servers and clients.</strong>
*FastMCP is made with 💙 by [Prefect](https://www.prefect.io/)*
[![Docs](https://img.shields.io/badge/docs-gofastmcp.com-blue)](https://gofastmcp.com)
[![PyPI - Version](https://img.shields.io/pypi/v/fastmcp.svg)](https://pypi.org/project/fastmcp)
[![Tests](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml/badge.svg)](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml)

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 KiB

View file

@ -125,6 +125,7 @@
{
"group": "Patterns",
"pages": [
"patterns/tool-transformation",
"patterns/decorating-methods",
"patterns/http-requests",
"patterns/testing",

View file

@ -72,7 +72,7 @@ For users concerned about stability in production environments, we recommend pin
Whenever possible, FastMCP will issue deprecation warnings when users attempt to use APIs that are either deprecated or destined for future removal. These warnings will be maintained for at least 1 minor version release, and may be maintained longer.
Note that the "public API" includes the core functionality of the `FastMCP` server and its methods. It does not include private methods or objects that are stored as private attributes, as we do not expect users to rely on those implementation details.
Note that the "public API" includes the public functionality of the `FastMCP` server, core FastMCP components like `Tool`, `Prompt`, `Resource`, and `ResourceTemplate`, and their respective public methods. It does not include private methods, utilities, or objects that are stored as private attributes, as we do not expect users to rely on those implementation details.
## Installing for Development

View file

@ -2,7 +2,6 @@
title: "Welcome to FastMCP 2.0!"
sidebarTitle: "Welcome!"
description: The fast, Pythonic way to build MCP servers and clients.
icon: hand-wave
---
@ -60,6 +59,9 @@ FastMCP aims to be:
🔍 **Complete**: A comprehensive platform for all MCP use cases, from dev to prod
FastMCP is made with 💙 by [Prefect](https://www.prefect.io/).
## `llms.txt`

View file

@ -1,6 +1,6 @@
---
title: Anthropic
sidebarTitle: Anthropic
title: Anthropic API + FastMCP
sidebarTitle: Anthropic API
description: Call FastMCP servers from the Anthropic API
icon: message-smile
tag: "New!"
@ -8,9 +8,6 @@ tag: "New!"
import { VersionBadge } from "/snippets/version-badge.mdx"
Anthropic supports MCP servers through the [MCP connector](https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector) feature in the Messages API, allowing you to extend AI capabilities with custom tools from remote MCP servers.
## Messages API
Anthropic's [Messages API](https://docs.anthropic.com/en/api/messages) supports MCP servers as remote tool sources. This tutorial will show you how to create a FastMCP server and deploy it to a public URL, then how to call it from the Messages API.
@ -18,7 +15,7 @@ Anthropic's [Messages API](https://docs.anthropic.com/en/api/messages) supports
Currently, the MCP connector only accesses **tools** from MCP servers—it queries the `list_tools` endpoint and exposes those functions to Claude. Other MCP features like resources and prompts are not currently supported. You can read more about the MCP connector in the [Anthropic documentation](https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector).
</Tip>
### Create a Server
## Create a Server
First, create a FastMCP server with the tools you want to expose. For this example, we'll create a server with a single tool that rolls dice.
@ -37,7 +34,7 @@ if __name__ == "__main__":
mcp.run(transport="sse", port=8000)
```
### Deploy the Server
## Deploy the Server
Your server must be deployed to a public URL in order for Anthropic to access it. The MCP connector supports both SSE and Streamable HTTP transports.
@ -59,7 +56,7 @@ ngrok http 8000
This exposes your unauthenticated server to the internet. Only run this command in a safe environment if you understand the risks.
</Warning>
### Call the Server
## Call the Server
To use the Messages API with MCP servers, you'll need to install the Anthropic Python SDK (not included with FastMCP):
@ -114,13 +111,13 @@ The results were 4, 2, and 6. Would you like me to roll again or roll a differen
```
### Authentication
## Authentication
<VersionBadge version="2.6.0" />
The MCP connector supports OAuth authentication through authorization tokens, which means you can secure your server while still allowing Anthropic to access it.
#### Server Authentication
### Server Authentication
The simplest way to add authentication to the server is to use a bearer token scheme.
@ -181,7 +178,7 @@ if __name__ == "__main__":
mcp.run(transport="sse", port=8000)
```
#### Client Authentication
### Client Authentication
If you try to call the authenticated server with the same Anthropic code we wrote earlier, you'll get an error indicating that the server rejected the request because it's not authenticated.

View file

@ -1,5 +1,5 @@
---
title: Claude Desktop
title: Claude Desktop + FastMCP
sidebarTitle: Claude Desktop
description: Call FastMCP servers from Claude Desktop
icon: desktop

View file

@ -1,5 +1,5 @@
---
title: Gemini SDK
title: Gemini SDK + FastMCP
sidebarTitle: Gemini SDK
description: Call FastMCP servers from the Google Gemini SDK
icon: message-smile
@ -98,7 +98,7 @@ For example, to connect to a remote, authenticated server, you can use the follo
from fastmcp import Client
from fastmcp.client.auth import BearerAuth
client = Client(
mcp_client = Client(
"https://my-server.com/sse",
auth=BearerAuth("<your-token>"),
)

View file

@ -1,6 +1,6 @@
---
title: OpenAI
sidebarTitle: OpenAI
title: OpenAI API + FastMCP
sidebarTitle: OpenAI API
description: Call FastMCP servers from the OpenAI API
icon: message-smile
tag: "New!"
@ -8,14 +8,13 @@ tag: "New!"
import { VersionBadge } from "/snippets/version-badge.mdx"
OpenAI recently announced support for MCP servers in the Responses API. Note that at this time, MCP is not supported in ChatGPT.
## Responses API
OpenAI's [Responses API](https://platform.openai.com/docs/api-reference/responses) supports [MCP servers](https://platform.openai.com/docs/guides/tools-remote-mcp) as remote tool sources, allowing you to extend AI capabilities with custom functions.
<Note>
The Responses API is a distinct API from OpenAI's Completions API, Assistants API, or ChatGPT. At this time, only the Responses API supports MCP.
The Responses API is a distinct API from OpenAI's Completions API or Assistants API. At this time, only the Responses API supports MCP.
</Note>
<Tip>

View file

@ -0,0 +1,454 @@
---
title: Tool Transformation
sidebarTitle: Tool Transformation
description: Create enhanced tool variants with modified schemas, argument mappings, and custom behavior.
icon: wand-magic-sparkles
---
import { VersionBadge } from '/snippets/version-badge.mdx'
<VersionBadge version="2.8.0" />
Tool transformation allows you to create new, enhanced tools from existing ones. This powerful feature enables you to adapt tools for different contexts, simplify complex interfaces, or add custom logic without duplicating code.
## Why Transform Tools?
Often, an existing tool is *almost* perfect for your use case, but it might have:
- A confusing description (or no description at all).
- Argument names or descriptions that are not intuitive for an LLM (e.g., `q` instead of `query`).
- Unnecessary parameters that you want to hide from the LLM.
- A need for input validation before the original tool is called.
- A need to modify or format the tool's output.
Instead of rewriting the tool from scratch, you can **transform** it to fit your needs.
## Basic Transformation
The primary way to create a transformed tool is with the `Tool.from_tool()` class method. At its simplest, you can use it to change a tool's top-level metadata like its `name`, `description`, or `tags`.
In the following simple example, we take a generic `search` tool and adjust its name and description to help an LLM client better understand its purpose.
```python {13-21}
from fastmcp import FastMCP
from fastmcp.tools import Tool
mcp = FastMCP()
# The original, generic tool
@mcp.tool
def search(query: str, category: str = "all") -> list[dict]:
"""Searches for items in the database."""
return database.search(query, category)
# Create a more domain-specific version by changing its metadata
product_search_tool = Tool.from_tool(
search,
name="find_products",
description="""
Search for products in the e-commerce catalog.
Use this when customers ask about finding specific items,
checking availability, or browsing product categories.
""",
)
mcp.add_tool(product_search_tool)
```
<Tip>
When you transform a tool, the original tool remains registered on the server. To avoid confusing an LLM with two similar tools, you can disable the original one:
```python
from fastmcp import FastMCP
from fastmcp.tools import Tool
mcp = FastMCP()
# The original, generic tool
@mcp.tool
def search(query: str, category: str = "all") -> list[dict]:
...
# Create a more domain-specific version
product_search_tool = Tool.from_tool(search, ...)
mcp.add_tool(product_search_tool)
# Disable the original tool
search.disable()
```
</Tip>
Now, clients see a tool named `find_products` with a clear, domain-specific purpose and relevant tags, even though it still uses the original generic `search` function's logic.
### Parameters
The `Tool.from_tool()` class method is the primary way to create a transformed tool. It takes the following parameters:
- `tool`: The tool to transform. This is the only required argument.
- `name`: An optional name for the new tool.
- `description`: An optional description for the new tool.
- `transform_args`: A dictionary of `ArgTransform` objects, one for each argument you want to modify.
- `transform_fn`: An optional function that will be called instead of the parent tool's logic.
- `tags`: An optional set of tags for the new tool.
- `annotations`: An optional set of `ToolAnnotations` for the new tool.
- `serializer`: An optional function that will be called to serialize the result of the new tool.
The result is a new `TransformedTool` object that wraps the parent tool and applies the transformations you specify. You can add this tool to your MCP server using its `add_tool()` method.
## Modifying Arguments
To modify a tool's parameters, provide a dictionary of `ArgTransform` objects to the `transform_args` parameter of `Tool.from_tool()`. Each key is the name of the *original* argument you want to modify.
<Tip>
You only need to provide a `transform_args` entry for arguments you want to modify. All other arguments will be passed through unchanged.
</Tip>
### The ArgTransform Class
To modify an argument, you need to create an `ArgTransform` object. This object has the following parameters:
- `name`: The new name for the argument.
- `description`: The new description for the argument.
- `default`: The new default value for the argument.
- `default_factory`: A function that will be called to generate a default value for the argument. This is useful for arguments that need to be generated for each tool call, such as timestamps or unique IDs.
- `hide`: Whether to hide the argument from the LLM.
- `required`: Whether the argument is required, usually used to make an optional argument be required instead.
- `type`: The new type for the argument.
<Tip>
Certain combinations of parameters are not allowed. For example, you can only use `default_factory` with `hide=True`, because dynamic defaults cannot be represented in a JSON schema for the client. You can only set required=True for arguments that do not declare a default value.
</Tip>
### Descriptions
By far the most common reason to transform a tool, after its own description, is to improve its argument descriptions. A good description is crucial for helping an LLM understand how to use a parameter correctly. This is especially important when wrapping tools from external APIs, whose argument descriptions may be missing or written for developers, not LLMs.
In this example, we add a helpful description to the `user_id` argument:
```python {16-19}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import ArgTransform
mcp = FastMCP()
@mcp.tool
def find_user(user_id: str):
"""Finds a user by their ID."""
...
new_tool = Tool.from_tool(
find_user,
transform_args={
"user_id": ArgTransform(
description=(
"The unique identifier for the user, "
"usually in the format 'usr-xxxxxxxx'."
)
)
}
)
```
### Names
At times, you may want to rename an argument to make it more intuitive for an LLM.
For example, in the following example, we take a generic `q` argument and expand it to `search_query`:
```python {15}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import ArgTransform
mcp = FastMCP()
@mcp.tool
def search(q: str):
"""Searches for items in the database."""
return database.search(q)
new_tool = Tool.from_tool(
search,
transform_args={
"q": ArgTransform(name="search_query")
}
)
```
### Default Values
You can update the default value for any argument using the `default` parameter. Here, we change the default value of the `y` argument to 10:
```python{15}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import ArgTransform
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
"""Adds two numbers."""
return x + y
new_tool = Tool.from_tool(
add,
transform_args={
"y": ArgTransform(default=10)
}
)
```
Default values are especially useful in combination with hidden arguments.
### Hiding Arguments
Sometimes a tool requires arguments that shouldn't be exposed to the LLM, such as API keys, configuration flags, or internal IDs. You can hide these parameters using `hide=True`. Note that you can only hide arguments that have a default value (or for which you provide a new default), because the LLM can't provide a value at call time.
<Tip>
To pass a constant value to the parent tool, combine `hide=True` with `default=<value>`.
</Tip>
```python {19-20}
import os
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import ArgTransform
mcp = FastMCP()
@mcp.tool
def send_email(to: str, subject: str, body: str, api_key: str):
"""Sends an email."""
...
# Create a simplified version that hides the API key
new_tool = Tool.from_tool(
send_email,
name="send_notification",
transform_args={
"api_key": ArgTransform(
hide=True,
default=os.environ.get("EMAIL_API_KEY"),
)
}
)
```
The LLM now only sees the `to`, `subject`, and `body` parameters. The `api_key` is supplied automatically from an environment variable.
For values that must be generated for each tool call (like timestamps or unique IDs), use `default_factory`, which is called with no arguments every time the tool is called. For example,
```python {3-4}
transform_args = {
'timestamp': ArgTransform(
hide=True,
default_factory=lambda: datetime.now(),
)
}
```
<Warning>
`default_factory` can only be used with `hide=True`. This is because visible parameters need static defaults that can be represented in a JSON schema for the client.
</Warning>
### Required Values
In rare cases where you want to make an optional argument required, you can set `required=True`. This has no effect if the argument was already required.
```python {3}
transform_args = {
'user_id': ArgTransform(
required=True,
)
}
```
## Modifying Tool Behavior
<Warning>
With great power comes great responsibility. Modifying tool behavior is a very advanced feature.
</Warning>
In addition to changing a tool's schema, advanced users can also modify its behavior. This is useful for adding validation logic, or for post-processing the tool's output.
The `from_tool()` method takes a `transform_fn` parameter, which is an async function that replaces the parent tool's logic and gives you complete control over the tool's execution.
### The Transform Function
The `transform_fn` is an async function that **completely replaces** the parent tool's logic.
Critically, the transform function's arguments are used to determine the new tool's final schema. Any arguments that are not already present in the parent tool schema OR the `transform_args` will be added to the new tool's schema. Note that when `transform_args` and your function have the same argument name, the `transform_args` metadata will take precedence, if provided.
```python
async def my_custom_logic(user_input: str, max_length: int = 100) -> str:
# Your custom logic here - this completely replaces the parent tool
return f"Custom result for: {user_input[:max_length]}"
Tool.from_tool(transform_fn=my_custom_logic)
```
<Tip>
The name / docstring of the `transform_fn` are ignored. Only its arguments are used to determine the final schema.
</Tip>
### Calling the Parent Tool
Most of the time, you don't want to completely replace the parent tool's behavior. Instead, you want to add validation, modify inputs, or post-process outputs while still leveraging the parent tool's core functionality. For this, FastMCP provides the special `forward()` and `forward_raw()` functions.
Both `forward()` and `forward_raw()` are async functions that let you call the parent tool from within your `transform_fn`:
- **`forward()`** (recommended): Automatically handles argument mapping based on your `ArgTransform` configurations. Call it with the transformed argument names.
- **`forward_raw()`**: Bypasses all transformation and calls the parent tool directly with its original argument names. This is rarely needed unless you're doing complex argument manipulation, perhaps without `arg_transforms`.
The most common transformation pattern is to validate (potentially renamed) arguments before calling the parent tool. Here's an example that validates that `x` and `y` are positive before calling the parent tool:
<Tabs>
<Tab title="Using forward()">
In the simplest case, your parent tool and your transform function have the same arguments. You can call `forward()` with the same argument names as the parent tool:
```python {15}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import forward
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
"""Adds two numbers."""
return x + y
async def ensure_positive(x: int, y: int) -> int:
if x <= 0 or y <= 0:
raise ValueError("x and y must be positive")
return await forward(x=x, y=y)
new_tool = Tool.from_tool(
add,
transform_fn=ensure_positive,
)
mcp.add_tool(new_tool)
```
</Tab>
<Tab title="Using forward() with renamed args">
When your transformed tool has different argument names than the parent tool, you can call `forward()` with the renamed arguments and it will automatically map the arguments to the parent tool's arguments:
```python {15, 20-23}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import forward
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
"""Adds two numbers."""
return x + y
async def ensure_positive(a: int, b: int) -> int:
if a <= 0 or b <= 0:
raise ValueError("a and b must be positive")
return await forward(a=a, b=b)
new_tool = Tool.from_tool(
add,
transform_fn=ensure_positive,
transform_args={
"x": ArgTransform(name="a"),
"y": ArgTransform(name="b"),
}
)
mcp.add_tool(new_tool)
```
</Tab>
<Tab title="Using forward_raw()">
Finally, you can use `forward_raw()` to bypass all argument mapping and call the parent tool directly with its original argument names.
```python {15, 20-23}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import forward
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
"""Adds two numbers."""
return x + y
async def ensure_positive(a: int, b: int) -> int:
if a <= 0 or b <= 0:
raise ValueError("a and b must be positive")
return await forward_raw(x=a, y=b)
new_tool = Tool.from_tool(
add,
transform_fn=ensure_positive,
transform_args={
"x": ArgTransform(name="a"),
"y": ArgTransform(name="b"),
}
)
mcp.add_tool(new_tool)
```
</Tab>
</Tabs>
### Passing Arguments with **kwargs
If your `transform_fn` includes `**kwargs` in its signature, it will receive **all arguments from the parent tool after `ArgTransform` configurations have been applied**. This is powerful for creating flexible validation functions that don't require you to add every argument to the function signature.
In the following example, we wrap a parent tool that accepts two arguments `x` and `y`. These are renamed to `a` and `b` in the transformed tool, and the transform only validates `a`, passing the other argument through as `**kwargs`.
```python {12, 15}
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.tools.tool_transform import forward
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
"""Adds two numbers."""
return x + y
async def ensure_a_positive(a: int, **kwargs) -> int:
if a <= 0:
raise ValueError("a must be positive")
return await forward(a=a, **kwargs)
new_tool = Tool.from_tool(
add,
transform_fn=ensure_a_positive,
transform_args={
"x": ArgTransform(name="a"),
"y": ArgTransform(name="b"),
}
)
mcp.add_tool(new_tool)
```
<Tip>
In the above example, `**kwargs` receives the renamed argument `b`, not the original argument `y`. It is therefore recommended to use with `forward()`, not `forward_raw()`.
</Tip>
## Common Patterns
Tool transformation is a flexible feature that supports many powerful patterns. Here are a few common use cases to give you ideas.
### Adapting Remote or Generated Tools
This is one of the most common reasons to use tool transformation. Tools from remote servers (via a [proxy](/servers/proxy)) or generated from an [OpenAPI spec](/servers/openapi) are often too generic for direct use by an LLM. You can use transformation to create a simpler, more intuitive version for your specific needs.
### Chaining Transformations
You can chain transformations by using an already transformed tool as the parent for a new transformation. This lets you build up complex behaviors in layers, for example, first renaming arguments, and then adding validation logic to the renamed tool.
### Context-Aware Tool Factories
You can write functions that act as "factories," generating specialized versions of a tool for different contexts. For example, you could create a `get_my_data` tool that is specific to the currently logged-in user by hiding the `user_id` parameter and providing it automatically.

View file

@ -147,7 +147,32 @@ def data_analysis_prompt(
- **`name`**: Sets the explicit prompt name exposed via MCP.
- **`description`**: Provides the description exposed via MCP. If set, the function's docstring is ignored for this purpose.
- **`tags`**: A set of strings used to categorize the prompt. Clients *might* use tags to filter or group available prompts.
- **`enabled`**: A boolean to enable or disable the prompt (defaults to `True`). See [Disabling Prompts](#disabling-prompts) for more information.
### Disabling Prompts
<VersionBadge version="2.8.0" />
You can control the visibility and availability of prompts by enabling or disabling them. Disabled prompts will not appear in the list of available prompts, and attempting to call a disabled prompt will result in an "Unknown prompt" error.
By default, all prompts are enabled. You can disable a prompt upon creation using the `enabled` parameter in the decorator:
```python
@mcp.prompt(enabled=False)
def experimental_prompt():
"""This prompt is not ready for use."""
return "This is an experimental prompt."
```
You can also toggle a prompt's state programmatically after it has been created:
```python
@mcp.prompt
def seasonal_prompt(): return "Happy Holidays!"
# Disable and re-enable the prompt
seasonal_prompt.disable()
seasonal_prompt.enable()
```
### Asynchronous Prompts
FastMCP seamlessly supports both standard (`def`) and asynchronous (`async def`) functions as prompts.
@ -191,6 +216,8 @@ async def generate_report_request(report_type: str, ctx: Context) -> str:
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
## Server Behavior
### Duplicate Prompts

View file

@ -94,6 +94,33 @@ def get_application_status() -> dict:
- **`description`**: Explanation of the resource (defaults to docstring).
- **`mime_type`**: Specifies the content type (FastMCP often infers a default like `text/plain` or `application/json`, but explicit is better for non-text types).
- **`tags`**: A set of strings for categorization, potentially used by clients for filtering.
- **`enabled`**: A boolean to enable or disable the resource (defaults to `True`). See [Disabling Resources](#disabling-resources) for more information.
### Disabling Resources
<VersionBadge version="2.8.0" />
You can control the visibility and availability of resources and templates by enabling or disabling them. Disabled resources will not appear in the list of available resources or templates, and attempting to read a disabled resource will result in an "Unknown resource" error.
By default, all resources are enabled. You can disable a resource upon creation using the `enabled` parameter in the decorator:
```python
@mcp.resource("data://secret", enabled=False)
def get_secret_data():
"""This resource is currently disabled."""
return "Secret data"
```
You can also toggle a resource's state programmatically after it has been created:
```python
@mcp.resource("data://config")
def get_config(): return {"version": 1}
# Disable and re-enable the resource
get_config.disable()
get_config.enable()
```
### Accessing MCP Context

View file

@ -169,27 +169,58 @@ def search_products_implementation(query: str, category: str | None = None) -> l
- **`name`**: Sets the explicit tool name exposed via MCP.
- **`description`**: Provides the description exposed via MCP. If set, the function's docstring is ignored for this purpose.
- **`tags`**: A set of strings used to categorize the tool. Clients *might* use tags to filter or group available tools.
- **`tags`**: A set of strings to categorize the tool. Clients *might* use tags to filter or group available tools.
- **`enabled`**: A boolean to enable or disable the tool (defaults to `True`). See [Disabling Tools](#disabling-tools) for more information.
- **`exclude_args`**: A list of argument names to exclude from the tool schema shown to the LLM. See [Excluding Arguments](#excluding-arguments) for more information.
### Excluding Arguments
- **`exclude_args`**:
<VersionBadge version="2.6.0" />
A list of argument names to exclude from the tool schema shown to the LLM. This is useful for arguments that are injected at runtime (such as `state`, `user_id`, or credentials) and should not be exposed to the LLM or client. Only arguments with default values can be excluded; attempting to exclude a required argument will raise an error.
<VersionBadge version="2.6.0" />
Example:
You can exclude certain arguments from the tool schema shown to the LLM. This is useful for arguments that are injected at runtime (such as `state`, `user_id`, or credentials) and should not be exposed to the LLM or client. Only arguments with default values can be excluded; attempting to exclude a required argument will raise an error.
```python
@mcp.tool(
name="get_user_details",
exclude_args=["user_id"]
)
def get_user_details(user_id: str = None) -> str:
# user_id will be injected by the server, not provided by the LLM
...
```
Example:
With this configuration, `user_id` will not appear in the tool's parameter schema, but can still be set by the server or framework at runtime.
```python
@mcp.tool(
name="get_user_details",
exclude_args=["user_id"]
)
def get_user_details(user_id: str = None) -> str:
# user_id will be injected by the server, not provided by the LLM
...
```
With this configuration, `user_id` will not appear in the tool's parameter schema, but can still be set by the server or framework at runtime.
For more complex tool transformations, see [Transforming Tools](/patterns/tool-transformation).
### Disabling Tools
<VersionBadge version="2.8.0" />
You can control the visibility and availability of tools by enabling or disabling them. This is useful for feature flagging, maintenance, or dynamically changing the toolset available to a client. Disabled tools will not appear in the list of available tools returned by `list_tools`, and attempting to call a disabled tool will result in an "Unknown tool" error, just as if the tool did not exist.
By default, all tools are enabled. You can disable a tool upon creation using the `enabled` parameter in the decorator:
```python
@mcp.tool(enabled=False)
def maintenance_tool():
"""This tool is currently under maintenance."""
return "This tool is disabled."
```
You can also toggle a tool's state programmatically after it has been created:
```python
@mcp.tool
def dynamic_tool():
return "I am a dynamic tool."
# Disable and re-enable the tool
dynamic_tool.disable()
dynamic_tool.enable()
```
### Async Tools

View file

@ -4,18 +4,140 @@ sidebarTitle: "Updates"
icon: "sparkles"
tag: "New!"
---
<Update label="FastMCP 2.6" description="June 6, 2025">
<Update label="FastMCP 2.7" description="June 6, 2025" tags={["Releases"]}>
<Card
title="FastMCP 2.7: Pare Programming" href="https://github.com/jlowin/fastmcp/releases/tag/v2.7.0"
img="assets/updates/release-2-7.png"
cta="Read the release notes"
>
FastMCP 2.7 has been released!
Most notably, it introduces the highly requested (and Pythonic) "naked" decorator usage:
```python {3}
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
```
In addition, decorators now return the objects they create, instead of the decorated function. This is an important usability enhancement.
The bulk of the update is focused on improving the FastMCP internals, including a few breaking internal changes to private APIs. A number of functions that have clung on since 1.0 are now deprecated.
</Card>
</Update>
<Update label="FastMCP 2.6" description="June 2, 2025" tags={["Releases", "Blog Posts"]}>
<Card
title="Blast Auth with FastMCP 2.6" href="https://www.jlowin.dev/blog/fastmcp-2-6"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.Bsu8afiw.png&w=1000&h=500&f=webp"
cta="Read more"
arrow="false"
horizontal="true">
cta="Read more"
>
FastMCP 2.6 is here!
This release introduces first-class authentication for MCP servers and clients, including pragmatic Bearer token support and seamless OAuth 2.1 integration. This release aligns with how major AI platforms are adopting MCP today, making it easier than ever to securely connect your tools to real-world AI models. Dive into the update and secure your stack with minimal friction.
</Card>
</Update>
<Update description="May 21, 2025" label="Vibe-Testing" tags={["Blog Posts", "Tutorials"]}>
<Card
title="Stop Vibe-Testing Your MCP Server"
href="https://www.jlowin.dev/blog/stop-vibe-testing-mcp-servers"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.BUPy9I9c.png&w=1000&h=500&f=webp"
cta="Read more"
>
Your tests are bad and you should feel bad.
Stop vibe-testing your MCP server through LLM guesswork. FastMCP 2.0 introduces in-memory testing for fast, deterministic, and fully Pythonic validation of your MCP logic—no network, no subprocesses, no vibes.
</Card>
</Update>
<Update description="May 8, 2025" label="10,000 Stars" tags={["Blog Posts"]}>
<Card
title="Reflecting on FastMCP at 10k stars 🌟"
href="https://www.jlowin.dev/blog/fastmcp-2-10k-stars"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.Cnvci9Q_.png&w=1000&h=500&f=webp"
cta="Read more"
>
In just six weeks since its relaunch, FastMCP has surpassed 10,000 GitHub stars—becoming the fastest-growing OSS project in our orbit. What started as a personal itch has become the backbone of Python-based MCP servers, powering a rapidly expanding ecosystem. While the protocol itself evolves, FastMCP continues to lead with clarity, developer experience, and opinionated tooling. Heres to whats next.
</Card>
</Update>
<Update description="May 8, 2025" label="FastMCP 2.3" tags={["Blog Posts", "Releases"]}>
<Card
title="Now Streaming: FastMCP 2.3"
href="https://www.jlowin.dev/blog/fastmcp-2-3-streamable-http"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.M_hv6gEB.png&w=1000&h=500&f=webp"
cta="Read more"
>
FastMCP 2.3 introduces full support for Streamable HTTP, a modern alternative to SSE that simplifies MCP deployments over the web. Its efficient, reliable, and now the default HTTP transport. Just run your server with transport="streamable-http" and connect clients via a standard URL—FastMCP handles the rest. No special setup required. This release makes deploying MCP servers easier and more portable than ever.
</Card>
</Update>
<Update description="April 23, 2025" label="Proxy Servers" tags={["Blog Posts", "Tutorials"]}>
<Card
title="MCP Proxy Servers with FastMCP 2.0"
href="https://www.jlowin.dev/blog/fastmcp-proxy"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Frobot-hero.DpmAqgui.png&w=1000&h=500&f=webp"
cta="Read more"
>
Even AI needs a good travel adapter 🔌
FastMCP now supports proxying arbitrary MCP servers, letting you run a local FastMCP instance that transparently forwards requests to any remote or third-party server—regardless of transport. This enables transport bridging (e.g., stdio ⇄ SSE), simplified client configuration, and powerful gateway patterns. Proxies are fully composable with other FastMCP servers, letting you mount or import them just like local servers. Use `FastMCP.from_client()` to wrap any backend in a clean, Pythonic proxy.
</Card>
</Update>
<Update label="FastMCP 2.0" description="April 16, 2025" tags={["Releases", "Blog Posts"]}>
<Card
title="Introducing FastMCP 2.0 🚀"
href="https://www.jlowin.dev/blog/fastmcp-2"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.DpbmGNrr.png&w=1000&h=500&f=webp"
cta="Read more"
>
This major release reimagines FastMCP as a full ecosystem platform, with powerful new features for composition, integration, and client interaction. You can now compose local and remote servers, proxy arbitrary MCP servers (with transport translation), and generate MCP servers from OpenAPI or FastAPI apps. A new client infrastructure supports advanced workflows like LLM sampling.
FastMCP 2.0 builds on the success of v1 with a cleaner, more flexible foundation—try it out today!
</Card>
</Update>
<Update label="Official SDK" description="December 3, 2024" tags={["Announcements"]}>
<Card
title="FastMCP is joining the official MCP Python SDK!"
href="https://bsky.app/profile/jlowin.dev/post/3lch4xk5cf22c"
icon="sparkles"
cta="Read the announcement"
>
FastMCP 1.0 will become part of the official MCP Python SDK!
</Card>
</Update>
<Update label="FastMCP 1.0" description="December 1, 2024" tags={["Releases", "Blog Posts"]}>
<Card
title="Introducing FastMCP 🚀"
href="https://www.jlowin.dev/blog/introducing-fastmcp"
img="https://www.jlowin.dev/_image?href=%2F_astro%2Ffastmcp.Bep7YlTw.png&w=1000&h=500&f=webp"
cta="Read more"
>
Because life's too short for boilerplate.
This is where it all started. FastMCPs launch post introduced a clean, Pythonic way to build MCP servers without the protocol overhead. Just write functions; FastMCP handles the rest. What began as a weekend project quickly became the foundation of a growing ecosystem.
</Card>
</Update>

View file

@ -145,6 +145,7 @@ class Client(Generic[ClientTransportT]):
progress_handler: ProgressHandler | None = None,
timeout: datetime.timedelta | float | int | None = None,
init_timeout: datetime.timedelta | float | int | None = None,
client_info: mcp.types.Implementation | None = None,
auth: httpx.Auth | Literal["oauth"] | str | None = None,
):
self.transport = cast(ClientTransportT, infer_transport(transport))
@ -180,6 +181,7 @@ class Client(Generic[ClientTransportT]):
"logging_callback": create_log_callback(log_handler),
"message_handler": message_handler,
"read_timeout_seconds": timeout,
"client_info": client_info,
}
if roots is not None:

View file

@ -8,39 +8,25 @@ import sys
import warnings
from collections.abc import AsyncIterator, Callable
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Literal,
TypedDict,
TypeVar,
cast,
overload,
)
from typing import Any, Literal, TypedDict, TypeVar, cast, overload
import anyio
import httpx
import mcp.types
from mcp import ClientSession, StdioServerParameters
from mcp.client.session import (
ListRootsFnT,
LoggingFnT,
MessageHandlerFnT,
SamplingFnT,
)
from mcp.client.session import ListRootsFnT, LoggingFnT, MessageHandlerFnT, SamplingFnT
from mcp.server.fastmcp import FastMCP as FastMCP1Server
from mcp.shared.memory import create_connected_server_and_client_session
from mcp.shared.memory import create_client_server_memory_streams
from pydantic import AnyUrl
from typing_extensions import Unpack
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.auth.oauth import OAuth
from fastmcp.server.dependencies import get_http_headers
from fastmcp.server.server import FastMCP
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_config import MCPConfig, infer_transport_type_from_url
if TYPE_CHECKING:
from fastmcp.utilities.mcp_config import MCPConfig
logger = get_logger(__name__)
# TypeVar for preserving specific ClientTransport subclass types
@ -64,11 +50,12 @@ __all__ = [
class SessionKwargs(TypedDict, total=False):
"""Keyword arguments for the MCP ClientSession constructor."""
read_timeout_seconds: datetime.timedelta | None
sampling_callback: SamplingFnT | None
list_roots_callback: ListRootsFnT | None
logging_callback: LoggingFnT | None
message_handler: MessageHandlerFnT | None
read_timeout_seconds: datetime.timedelta | None
client_info: mcp.types.Implementation | None
class ClientTransport(abc.ABC):
@ -152,7 +139,7 @@ class WSTransport(ClientTransport):
yield session
def __repr__(self) -> str:
return f"<WebSocket(url='{self.url}')>"
return f"<WebSocketTransport(url='{self.url}')>"
class SSETransport(ClientTransport):
@ -183,8 +170,7 @@ class SSETransport(ClientTransport):
if auth == "oauth":
auth = OAuth(self.url)
elif isinstance(auth, str):
self.headers["Authorization"] = auth
auth = None
auth = BearerAuth(auth)
self.auth = auth
@contextlib.asynccontextmanager
@ -221,7 +207,7 @@ class SSETransport(ClientTransport):
yield session
def __repr__(self) -> str:
return f"<SSE(url='{self.url}')>"
return f"<SSETransport(url='{self.url}')>"
class StreamableHttpTransport(ClientTransport):
@ -252,8 +238,7 @@ class StreamableHttpTransport(ClientTransport):
if auth == "oauth":
auth = OAuth(self.url)
elif isinstance(auth, str):
self.headers["Authorization"] = auth
auth = None
auth = BearerAuth(auth)
self.auth = auth
@contextlib.asynccontextmanager
@ -291,7 +276,7 @@ class StreamableHttpTransport(ClientTransport):
yield session
def __repr__(self) -> str:
return f"<StreamableHttp(url='{self.url}')>"
return f"<StreamableHttpTransport(url='{self.url}')>"
class StdioTransport(ClientTransport):
@ -663,27 +648,49 @@ class FastMCPTransport(ClientTransport):
tests or scenarios where client and server run in the same runtime.
"""
def __init__(self, mcp: FastMCP | FastMCP1Server):
def __init__(self, mcp: FastMCP | FastMCP1Server, raise_exceptions: bool = False):
"""Initialize a FastMCPTransport from a FastMCP server instance."""
# Accept both FastMCP 2.x and FastMCP 1.0 servers. Both expose a
# ``_mcp_server`` attribute pointing to the underlying MCP server
# implementation, so we can treat them identically.
self.server = mcp
self.raise_exceptions = raise_exceptions
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
# create_connected_server_and_client_session manages the session lifecycle itself
async with create_connected_server_and_client_session(
server=self.server._mcp_server,
**session_kwargs,
) as session:
yield session
async with create_client_server_memory_streams() as (
client_streams,
server_streams,
):
client_read, client_write = client_streams
server_read, server_write = server_streams
# Create a cancel scope for the server task
async with anyio.create_task_group() as tg:
tg.start_soon(
lambda: self.server._mcp_server.run(
server_read,
server_write,
self.server._mcp_server.create_initialization_options(),
raise_exceptions=self.raise_exceptions,
)
)
try:
async with ClientSession(
read_stream=client_read,
write_stream=client_write,
**session_kwargs,
) as client_session:
yield client_session
finally:
tg.cancel_scope.cancel()
def __repr__(self) -> str:
return f"<FastMCP(server='{self.server.name}')>"
return f"<FastMCPTransport(server='{self.server.name}')>"
class MCPConfigTransport(ClientTransport):
@ -769,7 +776,7 @@ class MCPConfigTransport(ClientTransport):
yield session
def __repr__(self) -> str:
return f"<MCPConfig(config='{self.config}')>"
return f"<MCPConfigTransport(config='{self.config}')>"
@overload
@ -860,7 +867,6 @@ def infer_transport(
transport = infer_transport(config)
```
"""
from fastmcp.utilities.mcp_config import MCPConfig
# the transport is already a ClientTransport
if isinstance(transport, ClientTransport):

View file

@ -33,3 +33,7 @@ class ClientError(Exception):
class NotFoundError(Exception):
"""Object not found."""
class DisabledError(Exception):
"""Object is disabled."""

View file

@ -5,21 +5,21 @@ from __future__ import annotations as _annotations
import inspect
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable, Sequence
from typing import TYPE_CHECKING, Annotated, Any
from typing import TYPE_CHECKING, Any
import pydantic_core
from mcp.types import EmbeddedResource, ImageContent, PromptMessage, Role, TextContent
from mcp.types import Prompt as MCPPrompt
from mcp.types import PromptArgument as MCPPromptArgument
from pydantic import BeforeValidator, Field, TypeAdapter, validate_call
from pydantic import Field, TypeAdapter, validate_call
from fastmcp.exceptions import PromptError
from fastmcp.server.dependencies import get_context
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
FastMCPBaseModel,
_convert_set_defaults,
find_kwarg_by_type,
get_cached_typeadapter,
)
@ -66,26 +66,13 @@ class PromptArgument(FastMCPBaseModel):
)
class Prompt(FastMCPBaseModel, ABC):
class Prompt(FastMCPComponent, ABC):
"""A prompt template that can be rendered with parameters."""
name: str = Field(description="Name of the prompt")
description: str | None = Field(
default=None, description="Description of what the prompt does"
)
tags: Annotated[set[str], BeforeValidator(_convert_set_defaults)] = Field(
default_factory=set, description="Tags for the prompt"
)
arguments: list[PromptArgument] | None = Field(
default=None, description="Arguments that can be passed to the prompt"
)
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return False
assert isinstance(other, type(self))
return self.model_dump() == other.model_dump()
def to_mcp_prompt(self, **overrides: Any) -> MCPPrompt:
"""Convert the prompt to an MCP prompt."""
arguments = [
@ -109,6 +96,7 @@ class Prompt(FastMCPBaseModel, ABC):
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionPrompt:
"""Create a Prompt from a function.
@ -119,7 +107,7 @@ class Prompt(FastMCPBaseModel, ABC):
- A sequence of any of the above
"""
return FunctionPrompt.from_function(
fn=fn, name=name, description=description, tags=tags
fn=fn, name=name, description=description, tags=tags, enabled=enabled
)
@abstractmethod
@ -143,6 +131,7 @@ class FunctionPrompt(Prompt):
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionPrompt:
"""Create a Prompt from a function.
@ -208,6 +197,7 @@ class FunctionPrompt(Prompt):
description=description,
arguments=arguments,
tags=tags or set(),
enabled=enabled if enabled is not None else True,
fn=fn,
)

View file

@ -41,9 +41,11 @@ class PromptManager:
self.duplicate_behavior = duplicate_behavior
def get_prompt(self, key: str) -> Prompt | None:
def get_prompt(self, key: str) -> Prompt:
"""Get prompt by key."""
return self._prompts.get(key)
if key in self._prompts:
return self._prompts[key]
raise NotFoundError(f"Unknown prompt: {key}")
def get_prompts(self) -> dict[str, Prompt]:
"""Get all registered prompts, indexed by registered key."""

View file

@ -11,18 +11,17 @@ import pydantic_core
from mcp.types import Resource as MCPResource
from pydantic import (
AnyUrl,
BeforeValidator,
ConfigDict,
Field,
UrlConstraints,
ValidationInfo,
field_validator,
model_validator,
)
from typing_extensions import Self
from fastmcp.server.dependencies import get_context
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.types import (
FastMCPBaseModel,
_convert_set_defaults,
find_kwarg_by_type,
)
@ -30,7 +29,7 @@ if TYPE_CHECKING:
pass
class Resource(FastMCPBaseModel, abc.ABC):
class Resource(FastMCPComponent, abc.ABC):
"""Base class for all resources."""
model_config = ConfigDict(validate_default=True)
@ -38,13 +37,7 @@ class Resource(FastMCPBaseModel, abc.ABC):
uri: Annotated[AnyUrl, UrlConstraints(host_required=False)] = Field(
default=..., description="URI of the resource"
)
name: str | None = Field(default=None, description="Name of the resource")
description: str | None = Field(
default=None, description="Description of the resource"
)
tags: Annotated[set[str], BeforeValidator(_convert_set_defaults)] = Field(
default_factory=set, description="Tags for the resource"
)
name: str = Field(default="", description="Name of the resource")
mime_type: str = Field(
default="text/plain",
description="MIME type of the resource content",
@ -59,6 +52,7 @@ class Resource(FastMCPBaseModel, abc.ABC):
description: str | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionResource:
return FunctionResource.from_function(
fn=fn,
@ -67,6 +61,7 @@ class Resource(FastMCPBaseModel, abc.ABC):
description=description,
mime_type=mime_type,
tags=tags,
enabled=enabled,
)
@field_validator("mime_type", mode="before")
@ -77,27 +72,22 @@ class Resource(FastMCPBaseModel, abc.ABC):
return mime_type
return "text/plain"
@field_validator("name", mode="before")
@classmethod
def set_default_name(cls, name: str | None, info: ValidationInfo) -> str:
@model_validator(mode="after")
def set_default_name(self) -> Self:
"""Set default name from URI if not provided."""
if name:
return name
if uri := info.data.get("uri"):
return str(uri)
raise ValueError("Either name or uri must be provided")
if self.name:
pass
elif self.uri:
self.name = str(self.uri)
else:
raise ValueError("Either name or uri must be provided")
return self
@abc.abstractmethod
async def read(self) -> str | bytes:
"""Read the resource content."""
pass
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return False
assert isinstance(other, type(self))
return self.model_dump() == other.model_dump()
def to_mcp_resource(self, **overrides: Any) -> MCPResource:
"""Convert the resource to an MCPResource."""
kwargs = {
@ -108,6 +98,9 @@ class Resource(FastMCPBaseModel, abc.ABC):
}
return MCPResource(**kwargs | overrides)
def __repr__(self) -> str:
return f"{self.__class__.__name__}(uri={self.uri!r}, name={self.name!r}, description={self.description!r}, tags={self.tags})"
class FunctionResource(Resource):
"""A resource that defers data loading by wrapping a function.
@ -133,6 +126,7 @@ class FunctionResource(Resource):
description: str | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionResource:
"""Create a FunctionResource from a function."""
if isinstance(uri, str):
@ -144,6 +138,7 @@ class FunctionResource(Resource):
description=description or fn.__doc__,
mime_type=mime_type or "text/plain",
tags=tags or set(),
enabled=enabled if enabled is not None else True,
)
async def read(self) -> str | bytes:

View file

@ -5,12 +5,11 @@ from __future__ import annotations
import inspect
import re
from collections.abc import Callable
from typing import Annotated, Any
from typing import Any
from urllib.parse import unquote
from mcp.types import ResourceTemplate as MCPResourceTemplate
from pydantic import (
BeforeValidator,
Field,
field_validator,
validate_call,
@ -18,10 +17,9 @@ from pydantic import (
from fastmcp.resources.types import Resource
from fastmcp.server.dependencies import get_context
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.types import (
FastMCPBaseModel,
_convert_set_defaults,
find_kwarg_by_type,
get_cached_typeadapter,
)
@ -51,17 +49,12 @@ def match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None:
return None
class ResourceTemplate(FastMCPBaseModel):
class ResourceTemplate(FastMCPComponent):
"""A template for dynamically creating resources."""
uri_template: str = Field(
description="URI template with parameters (e.g. weather://{city}/current)"
)
name: str = Field(description="Name of the resource")
description: str | None = Field(description="Description of what the resource does")
tags: Annotated[set[str], BeforeValidator(_convert_set_defaults)] = Field(
default_factory=set, description="Tags for the resource"
)
mime_type: str = Field(
default="text/plain", description="MIME type of the resource content"
)
@ -77,6 +70,7 @@ class ResourceTemplate(FastMCPBaseModel):
description: str | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionResourceTemplate:
return FunctionResourceTemplate.from_function(
fn=fn,
@ -85,6 +79,7 @@ class ResourceTemplate(FastMCPBaseModel):
description=description,
mime_type=mime_type,
tags=tags,
enabled=enabled,
)
@field_validator("mime_type", mode="before")
@ -120,14 +115,9 @@ class ResourceTemplate(FastMCPBaseModel):
description=self.description,
mime_type=self.mime_type,
tags=self.tags,
enabled=self.enabled,
)
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return False
assert isinstance(other, type(self))
return self.model_dump() == other.model_dump()
def to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate:
"""Convert the resource template to an MCPResourceTemplate."""
kwargs = {
@ -168,6 +158,7 @@ class FunctionResourceTemplate(ResourceTemplate):
description: str | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionResourceTemplate:
"""Create a template from a function."""
from fastmcp.server.context import Context
@ -250,4 +241,5 @@ class FunctionResourceTemplate(ResourceTemplate):
fn=fn,
parameters=parameters,
tags=tags or set(),
enabled=enabled if enabled is not None else True,
)

View file

@ -1,13 +1,10 @@
from types import EllipsisType
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastmcp.server.auth.providers.bearer import BearerAuthProvider
# Sentinel object to indicate that a setting is not set
class _NotSet:
pass
class EnvBearerAuthProviderSettings(BaseSettings):
"""Settings for the BearerAuthProvider."""
@ -33,11 +30,11 @@ class EnvBearerAuthProvider(BearerAuthProvider):
def __init__(
self,
public_key: str | None | type[_NotSet] = _NotSet,
jwks_uri: str | None | type[_NotSet] = _NotSet,
issuer: str | None | type[_NotSet] = _NotSet,
audience: str | None | type[_NotSet] = _NotSet,
required_scopes: list[str] | None | type[_NotSet] = _NotSet,
public_key: str | None | EllipsisType = ...,
jwks_uri: str | None | EllipsisType = ...,
issuer: str | None | EllipsisType = ...,
audience: str | None | EllipsisType = ...,
required_scopes: list[str] | None | EllipsisType = ...,
):
"""
Initialize the provider.
@ -57,6 +54,6 @@ class EnvBearerAuthProvider(BearerAuthProvider):
"required_scopes": required_scopes,
}
settings = EnvBearerAuthProviderSettings(
**{k: v for k, v in kwargs.items() if v is not _NotSet}
**{k: v for k, v in kwargs.items() if v is not ...}
)
super().__init__(**settings.model_dump())

View file

@ -67,6 +67,7 @@ def get_http_headers(include_all: bool = False) -> dict[str, str]:
"te",
"keep-alive",
"expect",
"accept",
# Proxy-related headers
"proxy-authenticate",
"proxy-authorization",

View file

@ -13,6 +13,7 @@ from mcp.server.auth.middleware.bearer_auth import (
from mcp.server.auth.routes import create_auth_routes
from mcp.server.lowlevel.server import LifespanResultT
from mcp.server.sse import SseServerTransport
from mcp.server.streamable_http import EventStore
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.applications import Starlette
from starlette.middleware import Middleware
@ -241,7 +242,7 @@ def create_sse_app(
def create_streamable_http_app(
server: FastMCP[LifespanResultT],
streamable_http_path: str,
event_store: None = None,
event_store: EventStore | None = None,
auth: OAuthProvider | None = None,
json_response: bool = False,
stateless_http: bool = False,

View file

@ -226,7 +226,6 @@ class OpenAPITool(Tool):
tags: set[str] = set(),
timeout: float | None = None,
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
serializer: Callable[[Any], str] | None = None,
):
super().__init__(
@ -235,7 +234,6 @@ class OpenAPITool(Tool):
parameters=parameters,
tags=tags,
annotations=annotations,
exclude_args=exclude_args,
serializer=serializer,
)
self._client = client

View file

@ -186,8 +186,10 @@ class FastMCPProxy(FastMCP):
else:
raise e
for tool in client_tools:
tool_proxy = await ProxyTool.from_client(self.client, tool)
tools[tool_proxy.name] = tool_proxy
# 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
@ -203,8 +205,12 @@ class FastMCPProxy(FastMCP):
else:
raise e
for resource in client_resources:
resource_proxy = await ProxyResource.from_client(self.client, resource)
resources[str(resource_proxy.uri)] = resource_proxy
# 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
@ -220,8 +226,12 @@ class FastMCPProxy(FastMCP):
else:
raise e
for template in client_templates:
template_proxy = await ProxyTemplate.from_client(self.client, template)
templates[template_proxy.uri_template] = template_proxy
# 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
@ -237,24 +247,27 @@ class FastMCPProxy(FastMCP):
else:
raise e
for prompt in client_prompts:
prompt_proxy = await ProxyPrompt.from_client(self.client, prompt)
prompts[prompt_proxy.name] = prompt_proxy
# 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 _mcp_call_tool(
async def _call_tool(
self, key: str, arguments: dict[str, Any]
) -> list[TextContent | ImageContent | EmbeddedResource]:
try:
result = await super()._mcp_call_tool(key, arguments)
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 _mcp_read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
async def _read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
try:
result = await super()._mcp_read_resource(uri)
result = await super()._read_resource(uri)
return result
except NotFoundError:
async with self.client:
@ -270,11 +283,11 @@ class FastMCPProxy(FastMCP):
ReadResourceContents(content=content, mime_type=resource[0].mimeType)
]
async def _mcp_get_prompt(
async def _get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
try:
result = await super()._mcp_get_prompt(name, arguments)
result = await super()._get_prompt(name, arguments)
return result
except NotFoundError:
async with self.client:

View file

@ -43,7 +43,8 @@ from starlette.routing import BaseRoute, Route
import fastmcp
import fastmcp.server
from fastmcp.exceptions import NotFoundError
import fastmcp.settings
from fastmcp.exceptions import DisabledError, NotFoundError
from fastmcp.prompts import Prompt, PromptManager
from fastmcp.prompts.prompt import FunctionPrompt
from fastmcp.resources import Resource, ResourceManager
@ -319,6 +320,12 @@ class FastMCP(Generic[LifespanResultT]):
self._cache.set("tools", tools)
return tools
async def get_tool(self, key: str) -> Tool:
tools = await self.get_tools()
if key not in tools:
raise NotFoundError(f"Unknown tool: {key}")
return tools[key]
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:
@ -336,6 +343,12 @@ class FastMCP(Generic[LifespanResultT]):
self._cache.set("resources", resources)
return resources
async def get_resource(self, key: str) -> Resource:
resources = await self.get_resources()
if key not in resources:
raise NotFoundError(f"Unknown resource: {key}")
return resources[key]
async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
"""Get all registered resource templates, indexed by registered key."""
if (
@ -356,6 +369,12 @@ class FastMCP(Generic[LifespanResultT]):
self._cache.set("resource_templates", templates)
return templates
async def get_resource_template(self, key: str) -> ResourceTemplate:
templates = await self.get_resource_templates()
if key not in templates:
raise NotFoundError(f"Unknown resource template: {key}")
return templates[key]
async def get_prompts(self) -> dict[str, Prompt]:
"""
List all available prompts.
@ -375,6 +394,12 @@ class FastMCP(Generic[LifespanResultT]):
self._cache.set("prompts", prompts)
return prompts
async def get_prompt(self, key: str) -> Prompt:
prompts = await self.get_prompts()
if key not in prompts:
raise NotFoundError(f"Unknown prompt: {key}")
return prompts[key]
def custom_route(
self,
path: str,
@ -426,7 +451,9 @@ class FastMCP(Generic[LifespanResultT]):
"""
tools = await self.get_tools()
return [tool.to_mcp_tool(name=key) for key, tool in tools.items()]
return [
tool.to_mcp_tool(name=key) for key, tool in tools.items() if tool.enabled
]
async def _mcp_list_resources(self) -> list[MCPResource]:
"""
@ -436,7 +463,9 @@ class FastMCP(Generic[LifespanResultT]):
"""
resources = await self.get_resources()
return [
resource.to_mcp_resource(uri=key) for key, resource in resources.items()
resource.to_mcp_resource(uri=key)
for key, resource in resources.items()
if resource.enabled
]
async def _mcp_list_resource_templates(self) -> list[MCPResourceTemplate]:
@ -449,6 +478,7 @@ class FastMCP(Generic[LifespanResultT]):
return [
template.to_mcp_template(uriTemplate=key)
for key, template in templates.items()
if template.enabled
]
async def _mcp_list_prompts(self) -> list[MCPPrompt]:
@ -458,12 +488,19 @@ class FastMCP(Generic[LifespanResultT]):
"""
prompts = await self.get_prompts()
return [prompt.to_mcp_prompt(name=key) for key, prompt in prompts.items()]
return [
prompt.to_mcp_prompt(name=key)
for key, prompt in prompts.items()
if prompt.enabled
]
async def _mcp_call_tool(
self, key: str, arguments: dict[str, Any]
) -> list[TextContent | ImageContent | EmbeddedResource]:
"""Handle MCP 'callTool' requests.
"""
Handle MCP 'callTool' requests.
Delegates to _call_tool, which should be overridden by FastMCP subclasses.
Args:
key: The name of the tool to call
@ -476,43 +513,109 @@ class FastMCP(Generic[LifespanResultT]):
# Create and use context for the entire call
with fastmcp.server.context.Context(fastmcp=self):
# Get tool, checking first from our tools, then from the mounted servers
if self._tool_manager.has_tool(key):
return await self._tool_manager.call_tool(key, arguments)
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}")
# Check mounted servers to see if they have the tool
for server in self._mounted_servers.values():
if server.match_tool(key):
tool_key = server.strip_tool_prefix(key)
return await server.server._mcp_call_tool(tool_key, arguments)
async def _call_tool(
self, key: str, arguments: dict[str, Any]
) -> list[TextContent | ImageContent | EmbeddedResource]:
"""
Call a tool with raw MCP arguments. FastMCP subclasses should override
this method, not _mcp_call_tool.
raise NotFoundError(f"Unknown tool: {key}")
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
"""
# 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)
if not tool.enabled:
raise DisabledError(f"Tool {key!r} is disabled")
return await self._tool_manager.call_tool(key, arguments)
# Check mounted servers to see if they have the tool
for server in self._mounted_servers.values():
if server.match_tool(key):
tool_key = server.strip_tool_prefix(key)
return await server.server._call_tool(tool_key, arguments)
raise NotFoundError(f"Unknown tool: {key!r}")
async def _mcp_read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
"""
Handle MCP 'readResource' requests.
Delegates to _read_resource, which should be overridden by FastMCP subclasses.
"""
logger.debug("Read resource: %s", uri)
with fastmcp.server.context.Context(fastmcp=self):
try:
return await self._read_resource(uri)
except DisabledError:
# convert to NotFoundError to avoid leaking resource presence
raise NotFoundError(f"Unknown resource: {str(uri)!r}")
except NotFoundError:
# standardize NotFound message
raise NotFoundError(f"Unknown resource: {str(uri)!r}")
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.
"""
with fastmcp.server.context.Context(fastmcp=self):
if self._resource_manager.has_resource(uri):
resource = await self._resource_manager.get_resource(uri)
content = await self._resource_manager.read_resource(uri)
return [
ReadResourceContents(
content=content,
mime_type=resource.mime_type,
)
]
if self._resource_manager.has_resource(uri):
resource = await self._resource_manager.get_resource(uri)
if not resource.enabled:
raise DisabledError(f"Resource {str(uri)!r} is disabled")
content = await self._resource_manager.read_resource(uri)
return [
ReadResourceContents(
content=content,
mime_type=resource.mime_type,
)
]
else:
for server in self._mounted_servers.values():
if server.match_resource(str(uri)):
new_uri = server.strip_resource_prefix(str(uri))
return await server.server._mcp_read_resource(new_uri)
else:
for server in self._mounted_servers.values():
if server.match_resource(str(uri)):
new_uri = server.strip_resource_prefix(str(uri))
return await server.server._mcp_read_resource(new_uri)
else:
raise NotFoundError(f"Unknown resource: {uri}")
raise NotFoundError(f"Unknown resource: {uri}")
async def _mcp_get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
"""
Handle MCP 'getPrompt' requests.
Delegates to _get_prompt, which should be overridden by FastMCP subclasses.
"""
logger.debug("Get prompt: %s with %s", name, arguments)
with fastmcp.server.context.Context(fastmcp=self):
try:
return await self._get_prompt(name, arguments)
except DisabledError:
# convert to NotFoundError to avoid leaking prompt presence
raise NotFoundError(f"Unknown prompt: {name}")
except NotFoundError:
# standardize NotFound message
raise NotFoundError(f"Unknown prompt: {name}")
async def _get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
"""Handle MCP 'getPrompt' requests.
@ -525,19 +628,20 @@ class FastMCP(Generic[LifespanResultT]):
"""
logger.debug("Get prompt: %s with %s", name, arguments)
# Create and use context for the entire call
with fastmcp.server.context.Context(fastmcp=self):
# Get prompt, checking first from our prompts, then from the mounted servers
if self._prompt_manager.has_prompt(name):
return await self._prompt_manager.render_prompt(name, arguments)
# 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)
if not prompt.enabled:
raise DisabledError(f"Prompt {name!r} is disabled")
return await self._prompt_manager.render_prompt(name, arguments)
# Check mounted servers to see if they have the prompt
for server in self._mounted_servers.values():
if server.match_prompt(name):
prompt_name = server.strip_prompt_prefix(name)
return await server.server._mcp_get_prompt(prompt_name, arguments)
# Check mounted servers to see if they have the prompt
for server in self._mounted_servers.values():
if server.match_prompt(name):
prompt_name = server.strip_prompt_prefix(name)
return await server.server._mcp_get_prompt(prompt_name, arguments)
raise NotFoundError(f"Unknown prompt: {name}")
raise NotFoundError(f"Unknown prompt: {name}")
def add_tool(self, tool: Tool) -> None:
"""Add a tool to the server.
@ -573,6 +677,7 @@ class FastMCP(Generic[LifespanResultT]):
tags: set[str] | None = None,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
enabled: bool | None = None,
) -> FunctionTool: ...
@overload
@ -585,6 +690,7 @@ class FastMCP(Generic[LifespanResultT]):
tags: set[str] | None = None,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
enabled: bool | None = None,
) -> Callable[[AnyFunction], FunctionTool]: ...
def tool(
@ -596,6 +702,7 @@ class FastMCP(Generic[LifespanResultT]):
tags: set[str] | None = None,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
enabled: bool | None = None,
) -> Callable[[AnyFunction], FunctionTool] | FunctionTool:
"""Decorator to register a tool.
@ -612,11 +719,12 @@ class FastMCP(Generic[LifespanResultT]):
Args:
name_or_fn: Either a function (when used as @tool), a string name, or None
name: Optional name for the tool (keyword-only, alternative to name_or_fn)
description: Optional description of what the tool does
tags: Optional set of tags for categorizing the tool
annotations: Optional annotations about the tool's behavior
annotations: Optional annotations about the tool's behavior (e.g. {"is_async": True})
exclude_args: Optional list of argument names to exclude from the tool schema
name: Optional name for the tool (keyword-only, alternative to name_or_fn)
enabled: Optional boolean to enable or disable the tool
Example:
@server.tool
@ -669,6 +777,7 @@ class FastMCP(Generic[LifespanResultT]):
annotations=annotations,
exclude_args=exclude_args,
serializer=self._tool_serializer,
enabled=enabled,
)
self.add_tool(tool)
return tool
@ -697,6 +806,7 @@ class FastMCP(Generic[LifespanResultT]):
tags=tags,
annotations=annotations,
exclude_args=exclude_args,
enabled=enabled,
)
def add_resource(self, resource: Resource, key: str | None = None) -> None:
@ -763,6 +873,7 @@ class FastMCP(Generic[LifespanResultT]):
description: str | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> Callable[[AnyFunction], Resource | ResourceTemplate]:
"""Decorator to register a function as a resource.
@ -785,6 +896,7 @@ class FastMCP(Generic[LifespanResultT]):
description: Optional description of the resource
mime_type: Optional MIME type for the resource
tags: Optional set of tags for categorizing the resource
enabled: Optional boolean to enable or disable the resource
Example:
@server.resource("resource://my-resource")
@ -849,6 +961,7 @@ class FastMCP(Generic[LifespanResultT]):
description=description,
mime_type=mime_type,
tags=tags,
enabled=enabled,
)
self.add_template(template)
return template
@ -860,6 +973,7 @@ class FastMCP(Generic[LifespanResultT]):
description=description,
mime_type=mime_type,
tags=tags,
enabled=enabled,
)
self.add_resource(resource)
return resource
@ -888,6 +1002,7 @@ class FastMCP(Generic[LifespanResultT]):
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> FunctionPrompt: ...
@overload
@ -898,6 +1013,7 @@ class FastMCP(Generic[LifespanResultT]):
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> Callable[[AnyFunction], FunctionPrompt]: ...
def prompt(
@ -907,6 +1023,7 @@ class FastMCP(Generic[LifespanResultT]):
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
enabled: bool | None = None,
) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt:
"""Decorator to register a prompt.
@ -916,16 +1033,17 @@ class FastMCP(Generic[LifespanResultT]):
This decorator supports multiple calling patterns:
- @server.prompt (without parentheses)
- @server.prompt (with empty parentheses)
- @server.prompt() (with empty parentheses)
- @server.prompt("custom_name") (with name as first argument)
- @server.prompt(name="custom_name") (with name as keyword argument)
- server.prompt(function, name="custom_name") (direct function call)
Args:
name_or_fn: Either a function (when used as @prompt), a string name, or None
name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
description: Optional description of what the prompt does
tags: Optional set of tags for categorizing the prompt
name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
enabled: Optional boolean to enable or disable the prompt
Example:
@server.prompt
@ -938,7 +1056,7 @@ class FastMCP(Generic[LifespanResultT]):
}
]
@server.prompt
@server.prompt()
def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
ctx.info(f"Analyzing table {table_name}")
schema = read_table_schema(table_name)
@ -998,6 +1116,7 @@ class FastMCP(Generic[LifespanResultT]):
name=prompt_name,
description=description,
tags=tags,
enabled=enabled,
)
self.add_prompt(prompt)
@ -1025,6 +1144,7 @@ class FastMCP(Generic[LifespanResultT]):
name=prompt_name,
description=description,
tags=tags,
enabled=enabled,
)
async def run_stdio_async(self) -> None:

View file

@ -1,4 +1,5 @@
from .tool import Tool, FunctionTool
from .tool_manager import ToolManager
from .tool_transform import forward, forward_raw
__all__ = ["Tool", "ToolManager", "FunctionTool"]
__all__ = ["Tool", "ToolManager", "FunctionTool", "forward", "forward_raw"]

View file

@ -4,27 +4,27 @@ import inspect
import json
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import TYPE_CHECKING, Annotated, Any
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import pydantic_core
from mcp.types import EmbeddedResource, ImageContent, TextContent, ToolAnnotations
from mcp.types import Tool as MCPTool
from pydantic import BeforeValidator, Field
from pydantic import Field
import fastmcp
from fastmcp.server.dependencies import get_context
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
FastMCPBaseModel,
Image,
_convert_set_defaults,
find_kwarg_by_type,
get_cached_typeadapter,
)
if TYPE_CHECKING:
pass
from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
logger = get_logger(__name__)
@ -33,24 +33,13 @@ def default_serializer(data: Any) -> str:
return pydantic_core.to_json(data, fallback=str, indent=2).decode()
class Tool(FastMCPBaseModel, ABC):
class Tool(FastMCPComponent, ABC):
"""Internal tool registration info."""
name: str = Field(description="Name of the tool")
description: str | None = Field(
default=None, description="Description of what the tool does"
)
parameters: dict[str, Any] = Field(description="JSON schema for tool parameters")
tags: Annotated[set[str], BeforeValidator(_convert_set_defaults)] = Field(
default_factory=set, description="Tags for the tool"
)
annotations: ToolAnnotations | None = Field(
default=None, description="Additional annotations about the tool"
)
exclude_args: list[str] | None = Field(
default=None,
description="Arguments to exclude from the tool schema, such as State, Memory, or Credential",
)
serializer: Callable[[Any], str] | None = Field(
default=None, description="Optional custom serializer for tool results"
)
@ -73,6 +62,7 @@ class Tool(FastMCPBaseModel, ABC):
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
serializer: Callable[[Any], str] | None = None,
enabled: bool | None = None,
) -> FunctionTool:
"""Create a Tool from a function."""
return FunctionTool.from_function(
@ -83,14 +73,9 @@ class Tool(FastMCPBaseModel, ABC):
annotations=annotations,
exclude_args=exclude_args,
serializer=serializer,
enabled=enabled,
)
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return False
assert isinstance(other, type(self))
return self.model_dump() == other.model_dump()
@abstractmethod
async def run(
self, arguments: dict[str, Any]
@ -98,6 +83,33 @@ class Tool(FastMCPBaseModel, ABC):
"""Run the tool with arguments."""
raise NotImplementedError("Subclasses must implement run()")
@classmethod
def from_tool(
cls,
tool: Tool,
transform_fn: Callable[..., Any] | None = None,
name: str | None = None,
transform_args: dict[str, ArgTransform] | None = None,
description: str | None = None,
tags: set[str] | None = None,
annotations: ToolAnnotations | None = None,
serializer: Callable[[Any], str] | None = None,
enabled: bool | None = None,
) -> TransformedTool:
from fastmcp.tools.tool_transform import TransformedTool
return TransformedTool.from_tool(
tool=tool,
transform_fn=transform_fn,
name=name,
transform_args=transform_args,
description=description,
tags=tags,
annotations=annotations,
serializer=serializer,
enabled=enabled,
)
class FunctionTool(Tool):
fn: Callable[..., Any]
@ -112,65 +124,24 @@ class FunctionTool(Tool):
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
serializer: Callable[[Any], str] | None = None,
enabled: bool | None = None,
) -> FunctionTool:
"""Create a Tool from a function."""
from fastmcp.server.context import Context
# Reject functions with *args or **kwargs
sig = inspect.signature(fn)
for param in sig.parameters.values():
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise ValueError("Functions with *args are not supported as tools")
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise ValueError("Functions with **kwargs are not supported as tools")
parsed_fn = ParsedFunction.from_function(fn, exclude_args=exclude_args)
if exclude_args:
for arg_name in exclude_args:
if arg_name not in sig.parameters:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args does not exist in function."
)
param = sig.parameters[arg_name]
if param.default == inspect.Parameter.empty:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args must have a default value."
)
func_name = name or getattr(fn, "__name__", None) or fn.__class__.__name__
if func_name == "<lambda>":
if name is None and parsed_fn.name == "<lambda>":
raise ValueError("You must provide a name for lambda functions")
func_doc = description or fn.__doc__
# if the fn is a callable class, we need to get the __call__ method from here out
if not inspect.isroutine(fn):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
fn = fn.__func__
type_adapter = get_cached_typeadapter(fn)
schema = type_adapter.json_schema()
prune_params: list[str] = []
context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)
if context_kwarg:
prune_params.append(context_kwarg)
if exclude_args:
prune_params.extend(exclude_args)
schema = compress_schema(schema, prune_params=prune_params)
return cls(
fn=fn,
name=func_name,
description=func_doc,
parameters=schema,
fn=parsed_fn.fn,
name=name or parsed_fn.name,
description=description or parsed_fn.description,
parameters=parsed_fn.parameters,
tags=tags or set(),
annotations=annotations,
exclude_args=exclude_args,
serializer=serializer,
enabled=enabled if enabled is not None else True,
)
async def run(
@ -222,6 +193,76 @@ class FunctionTool(Tool):
return _convert_to_content(result, serializer=self.serializer)
@dataclass
class ParsedFunction:
fn: Callable[..., Any]
name: str
description: str | None
parameters: dict[str, Any]
@classmethod
def from_function(
cls,
fn: Callable[..., Any],
exclude_args: list[str] | None = None,
validate: bool = True,
) -> ParsedFunction:
from fastmcp.server.context import Context
if validate:
sig = inspect.signature(fn)
# Reject functions with *args or **kwargs
for param in sig.parameters.values():
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise ValueError("Functions with *args are not supported as tools")
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise ValueError(
"Functions with **kwargs are not supported as tools"
)
# Reject exclude_args that don't exist in the function or don't have a default value
if exclude_args:
for arg_name in exclude_args:
if arg_name not in sig.parameters:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args does not exist in function."
)
param = sig.parameters[arg_name]
if param.default == inspect.Parameter.empty:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args must have a default value."
)
# collect name and doc before we potentially modify the function
fn_name = getattr(fn, "__name__", None) or fn.__class__.__name__
fn_doc = fn.__doc__
# if the fn is a callable class, we need to get the __call__ method from here out
if not inspect.isroutine(fn):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
fn = fn.__func__
type_adapter = get_cached_typeadapter(fn)
schema = type_adapter.json_schema()
prune_params: list[str] = []
context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)
if context_kwarg:
prune_params.append(context_kwarg)
if exclude_args:
prune_params.extend(exclude_args)
schema = compress_schema(schema, prune_params=prune_params)
return cls(
fn=fn,
name=fn_name,
description=fn_doc,
parameters=schema,
)
def _convert_to_content(
result: Any,
serializer: Callable[[Any], str] | None = None,

View file

@ -0,0 +1,665 @@
from __future__ import annotations
import inspect
from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass
from types import EllipsisType
from typing import Any, Literal
from mcp.types import EmbeddedResource, ImageContent, TextContent, ToolAnnotations
from pydantic import ConfigDict
from fastmcp.tools.tool import ParsedFunction, Tool
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import get_cached_typeadapter
logger = get_logger(__name__)
NotSet = ...
# Context variable to store current transformed tool
_current_tool: ContextVar[TransformedTool | None] = ContextVar(
"_current_tool", default=None
)
async def forward(**kwargs) -> Any:
"""Forward to parent tool with argument transformation applied.
This function can only be called from within a transformed tool's custom
function. It applies argument transformation (renaming, validation) before
calling the parent tool.
For example, if the parent tool has args `x` and `y`, but the transformed
tool has args `a` and `b`, and an `transform_args` was provided that maps `x` to
`a` and `y` to `b`, then `forward(a=1, b=2)` will call the parent tool with
`x=1` and `y=2`.
Args:
**kwargs: Arguments to forward to the parent tool (using transformed names).
Returns:
The result from the parent tool execution.
Raises:
RuntimeError: If called outside a transformed tool context.
TypeError: If provided arguments don't match the transformed schema.
"""
tool = _current_tool.get()
if tool is None:
raise RuntimeError("forward() can only be called within a transformed tool")
# Use the forwarding function that handles mapping
return await tool.forwarding_fn(**kwargs)
async def forward_raw(**kwargs) -> Any:
"""Forward directly to parent tool without transformation.
This function bypasses all argument transformation and validation, calling the parent
tool directly with the provided arguments. Use this when you need to call the parent
with its original parameter names and structure.
For example, if the parent tool has args `x` and `y`, then `forward_raw(x=1,
y=2)` will call the parent tool with `x=1` and `y=2`.
Args:
**kwargs: Arguments to pass directly to the parent tool (using original names).
Returns:
The result from the parent tool execution.
Raises:
RuntimeError: If called outside a transformed tool context.
"""
tool = _current_tool.get()
if tool is None:
raise RuntimeError("forward_raw() can only be called within a transformed tool")
return await tool.parent_tool.run(kwargs)
@dataclass(kw_only=True)
class ArgTransform:
"""Configuration for transforming a parent tool's argument.
This class allows fine-grained control over how individual arguments are transformed
when creating a new tool from an existing one. You can rename arguments, change their
descriptions, add default values, or hide them from clients while passing constants.
Attributes:
name: New name for the argument. Use None to keep original name, or ... for no change.
description: New description for the argument. Use None to remove description, or ... for no change.
default: New default value for the argument. Use ... for no change.
default_factory: Callable that returns a default value. Cannot be used with default.
type: New type for the argument. Use ... for no change.
hide: If True, hide this argument from clients but pass a constant value to parent.
required: If True, make argument required (remove default). Use ... for no change.
Examples:
# Rename argument 'old_name' to 'new_name'
ArgTransform(name="new_name")
# Change description only
ArgTransform(description="Updated description")
# Add a default value (makes argument optional)
ArgTransform(default=42)
# Add a default factory (makes argument optional)
ArgTransform(default_factory=lambda: time.time())
# Change the type
ArgTransform(type=str)
# Hide the argument entirely from clients
ArgTransform(hide=True)
# Hide argument but pass a constant value to parent
ArgTransform(hide=True, default="constant_value")
# Hide argument but pass a factory-generated value to parent
ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex)
# Make an optional parameter required (removes any default)
ArgTransform(required=True)
# Combine multiple transformations
ArgTransform(name="new_name", description="New desc", default=None, type=int)
"""
name: str | EllipsisType = NotSet
description: str | EllipsisType = NotSet
default: Any | EllipsisType = NotSet
default_factory: Callable[[], Any] | EllipsisType = NotSet
type: Any | EllipsisType = NotSet
hide: bool = False
required: Literal[True] | EllipsisType = NotSet
def __post_init__(self):
"""Validate that only one of default or default_factory is provided."""
has_default = self.default is not NotSet
has_factory = self.default_factory is not NotSet
if has_default and has_factory:
raise ValueError(
"Cannot specify both 'default' and 'default_factory' in ArgTransform. "
"Use either 'default' for a static value or 'default_factory' for a callable."
)
if has_factory and not self.hide:
raise ValueError(
"default_factory can only be used with hide=True. "
"Visible parameters must use static 'default' values since JSON schema "
"cannot represent dynamic factories."
)
if self.required is True and (has_default or has_factory):
raise ValueError(
"Cannot specify 'required=True' with 'default' or 'default_factory'. "
"Required parameters cannot have defaults."
)
if self.hide and self.required is True:
raise ValueError(
"Cannot specify both 'hide=True' and 'required=True'. "
"Hidden parameters cannot be required since clients cannot provide them."
)
if self.required is False:
raise ValueError(
"Cannot specify 'required=False'. Set a default value instead."
)
class TransformedTool(Tool):
"""A tool that is transformed from another tool.
This class represents a tool that has been created by transforming another tool.
It supports argument renaming, schema modification, custom function injection,
and provides context for the forward() and forward_raw() functions.
The transformation can be purely schema-based (argument renaming, dropping, etc.)
or can include a custom function that uses forward() to call the parent tool
with transformed arguments.
Attributes:
parent_tool: The original tool that this tool was transformed from.
fn: The function to execute when this tool is called (either the forwarding
function for pure transformations or a custom user function).
forwarding_fn: Internal function that handles argument transformation and
validation when forward() is called from custom functions.
"""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
parent_tool: Tool
fn: Callable[..., Any]
forwarding_fn: Callable[..., Any] # Always present, handles arg transformation
transform_args: dict[str, ArgTransform]
async def run(
self, arguments: dict[str, Any]
) -> list[TextContent | ImageContent | EmbeddedResource]:
"""Run the tool with context set for forward() functions.
This method executes the tool's function while setting up the context
that allows forward() and forward_raw() to work correctly within custom
functions.
Args:
arguments: Dictionary of arguments to pass to the tool's function.
Returns:
List of content objects (text, image, or embedded resources) representing
the tool's output.
"""
from fastmcp.tools.tool import _convert_to_content
# Fill in missing arguments with schema defaults to ensure
# ArgTransform defaults take precedence over function defaults
arguments = arguments.copy()
properties = self.parameters.get("properties", {})
for param_name, param_schema in properties.items():
if param_name not in arguments and "default" in param_schema:
# Check if this parameter has a default_factory from transform_args
# We need to call the factory for each run, not use the cached schema value
has_factory_default = False
if self.transform_args:
# Find the original parameter name that maps to this param_name
for orig_name, transform in self.transform_args.items():
transform_name = (
transform.name
if transform.name is not NotSet
else orig_name
)
if (
transform_name == param_name
and transform.default_factory is not NotSet
):
# Type check to ensure default_factory is callable
if callable(transform.default_factory):
arguments[param_name] = transform.default_factory()
has_factory_default = True
break
if not has_factory_default:
arguments[param_name] = param_schema["default"]
token = _current_tool.set(self)
try:
result = await self.fn(**arguments)
return _convert_to_content(result, serializer=self.serializer)
finally:
_current_tool.reset(token)
@classmethod
def from_tool(
cls,
tool: Tool,
name: str | None = None,
description: str | None = None,
tags: set[str] | None = None,
transform_fn: Callable[..., Any] | None = None,
transform_args: dict[str, ArgTransform] | None = None,
annotations: ToolAnnotations | None = None,
serializer: Callable[[Any], str] | None = None,
enabled: bool | None = None,
) -> TransformedTool:
"""Create a transformed tool from a parent tool.
Args:
tool: The parent tool to transform.
transform_fn: Optional custom function. Can use forward() and forward_raw()
to call the parent tool. Functions with **kwargs receive transformed
argument names.
name: New name for the tool. Defaults to parent tool's name.
transform_args: Optional transformations for parent tool arguments.
Only specified arguments are transformed, others pass through unchanged:
- str: Simple rename
- ArgTransform: Complex transformation (rename/description/default/drop)
- None: Drop the argument
description: New description. Defaults to parent's description.
tags: New tags. Defaults to parent's tags.
annotations: New annotations. Defaults to parent's annotations.
serializer: New serializer. Defaults to parent's serializer.
Returns:
TransformedTool with the specified transformations.
Examples:
# Transform specific arguments only
Tool.from_tool(parent, transform_args={"old": "new"}) # Others unchanged
# Custom function with partial transforms
async def custom(x: int, y: int) -> str:
result = await forward(x=x, y=y)
return f"Custom: {result}"
Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"})
# Using **kwargs (gets all args, transformed and untransformed)
async def flexible(**kwargs) -> str:
result = await forward(**kwargs)
return f"Got: {kwargs}"
Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})
"""
transform_args = transform_args or {}
# Validate transform_args
parent_params = set(tool.parameters.get("properties", {}).keys())
unknown_args = set(transform_args.keys()) - parent_params
if unknown_args:
raise ValueError(
f"Unknown arguments in transform_args: {', '.join(sorted(unknown_args))}. "
f"Parent tool has: {', '.join(sorted(parent_params))}"
)
# Always create the forwarding transform
schema, forwarding_fn = cls._create_forwarding_transform(tool, transform_args)
if transform_fn is None:
# User wants pure transformation - use forwarding_fn as the main function
final_fn = forwarding_fn
final_schema = schema
else:
# User provided custom function - merge schemas
parsed_fn = ParsedFunction.from_function(transform_fn, validate=False)
final_fn = transform_fn
has_kwargs = cls._function_has_kwargs(transform_fn)
# Validate function parameters against transformed schema
fn_params = set(parsed_fn.parameters.get("properties", {}).keys())
transformed_params = set(schema.get("properties", {}).keys())
if not has_kwargs:
# Without **kwargs, function must declare all transformed params
# Check if function is missing any parameters required after transformation
missing_params = transformed_params - fn_params
if missing_params:
raise ValueError(
f"Function missing parameters required after transformation: "
f"{', '.join(sorted(missing_params))}. "
f"Function declares: {', '.join(sorted(fn_params))}"
)
# ArgTransform takes precedence over function signature
# Start with function schema as base, then override with transformed schema
final_schema = cls._merge_schema_with_precedence(
parsed_fn.parameters, schema
)
else:
# With **kwargs, function can access all transformed params
# ArgTransform takes precedence over function signature
# No validation needed - kwargs makes everything accessible
# Start with function schema as base, then override with transformed schema
final_schema = cls._merge_schema_with_precedence(
parsed_fn.parameters, schema
)
# Additional validation: check for naming conflicts after transformation
if transform_args:
new_names = []
for old_name, transform in transform_args.items():
if not transform.hide:
if transform.name is not NotSet:
new_names.append(transform.name)
else:
new_names.append(old_name)
# Check for duplicate names after transformation
name_counts = {}
for arg_name in new_names:
name_counts[arg_name] = name_counts.get(arg_name, 0) + 1
duplicates = [
arg_name for arg_name, count in name_counts.items() if count > 1
]
if duplicates:
raise ValueError(
f"Multiple arguments would be mapped to the same names: "
f"{', '.join(sorted(duplicates))}"
)
final_description = description if description is not None else tool.description
transformed_tool = cls(
fn=final_fn,
forwarding_fn=forwarding_fn,
parent_tool=tool,
name=name or tool.name,
description=final_description,
parameters=final_schema,
tags=tags or tool.tags,
annotations=annotations or tool.annotations,
serializer=serializer or tool.serializer,
transform_args=transform_args,
enabled=enabled if enabled is not None else True,
)
return transformed_tool
@classmethod
def _create_forwarding_transform(
cls,
parent_tool: Tool,
transform_args: dict[str, ArgTransform] | None,
) -> tuple[dict[str, Any], Callable[..., Any]]:
"""Create schema and forwarding function that encapsulates all transformation logic.
This method builds a new JSON schema for the transformed tool and creates a
forwarding function that validates arguments against the new schema and maps
them back to the parent tool's expected arguments.
Args:
parent_tool: The original tool to transform.
transform_args: Dictionary defining how to transform each argument.
Returns:
A tuple containing:
- dict: The new JSON schema for the transformed tool
- Callable: Async function that validates and forwards calls to the parent tool
"""
# Build transformed schema and mapping
parent_props = parent_tool.parameters.get("properties", {}).copy()
parent_required = set(parent_tool.parameters.get("required", []))
new_props = {}
new_required = set()
new_to_old = {}
hidden_defaults = {} # Track hidden parameters with constant values
for old_name, old_schema in parent_props.items():
# Check if parameter is in transform_args
if transform_args and old_name in transform_args:
transform = transform_args[old_name]
else:
# Default behavior - pass through (no transformation)
transform = ArgTransform() # Default ArgTransform with no changes
# Handle hidden parameters with defaults
if transform.hide:
# Validate that hidden parameters without user defaults have parent defaults
has_user_default = (
transform.default is not NotSet
or transform.default_factory is not NotSet
)
if not has_user_default and old_name in parent_required:
raise ValueError(
f"Hidden parameter '{old_name}' has no default value in parent tool "
f"and no default or default_factory provided in ArgTransform. Either provide a default "
f"or default_factory in ArgTransform or don't hide required parameters."
)
if has_user_default:
# Store info for later factory calling or direct value
hidden_defaults[old_name] = transform
# Skip adding to schema (not exposed to clients)
continue
transform_result = cls._apply_single_transform(
old_name,
old_schema,
transform,
old_name in parent_required,
)
if transform_result:
new_name, new_schema, is_required = transform_result
new_props[new_name] = new_schema
new_to_old[new_name] = old_name
if is_required:
new_required.add(new_name)
schema = {
"type": "object",
"properties": new_props,
"required": list(new_required),
}
# Create forwarding function that closes over everything it needs
async def _forward(**kwargs):
# Validate arguments
valid_args = set(new_props.keys())
provided_args = set(kwargs.keys())
unknown_args = provided_args - valid_args
if unknown_args:
raise TypeError(
f"Got unexpected keyword argument(s): {', '.join(sorted(unknown_args))}"
)
# Check required arguments
missing_args = new_required - provided_args
if missing_args:
raise TypeError(
f"Missing required argument(s): {', '.join(sorted(missing_args))}"
)
# Map arguments to parent names
parent_args = {}
for new_name, value in kwargs.items():
old_name = new_to_old.get(new_name, new_name)
parent_args[old_name] = value
# Add hidden defaults (constant values for hidden parameters)
for old_name, transform in hidden_defaults.items():
if transform.default is not NotSet:
parent_args[old_name] = transform.default
elif transform.default_factory is not NotSet:
# Type check to ensure default_factory is callable
if callable(transform.default_factory):
parent_args[old_name] = transform.default_factory()
return await parent_tool.run(parent_args)
return schema, _forward
@staticmethod
def _apply_single_transform(
old_name: str,
old_schema: dict[str, Any],
transform: ArgTransform,
is_required: bool,
) -> tuple[str, dict[str, Any], bool] | None:
"""Apply transformation to a single parameter.
This method handles the transformation of a single argument according to
the specified transformation rules.
Args:
old_name: Original name of the parameter.
old_schema: Original JSON schema for the parameter.
transform: ArgTransform object specifying how to transform the parameter.
is_required: Whether the original parameter was required.
Returns:
Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
None if parameter should be dropped.
"""
if transform.hide:
return None
# Handle name transformation - ensure we always have a string
if transform.name is not NotSet:
new_name = transform.name if transform.name is not None else old_name
else:
new_name = old_name
# Ensure new_name is always a string
if not isinstance(new_name, str):
new_name = old_name
new_schema = old_schema.copy()
# Handle description transformation
if transform.description is not NotSet:
if transform.description is None:
new_schema.pop("description", None) # Remove description
else:
new_schema["description"] = transform.description
# Handle required transformation first
if transform.required is not NotSet:
is_required = bool(transform.required)
if transform.required is True:
# Remove any existing default when making required
new_schema.pop("default", None)
# Handle default value transformation (only if not making required)
if transform.default is not NotSet and transform.required is not True:
new_schema["default"] = transform.default
is_required = False
# Handle type transformation
if transform.type is not NotSet:
# Use TypeAdapter to get proper JSON schema for the type
type_schema = get_cached_typeadapter(transform.type).json_schema()
# Update the schema with the type information from TypeAdapter
new_schema.update(type_schema)
return new_name, new_schema, is_required
@staticmethod
def _merge_schema_with_precedence(
base_schema: dict[str, Any], override_schema: dict[str, Any]
) -> dict[str, Any]:
"""Merge two schemas, with the override schema taking precedence.
Args:
base_schema: Base schema to start with
override_schema: Schema that takes precedence for overlapping properties
Returns:
Merged schema with override taking precedence
"""
merged_props = base_schema.get("properties", {}).copy()
merged_required = set(base_schema.get("required", []))
override_props = override_schema.get("properties", {})
override_required = set(override_schema.get("required", []))
# Override properties
for param_name, param_schema in override_props.items():
if param_name in merged_props:
# Merge the schemas, with override taking precedence
base_param = merged_props[param_name].copy()
base_param.update(param_schema)
merged_props[param_name] = base_param
else:
merged_props[param_name] = param_schema.copy()
# Handle required parameters - override takes complete precedence
# Start with override's required set
final_required = override_required.copy()
# For parameters not in override, inherit base requirement status
# but only if they don't have a default in the final merged properties
for param_name in merged_required:
if param_name not in override_props:
# Parameter not mentioned in override, keep base requirement status
final_required.add(param_name)
elif (
param_name in override_props
and "default" not in merged_props[param_name]
):
# Parameter in override but no default, keep required if it was required in base
if param_name not in override_required:
# Override doesn't specify it as required, and it has no default,
# so inherit from base
final_required.add(param_name)
# Remove any parameters that have defaults (they become optional)
for param_name, param_schema in merged_props.items():
if "default" in param_schema:
final_required.discard(param_name)
return {
"type": "object",
"properties": merged_props,
"required": list(final_required),
}
@staticmethod
def _function_has_kwargs(fn: Callable[..., Any]) -> bool:
"""Check if function accepts **kwargs.
This determines whether a custom function can accept arbitrary keyword arguments,
which affects how schemas are merged during tool transformation.
Args:
fn: Function to inspect.
Returns:
True if the function has a **kwargs parameter, False otherwise.
"""
sig = inspect.signature(fn)
return any(
p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
)

View file

@ -0,0 +1,55 @@
from collections.abc import Sequence
from typing import Annotated, TypeVar
from pydantic import BeforeValidator, Field
from fastmcp.utilities.types import FastMCPBaseModel
T = TypeVar("T")
def _convert_set_default_none(maybe_set: set[T] | Sequence[T] | None) -> set[T]:
"""Convert a sequence to a set, defaulting to an empty set if None."""
if maybe_set is None:
return set()
if isinstance(maybe_set, set):
return maybe_set
return set(maybe_set)
class FastMCPComponent(FastMCPBaseModel):
"""Base class for FastMCP tools, prompts, resources, and resource templates."""
name: str = Field(
description="The name of the component.",
)
description: str | None = Field(
default=None,
description="The description of the component.",
)
tags: Annotated[set[str], BeforeValidator(_convert_set_default_none)] = Field(
default_factory=set,
description="Tags for the component.",
)
enabled: bool = Field(
default=True,
description="Whether the component is enabled.",
)
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return False
assert isinstance(other, type(self))
return self.model_dump() == other.model_dump()
def __repr__(self) -> str:
return f"{self.__class__.__name__}(name={self.name!r}, description={self.description!r}, tags={self.tags}, enabled={self.enabled})"
def enable(self) -> None:
"""Enable the component."""
self.enabled = True
def disable(self) -> None:
"""Disable the component."""
self.enabled = False

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
from typing import TYPE_CHECKING, Annotated, Any, Literal
from urllib.parse import urlparse
from pydantic import AnyUrl, Field
@ -55,7 +55,13 @@ class StdioMCPServer(FastMCPBaseModel):
class RemoteMCPServer(FastMCPBaseModel):
url: str
headers: dict[str, str] = Field(default_factory=dict)
transport: Literal["streamable-http", "sse", "http"] | None = None
transport: Literal["streamable-http", "sse"] | None = None
auth: Annotated[
str | Literal["oauth"] | None,
Field(
description='Either a string representing a Bearer token or the literal "oauth" to use OAuth authentication.'
),
] = None
def to_transport(self) -> StreamableHttpTransport | SSETransport:
from fastmcp.client.transports import SSETransport, StreamableHttpTransport
@ -66,9 +72,11 @@ class RemoteMCPServer(FastMCPBaseModel):
transport = self.transport
if transport == "sse":
return SSETransport(self.url, headers=self.headers)
return SSETransport(self.url, headers=self.headers, auth=self.auth)
else:
return StreamableHttpTransport(self.url, headers=self.headers)
return StreamableHttpTransport(
self.url, headers=self.headers, auth=self.auth
)
class MCPConfig(FastMCPBaseModel):

View file

@ -80,15 +80,6 @@ def find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None:
return None
def _convert_set_defaults(maybe_set: set[T] | list[T] | None) -> set[T]:
"""Convert a set or list to a set, defaulting to an empty set if None."""
if maybe_set is None:
return set()
if isinstance(maybe_set, set):
return maybe_set
return set(maybe_set)
class Image:
"""Helper class for returning images from tools."""

View file

@ -1,12 +1,16 @@
import asyncio
import sys
from typing import cast
from unittest.mock import AsyncMock
import mcp
import pytest
from mcp import McpError
from mcp.client.auth import OAuthClientProvider
from pydantic import AnyUrl
from fastmcp.client import Client
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.transports import (
FastMCPTransport,
MCPConfigTransport,
@ -273,6 +277,14 @@ async def test_client_connection(fastmcp_server):
assert not client.is_connected()
async def test_initialize_called_once(fastmcp_server, monkeypatch):
mock_initialize = AsyncMock()
monkeypatch.setattr(mcp.ClientSession, "initialize", mock_initialize)
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
assert mock_initialize.call_count == 1
async def test_initialize_result_connected(fastmcp_server):
"""Test that initialize_result returns the correct result when connected."""
client = Client(transport=FastMCPTransport(fastmcp_server))
@ -810,3 +822,73 @@ class TestInferTransport:
server = FastMCP1()
transport = infer_transport(server)
assert isinstance(transport, FastMCPTransport)
class TestAuth:
def test_default_auth_is_none(self):
client = Client(transport=StreamableHttpTransport("http://localhost:8000"))
assert client.transport.auth is None
def test_stdio_doesnt_support_auth(self):
with pytest.raises(ValueError, match="This transport does not support auth"):
Client(transport=StdioTransport("echo", ["hello"]), auth="oauth")
def test_oauth_literal_sets_up_oauth_shttp(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000"), auth="oauth"
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_pass_direct_to_transport(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000", auth="oauth"),
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_sets_up_oauth_sse(self):
client = Client(transport=SSETransport("http://localhost:8000"), auth="oauth")
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_pass_direct_to_transport_sse(self):
client = Client(transport=SSETransport("http://localhost:8000", auth="oauth"))
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_auth_string_sets_up_bearer_auth_shttp(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000"),
auth="test_token",
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_pass_direct_to_transport_shttp(self):
client = Client(
transport=StreamableHttpTransport(
"http://localhost:8000", auth="test_token"
),
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_sets_up_bearer_auth_sse(self):
client = Client(
transport=SSETransport("http://localhost:8000"),
auth="test_token",
)
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_pass_direct_to_transport_sse(self):
client = Client(
transport=SSETransport("http://localhost:8000", auth="test_token"),
)
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"

View file

@ -50,18 +50,12 @@ class TestResourceValidation:
)
assert resource.name == "resource://my-resource"
def test_resource_name_validation(self):
"""Test name validation."""
def test_provided_name_takes_precedence_over_uri(self):
"""Test that provided name takes precedence over URI."""
def dummy_func() -> str:
return "data"
# Must provide either name or URI
with pytest.raises(ValueError, match="Either name or uri must be provided"):
FunctionResource(
fn=dummy_func,
)
# Explicit name takes precedence over URI
resource = FunctionResource(
uri=AnyUrl("resource://uri-name"),

View file

@ -9,7 +9,7 @@ from pydantic import AnyUrl
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
from fastmcp.client.transports import FastMCPTransport, StreamableHttpTransport
from fastmcp.exceptions import ToolError
from fastmcp.server.proxy import FastMCPProxy
@ -104,7 +104,8 @@ def test_as_proxy_with_url():
"""FastMCP.as_proxy should accept a URL without connecting."""
proxy = FastMCP.as_proxy("http://example.com/mcp")
assert isinstance(proxy, FastMCPProxy)
assert repr(proxy.client.transport).startswith("<StreamableHttp(")
assert isinstance(proxy.client.transport, StreamableHttpTransport)
assert proxy.client.transport.url == "http://example.com/mcp"
class TestTools:
@ -139,10 +140,65 @@ class TestTools:
assert proxy_result[0].text == "3" # type: ignore[attr-defined]
async def test_error_tool_raises_error(self, proxy_server):
with pytest.raises(ToolError, match=""):
with pytest.raises(ToolError, match="This is a test error"):
async with Client(proxy_server) as client:
await client.call_tool("error_tool", {})
async def test_proxy_can_overwrite_proxied_tool(self, proxy_server):
"""
Test that a tool defined on the proxy can overwrite the proxied tool with the same name.
"""
@proxy_server.tool
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
result = await client.call_tool("greet", {"name": "Marvin", "extra": "abc"})
assert result[0].text == "Overwritten, Marvin! abc" # type: ignore[attr-defined]
async def test_proxy_errors_if_overwritten_tool_is_disabled(self, proxy_server):
"""
Test that a tool defined on the proxy is not listed if it is disabled,
and it doesn't fall back to the proxied tool with the same name
"""
@proxy_server.tool(enabled=False)
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
with pytest.raises(ToolError, match="Unknown tool"):
await client.call_tool("greet", {"name": "Marvin", "extra": "abc"})
async def test_proxy_can_list_overwritten_tool(self, proxy_server):
"""
Test that a tool defined on the proxy is listed instead of the proxied tool
"""
@proxy_server.tool
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
tools = await client.list_tools()
greet_tool = next(t for t in tools if t.name == "greet")
assert "extra" in greet_tool.inputSchema["properties"]
async def test_proxy_can_list_overwritten_tool_if_disabled(self, proxy_server):
"""
Test that a tool defined on the proxy is not listed if it is disabled,
and it doesn't fall back to the proxied tool with the same name
"""
@proxy_server.tool(enabled=False)
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
tools = await client.list_tools()
assert not any(t.name == "greet" for t in tools)
class TestResources:
async def test_get_resources(self, proxy_server):
@ -177,10 +233,70 @@ class TestResources:
assert json.loads(result[0].text) == USERS # type: ignore[attr-defined]
async def test_read_resource_returns_none_if_not_found(self, proxy_server):
with pytest.raises(McpError, match="Unknown resource: resource://nonexistent"):
with pytest.raises(
McpError, match="Unknown resource: 'resource://nonexistent'"
):
async with Client(proxy_server) as client:
await client.read_resource("resource://nonexistent")
async def test_proxy_can_overwrite_proxied_resource(self, proxy_server):
"""
Test that a resource defined on the proxy can overwrite the proxied resource with the same URI.
"""
@proxy_server.resource(uri="resource://wave")
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
result = await client.read_resource("resource://wave")
assert result[0].text == "Overwritten wave! 🌊" # type: ignore[attr-defined]
async def test_proxy_errors_if_overwritten_resource_is_disabled(self, proxy_server):
"""
Test that a resource defined on the proxy is not accessible if it is disabled,
and it doesn't fall back to the proxied resource with the same URI
"""
@proxy_server.resource(uri="resource://wave", enabled=False)
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource("resource://wave")
async def test_proxy_can_list_overwritten_resource(self, proxy_server):
"""
Test that a resource defined on the proxy is listed instead of the proxied resource
"""
@proxy_server.resource(uri="resource://wave", name="overwritten_wave")
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
resources = await client.list_resources()
wave_resource = next(
r for r in resources if str(r.uri) == "resource://wave"
)
assert wave_resource.name == "overwritten_wave"
async def test_proxy_can_list_overwritten_resource_if_disabled(self, proxy_server):
"""
Test that a resource defined on the proxy is not listed if it is disabled,
and it doesn't fall back to the proxied resource with the same URI
"""
@proxy_server.resource(uri="resource://wave", enabled=False)
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
resources = await client.list_resources()
wave_resources = [r for r in resources if str(r.uri) == "resource://wave"]
assert len(wave_resources) == 0
class TestResourceTemplates:
async def test_get_resource_templates(self, proxy_server):
@ -209,6 +325,77 @@ class TestResourceTemplates:
proxy_result = await client.read_resource("data://user/1")
assert proxy_result == result
async def test_proxy_can_overwrite_proxied_resource_template(self, proxy_server):
"""
Test that a resource template defined on the proxy can overwrite the proxied template with the same URI template.
"""
@proxy_server.resource(uri="data://user/{user_id}", name="overwritten_get_user")
def overwritten_get_user(user_id: str) -> dict[str, Any]:
return {
"id": user_id,
"name": "Overwritten User",
"active": True,
"extra": "data",
}
async with Client(proxy_server) as client:
result = await client.read_resource("data://user/1")
user_data = json.loads(result[0].text) # type: ignore[attr-defined]
assert user_data["name"] == "Overwritten User"
assert user_data["extra"] == "data"
async def test_proxy_errors_if_overwritten_resource_template_is_disabled(
self, proxy_server
):
"""
Test that a resource template defined on the proxy is not accessible if it is disabled,
and it doesn't fall back to the proxied template with the same URI template
"""
@proxy_server.resource(uri="data://user/{user_id}", enabled=False)
def overwritten_get_user(user_id: str) -> dict[str, Any]:
return {"id": user_id, "name": "Overwritten User", "active": True}
async with Client(proxy_server) as client:
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource("data://user/1")
async def test_proxy_can_list_overwritten_resource_template(self, proxy_server):
"""
Test that a resource template defined on the proxy is listed instead of the proxied template
"""
@proxy_server.resource(uri="data://user/{user_id}", name="overwritten_get_user")
def overwritten_get_user(user_id: str) -> dict[str, Any]:
return {"id": user_id, "name": "Overwritten User", "active": True}
async with Client(proxy_server) as client:
templates = await client.list_resource_templates()
user_template = next(
t for t in templates if t.uriTemplate == "data://user/{user_id}"
)
assert user_template.name == "overwritten_get_user"
async def test_proxy_can_list_overwritten_resource_template_if_disabled(
self, proxy_server
):
"""
Test that a resource template defined on the proxy is not listed if it is disabled,
and it doesn't fall back to the proxied template with the same URI template
"""
@proxy_server.resource(uri="data://user/{user_id}", enabled=False)
def overwritten_get_user(user_id: str) -> dict[str, Any]:
return {"id": user_id, "name": "Overwritten User", "active": True}
async with Client(proxy_server) as client:
templates = await client.list_resource_templates()
user_templates = [
t for t in templates if t.uriTemplate == "data://user/{user_id}"
]
assert len(user_templates) == 0
class TestPrompts:
async def test_get_prompts_server_method(self, proxy_server: FastMCPProxy):
@ -237,6 +424,70 @@ class TestPrompts:
assert result.messages[0].role == "user"
assert result.messages[0].content.text == "Welcome to FastMCP, Alice!" # type: ignore[attr-defined]
async def test_proxy_can_overwrite_proxied_prompt(self, proxy_server):
"""
Test that a prompt defined on the proxy can overwrite the proxied prompt with the same name.
"""
@proxy_server.prompt
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
result = await client.get_prompt(
"welcome", {"name": "Alice", "extra": "colleague"}
)
assert result.messages[0].role == "user"
assert (
result.messages[0].content.text # type: ignore[attr-defined]
== "Overwritten welcome, Alice! You are my colleague."
)
async def test_proxy_errors_if_overwritten_prompt_is_disabled(self, proxy_server):
"""
Test that a prompt defined on the proxy is not accessible if it is disabled,
and it doesn't fall back to the proxied prompt with the same name
"""
@proxy_server.prompt(enabled=False)
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
with pytest.raises(McpError, match="Unknown prompt"):
await client.get_prompt("welcome", {"name": "Alice"})
async def test_proxy_can_list_overwritten_prompt(self, proxy_server):
"""
Test that a prompt defined on the proxy is listed instead of the proxied prompt
"""
@proxy_server.prompt
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
prompts = await client.list_prompts()
welcome_prompt = next(p for p in prompts if p.name == "welcome")
# Check that the overwritten prompt has the additional 'extra' parameter
param_names = [arg.name for arg in welcome_prompt.arguments or []]
assert "extra" in param_names
async def test_proxy_can_list_overwritten_prompt_if_disabled(self, proxy_server):
"""
Test that a prompt defined on the proxy is not listed if it is disabled,
and it doesn't fall back to the proxied prompt with the same name
"""
@proxy_server.prompt(enabled=False)
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
prompts = await client.list_prompts()
welcome_prompts = [p for p in prompts if p.name == "welcome"]
assert len(welcome_prompts) == 0
async def test_proxy_handles_multiple_concurrent_tasks_correctly(
proxy_server: FastMCPProxy,

View file

@ -617,7 +617,7 @@ class TestToolContextInjection:
result = await client.call_tool("tool_with_context", {"x": 42})
assert len(result) == 1
content = result[0]
assert content.text == "2" # type: ignore[attr-defined]
assert content.text == "1" # type: ignore[attr-defined]
async def test_async_context(self):
"""Test that context works in async functions."""
@ -632,7 +632,7 @@ class TestToolContextInjection:
result = await client.call_tool("async_tool", {"x": 42})
assert len(result) == 1
content = result[0]
assert content.text == "Async request 2: 42" # type: ignore[attr-defined]
assert content.text == "Async request 1: 42" # type: ignore[attr-defined]
async def test_optional_context(self):
"""Test that context is optional."""
@ -696,7 +696,103 @@ class TestToolContextInjection:
async with Client(mcp) as client:
result = await client.call_tool("MyTool", {"x": 2})
assert result[0].text == "4" # type: ignore[attr-defined]
assert result[0].text == "3" # type: ignore[attr-defined]
class TestToolEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
assert sample_tool.enabled
tool = await mcp.get_tool("sample_tool")
assert tool.enabled
tool.disable()
assert not tool.enabled
assert not sample_tool.enabled
tool.enable()
assert tool.enabled
assert sample_tool.enabled
async def test_tool_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.tool(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 0
with pytest.raises(ToolError, match="Unknown tool"):
await client.call_tool("sample_tool", {"x": 5})
async def test_tool_toggle_enabled(self):
mcp = FastMCP()
@mcp.tool(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
sample_tool.enable()
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 1
async def test_tool_toggle_disabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
sample_tool.disable()
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 0
with pytest.raises(ToolError, match="Unknown tool"):
await client.call_tool("sample_tool", {"x": 5})
async def test_get_tool_and_disable(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
tool = await mcp.get_tool("sample_tool")
assert tool.enabled
sample_tool.disable()
async with Client(mcp) as client:
result = await client.list_tools()
assert len(result) == 0
with pytest.raises(ToolError, match="Unknown tool"):
await client.call_tool("sample_tool", {"x": 5})
async def test_cant_call_disabled_tool(self):
mcp = FastMCP()
@mcp.tool(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
with pytest.raises(Exception, match="Unknown tool"):
async with Client(mcp) as client:
await client.call_tool("sample_tool", {"x": 5})
class TestResource:
@ -780,7 +876,103 @@ class TestResourceContext:
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text == "2" # type: ignore[attr-defined]
assert result[0].text == "1" # type: ignore[attr-defined]
class TestResourceEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://data")
def sample_resource() -> str:
return "Hello, world!"
assert sample_resource.enabled
resource = await mcp.get_resource("resource://data")
assert resource.enabled
resource.disable()
assert not resource.enabled
assert not sample_resource.enabled
resource.enable()
assert resource.enabled
assert sample_resource.enabled
async def test_resource_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.resource("resource://data", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources) == 0
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource(AnyUrl("resource://data"))
async def test_resource_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://data", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
sample_resource.enable()
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources) == 1
async def test_resource_toggle_disabled(self):
mcp = FastMCP()
@mcp.resource("resource://data")
def sample_resource() -> str:
return "Hello, world!"
sample_resource.disable()
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources) == 0
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource(AnyUrl("resource://data"))
async def test_get_resource_and_disable(self):
mcp = FastMCP()
@mcp.resource("resource://data")
def sample_resource() -> str:
return "Hello, world!"
resource = await mcp.get_resource("resource://data")
assert resource.enabled
sample_resource.disable()
async with Client(mcp) as client:
result = await client.list_resources()
assert len(result) == 0
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource(AnyUrl("resource://data"))
async def test_cant_read_disabled_resource(self):
mcp = FastMCP()
@mcp.resource("resource://data", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
with pytest.raises(McpError, match="Unknown resource"):
async with Client(mcp) as client:
await client.read_resource(AnyUrl("resource://data"))
class TestResourceTemplates:
@ -1015,7 +1207,7 @@ class TestResourceTemplateContext:
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text.startswith("Resource template: test 2") # type: ignore[attr-defined]
assert result[0].text.startswith("Resource template: test 1") # type: ignore[attr-defined]
async def test_resource_template_context_with_callable_object(self):
mcp = FastMCP()
@ -1031,7 +1223,100 @@ class TestResourceTemplateContext:
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text.startswith("Resource template: test 2") # type: ignore[attr-defined]
assert result[0].text.startswith("Resource template: test 1") # type: ignore[attr-defined]
class TestResourceTemplateEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://{param}")
def sample_template(param: str) -> str:
return f"Template: {param}"
assert sample_template.enabled
template = await mcp.get_resource_template("resource://{param}")
assert template.enabled
template.disable()
assert not template.enabled
assert not sample_template.enabled
template.enable()
assert template.enabled
assert sample_template.enabled
async def test_template_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.resource("resource://{param}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {param}"
async with Client(mcp) as client:
templates = await client.list_resource_templates()
assert len(templates) == 0
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource(AnyUrl("resource://test"))
async def test_template_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://{param}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {param}"
sample_template.enable()
async with Client(mcp) as client:
templates = await client.list_resource_templates()
assert len(templates) == 1
async def test_template_toggle_disabled(self):
mcp = FastMCP()
@mcp.resource("resource://{param}")
def sample_template(param: str) -> str:
return f"Template: {param}"
sample_template.disable()
async with Client(mcp) as client:
templates = await client.list_resource_templates()
assert len(templates) == 0
async def test_get_template_and_disable(self):
mcp = FastMCP()
@mcp.resource("resource://{param}")
def sample_template(param: str) -> str:
return f"Template: {param}"
template = await mcp.get_resource_template("resource://{param}")
assert template.enabled
sample_template.disable()
async with Client(mcp) as client:
result = await client.list_resource_templates()
assert len(result) == 0
with pytest.raises(McpError, match="Unknown resource"):
await client.read_resource(AnyUrl("resource://test"))
async def test_cant_read_disabled_template(self):
mcp = FastMCP()
@mcp.resource("resource://{param}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {param}"
with pytest.raises(McpError, match="Unknown resource"):
async with Client(mcp) as client:
await client.read_resource(AnyUrl("resource://test"))
class TestPrompts:
@ -1220,6 +1505,102 @@ class TestPrompts:
assert prompt.tags == {"example", "test-tag"}
class TestPromptEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.prompt
def sample_prompt() -> str:
return "Hello, world!"
assert sample_prompt.enabled
prompt = await mcp.get_prompt("sample_prompt")
assert prompt.enabled
prompt.disable()
assert not prompt.enabled
assert not sample_prompt.enabled
prompt.enable()
assert prompt.enabled
assert sample_prompt.enabled
async def test_prompt_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.prompt(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
async with Client(mcp) as client:
prompts = await client.list_prompts()
assert len(prompts) == 0
with pytest.raises(McpError, match="Unknown prompt"):
await client.get_prompt("sample_prompt")
async def test_prompt_toggle_enabled(self):
mcp = FastMCP()
@mcp.prompt(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
sample_prompt.enable()
async with Client(mcp) as client:
prompts = await client.list_prompts()
assert len(prompts) == 1
async def test_prompt_toggle_disabled(self):
mcp = FastMCP()
@mcp.prompt
def sample_prompt() -> str:
return "Hello, world!"
sample_prompt.disable()
async with Client(mcp) as client:
prompts = await client.list_prompts()
assert len(prompts) == 0
with pytest.raises(McpError, match="Unknown prompt"):
await client.get_prompt("sample_prompt")
async def test_get_prompt_and_disable(self):
mcp = FastMCP()
@mcp.prompt
def sample_prompt() -> str:
return "Hello, world!"
prompt = await mcp.get_prompt("sample_prompt")
assert prompt.enabled
sample_prompt.disable()
async with Client(mcp) as client:
result = await client.list_prompts()
assert len(result) == 0
with pytest.raises(McpError, match="Unknown prompt"):
await client.get_prompt("sample_prompt")
async def test_cant_get_disabled_prompt(self):
mcp = FastMCP()
@mcp.prompt(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
with pytest.raises(McpError, match="Unknown prompt"):
async with Client(mcp) as client:
await client.get_prompt("sample_prompt")
class TestPromptContext:
async def test_prompt_context(self):
mcp = FastMCP()
@ -1249,4 +1630,4 @@ class TestPromptContext:
assert len(result.messages) == 1
message = result.messages[0]
assert message.role == "user"
assert message.content.text == "Hello, World! 2" # type: ignore[attr-defined]
assert message.content.text == "Hello, World! 1" # type: ignore[attr-defined]

View file

@ -21,9 +21,7 @@ async def test_tool_exclude_args_in_tool_manager():
tools = mcp._tool_manager.list_tools()
assert len(tools) == 1
assert tools[0].exclude_args is not None
for args in tools[0].exclude_args:
assert args not in tools[0].parameters
assert "state" not in echo.parameters["properties"]
async def test_tool_exclude_args_without_default_value_raises_error():
@ -64,10 +62,7 @@ async def test_add_tool_method_exclude_args():
# Check internal tool objects directly
tools = mcp._tool_manager.list_tools()
assert len(tools) == 1
assert tools[0].exclude_args is not None
assert tools[0].exclude_args == ["state"]
for args in tools[0].exclude_args:
assert args not in tools[0].parameters
assert "state" not in tools[0].parameters["properties"]
async def test_tool_functionality_with_exclude_args():

View file

@ -0,0 +1,989 @@
import re
from dataclasses import dataclass
from typing import Annotated, Any
import pytest
from dirty_equals import IsList
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.client.client import Client
from fastmcp.exceptions import ToolError
from fastmcp.tools import Tool, forward, forward_raw
from fastmcp.tools.tool import FunctionTool
from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
) -> int:
print("running!")
return old_x + old_y
return Tool.from_function(add)
def test_tool_from_tool_no_change(add_tool):
new_tool = Tool.from_tool(add_tool)
assert isinstance(new_tool, TransformedTool)
assert new_tool.parameters == add_tool.parameters
assert new_tool.name == add_tool.name
assert new_tool.description == add_tool.description
async def test_renamed_arg_description_is_maintained(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
assert (
new_tool.parameters["properties"]["new_x"]["description"] == "old_x description"
)
async def test_tool_defaults_are_maintained_on_unmapped_args(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
result = await new_tool.run(arguments={"new_x": 1})
assert result[0].text == "11" # type: ignore[attr-defined]
async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(name="new_y")}
)
result = await new_tool.run(arguments={"old_x": 1})
assert result[0].text == "11" # type: ignore[attr-defined]
def test_tool_change_arg_name(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
assert sorted(new_tool.parameters["properties"]) == ["new_x", "old_y"]
assert get_property(new_tool, "new_x") == get_property(add_tool, "old_x")
assert get_property(new_tool, "old_y") == get_property(add_tool, "old_y")
assert new_tool.parameters["required"] == ["new_x"]
def test_tool_change_arg_description(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(description="new description")}
)
assert get_property(new_tool, "old_x")["description"] == "new description"
async def test_tool_drop_arg(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
assert sorted(new_tool.parameters["properties"]) == ["old_x"]
result = await new_tool.run(arguments={"old_x": 1})
assert result[0].text == "11" # type: ignore[attr-defined]
async def test_dropped_args_error_if_provided(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
with pytest.raises(
TypeError, match="Got unexpected keyword argument\\(s\\): old_y"
):
await new_tool.run(arguments={"old_x": 1, "old_y": 2})
async def test_hidden_arg_with_constant_default(add_tool):
"""Test that hidden argument with default value passes constant to parent."""
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True, default=20)}
)
# Only old_x should be exposed
assert sorted(new_tool.parameters["properties"]) == ["old_x"]
# Should pass old_x=5 and old_y=20 to parent
result = await new_tool.run(arguments={"old_x": 5})
assert result[0].text == "25" # type: ignore[attr-defined]
async def test_hidden_arg_without_default_uses_parent_default(add_tool):
"""Test that hidden argument without default uses parent's default."""
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
# Only old_x should be exposed
assert sorted(new_tool.parameters["properties"]) == ["old_x"]
# Should pass old_x=3 and let parent use its default old_y=10
result = await new_tool.run(arguments={"old_x": 3})
assert result[0].text == "13" # type: ignore[attr-defined]
async def test_mixed_hidden_args_with_custom_function(add_tool):
"""Test custom function with both hidden constant and hidden default parameters."""
async def custom_fn(visible_x: int) -> int:
# This custom function should receive the transformed visible parameter
# and the hidden parameters should be automatically handled
result = await forward(visible_x=visible_x)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="visible_x"), # Rename and expose
"old_y": ArgTransform(hide=True, default=25), # Hidden with constant
},
)
# Only visible_x should be exposed
assert sorted(new_tool.parameters["properties"]) == ["visible_x"]
# Should pass visible_x=7 as old_x=7 and old_y=25 to parent
result = await new_tool.run(arguments={"visible_x": 7})
assert result[0].text == "32" # type: ignore[attr-defined]
async def test_hide_required_param_without_default_raises_error():
"""Test that hiding a required parameter without providing default raises error."""
@Tool.from_function
def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
return required_param + optional_param
# This should raise an error because required_param has no default and we're not providing one
with pytest.raises(
ValueError,
match=r"Hidden parameter 'required_param' has no default value in parent tool",
):
Tool.from_tool(
tool_with_required_param,
transform_args={"required_param": ArgTransform(hide=True)},
)
async def test_hide_required_param_with_user_default_works():
"""Test that hiding a required parameter works when user provides a default."""
@Tool.from_function
def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
return required_param + optional_param
# This should work because we're providing a default for the hidden required param
new_tool = Tool.from_tool(
tool_with_required_param,
transform_args={"required_param": ArgTransform(hide=True, default=5)},
)
# Only optional_param should be exposed
assert sorted(new_tool.parameters["properties"]) == ["optional_param"]
# Should pass required_param=5 and optional_param=20 to parent
result = await new_tool.run(arguments={"optional_param": 20})
assert result[0].text == "25" # type: ignore[attr-defined]
async def test_forward_with_argument_mapping(add_tool):
"""Test that forward() applies argument mapping correctly."""
async def custom_fn(new_x: int, new_y: int = 5) -> int:
return await forward(new_x=new_x, new_y=new_y)
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
assert result[0].text == "5" # type: ignore[attr-defined]
async def test_forward_with_incorrect_args_raises_error(add_tool):
async def custom_fn(new_x: int, new_y: int = 5) -> int:
# the forward should use the new args, not the old ones
return await forward(old_x=new_x, old_y=new_y)
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
with pytest.raises(
TypeError, match=re.escape("Got unexpected keyword argument(s): old_x, old_y")
):
await new_tool.run(arguments={"new_x": 2, "new_y": 3})
async def test_forward_raw_without_argument_mapping(add_tool):
"""Test that forward_raw() calls parent directly without mapping."""
async def custom_fn(new_x: int, new_y: int = 5) -> int:
# Call parent directly with original argument names
result = await forward_raw(old_x=new_x, old_y=new_y)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
assert result[0].text == "5" # type: ignore[attr-defined]
async def test_custom_fn_with_kwargs_and_no_transform_args(add_tool):
async def custom_fn(extra: int, **kwargs) -> int:
sum = await forward(**kwargs)
return int(sum[0].text) + extra # type: ignore[attr-defined]
new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
result = await new_tool.run(arguments={"extra": 1, "old_x": 2, "old_y": 3})
assert result[0].text == "6" # type: ignore[attr-defined]
assert new_tool.parameters["required"] == IsList(
"extra", "old_x", check_order=False
)
assert list(new_tool.parameters["properties"]) == IsList(
"extra", "old_x", "old_y", check_order=False
)
async def test_fn_with_kwargs_passes_through_original_args(add_tool):
async def custom_fn(new_y: int = 5, **kwargs) -> int:
assert kwargs == {"old_y": 3}
result = await forward(old_x=new_y, **kwargs)
return result
new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
result = await new_tool.run(arguments={"new_y": 2, "old_y": 3})
assert result[0].text == "5" # type: ignore[attr-defined]
async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):
"""Test that **kwargs receives arguments with their transformed names from transform_args."""
async def custom_fn(new_x: int, **kwargs) -> int:
# kwargs should contain 'old_y': 3 (transformed name), not 'old_y': 3 (original name)
assert kwargs == {"old_y": 3}
result = await forward(new_x=new_x, **kwargs)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
result = await new_tool.run(arguments={"new_x": 2, "old_y": 3})
assert result[0].text == "5" # type: ignore[attr-defined]
async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):
"""Test that function can explicitly handle some transformed args while others pass through kwargs."""
async def custom_fn(new_x: int, some_other_param: str = "default", **kwargs) -> int:
# x is explicitly handled, y should come through kwargs with transformed name
assert kwargs == {"old_y": 7}
result = await forward(new_x=new_x, **kwargs)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
result = await new_tool.run(
arguments={"new_x": 3, "old_y": 7, "some_other_param": "test"}
)
assert result[0].text == "10" # type: ignore[attr-defined]
async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):
"""Test **kwargs behavior with mix of mapped and unmapped arguments."""
async def custom_fn(new_x: int, **kwargs) -> int:
# new_x is explicitly handled, old_y should pass through kwargs with original name (unmapped)
assert kwargs == {"old_y": 5}
result = await forward(new_x=new_x, **kwargs)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
) # only map 'a'
result = await new_tool.run(arguments={"new_x": 1, "old_y": 5})
assert result[0].text == "6" # type: ignore[attr-defined]
async def test_fn_with_kwargs_dropped_args_not_in_kwargs(add_tool):
"""Test that dropped arguments don't appear in **kwargs."""
async def custom_fn(new_x: int, **kwargs) -> int:
# 'b' was dropped, so kwargs should be empty
assert kwargs == {}
# Can't use 'old_y' since it was dropped, so just use 'old_x' mapped to 'new_x'
result = await forward(new_x=new_x)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(hide=True),
},
) # drop 'old_y'
result = await new_tool.run(arguments={"new_x": 8})
# 8 + 10 (default value of b in parent)
assert result[0].text == "18" # type: ignore[attr-defined]
async def test_forward_outside_context_raises_error():
"""Test that forward() raises RuntimeError when called outside a transformed tool."""
with pytest.raises(
RuntimeError,
match=re.escape("forward() can only be called within a transformed tool"),
):
await forward(new_x=1, old_y=2)
async def test_forward_raw_outside_context_raises_error():
"""Test that forward_raw() raises RuntimeError when called outside a transformed tool."""
with pytest.raises(
RuntimeError,
match=re.escape("forward_raw() can only be called within a transformed tool"),
):
await forward_raw(new_x=1, old_y=2)
def test_transform_args_validation_unknown_arg(add_tool):
"""Test that transform_args with unknown arguments raises ValueError."""
with pytest.raises(
ValueError, match="Unknown arguments in transform_args: unknown_param"
):
Tool.from_tool(
add_tool, transform_args={"unknown_param": ArgTransform(name="new_name")}
)
def test_transform_args_creates_duplicate_names(add_tool):
"""Test that transform_args creating duplicate parameter names raises ValueError."""
with pytest.raises(
ValueError,
match="Multiple arguments would be mapped to the same names: same_name",
):
Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(name="same_name"),
"old_y": ArgTransform(name="same_name"),
},
)
def test_function_without_kwargs_missing_params(add_tool):
"""Test that function missing required transformed parameters raises ValueError."""
def invalid_fn(new_x: int, non_existent: str) -> str:
return f"{new_x}_{non_existent}"
with pytest.raises(
ValueError,
match="Function missing parameters required after transformation: new_y",
):
Tool.from_tool(
add_tool,
transform_fn=invalid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
def test_function_without_kwargs_can_have_extra_params(add_tool):
"""Test that function can have extra parameters not in parent tool."""
def valid_fn(new_x: int, new_y: int, extra_param: str = "default") -> str:
return f"{new_x}_{new_y}_{extra_param}"
# Should work - extra_param is fine as long as it has a default
new_tool = Tool.from_tool(
add_tool,
transform_fn=valid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
# The final schema should include all function parameters
assert "new_x" in new_tool.parameters["properties"]
assert "new_y" in new_tool.parameters["properties"]
assert "extra_param" in new_tool.parameters["properties"]
def test_function_with_kwargs_can_add_params(add_tool):
"""Test that function with **kwargs can add new parameters."""
async def valid_fn(extra_param: str, **kwargs) -> str:
result = await forward(**kwargs)
return f"{extra_param}: {result}"
# This should work fine - kwargs allows access to all transformed params
tool = Tool.from_tool(
add_tool,
transform_fn=valid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
# extra_param is added, new_x and new_y are available
assert "extra_param" in tool.parameters["properties"]
assert "new_x" in tool.parameters["properties"]
assert "new_y" in tool.parameters["properties"]
async def test_tool_transform_chaining(add_tool):
"""Test that transformed tools can be transformed again."""
# First transformation: a -> x
tool1 = Tool.from_tool(add_tool, transform_args={"old_x": ArgTransform(name="x")})
# Second transformation: x -> final_x, using tool1
tool2 = Tool.from_tool(tool1, transform_args={"x": ArgTransform(name="final_x")})
result = await tool2.run(arguments={"final_x": 5})
assert result[0].text == "15" # type: ignore[attr-defined]
# Transform tool1 with custom function that handles all parameters
async def custom(final_x: int, **kwargs) -> str:
result = await forward(final_x=final_x, **kwargs)
return f"custom {result[0].text}" # Extract text from content
tool3 = Tool.from_tool(
tool1, transform_fn=custom, transform_args={"x": ArgTransform(name="final_x")}
)
result = await tool3.run(arguments={"final_x": 3, "old_y": 5})
assert result[0].text == "custom 8" # type: ignore[attr-defined]
class MyModel(BaseModel):
x: int
y: str
@dataclass
class MyDataclass:
x: int
y: str
class MyTypedDict(TypedDict):
x: int
y: str
@pytest.mark.parametrize(
"py_type, json_type",
[
(int, "integer"),
(float, "number"),
(str, "string"),
(bool, "boolean"),
(list, "array"),
(list[int], "array"),
(dict, "object"),
(dict[str, int], "object"),
(MyModel, "object"),
(MyDataclass, "object"),
(MyTypedDict, "object"),
],
)
def test_arg_transform_type_handling(add_tool, py_type, json_type):
"""Test that ArgTransform type attribute gets applied to schema."""
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(type=py_type)}
)
# Check that the type was changed in the schema
x_prop = get_property(new_tool, "old_x")
assert x_prop["type"] == json_type
def test_arg_transform_annotated_types(add_tool):
"""Test that ArgTransform works with annotated types and complex types."""
from typing import Annotated
from pydantic import Field
# Test with Annotated types
tool = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(
type=Annotated[int, Field(description="An annotated integer")]
)
},
)
x_prop = get_property(tool, "old_x")
assert x_prop["type"] == "integer"
# The ArgTransform description should override the annotation description
# (since we didn't set a description in ArgTransform, it should use the original)
# Test with Annotated string that has constraints
tool2 = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(
type=Annotated[str, Field(min_length=1, max_length=10)]
)
},
)
x_prop2 = get_property(tool2, "old_x")
assert x_prop2["type"] == "string"
assert x_prop2["minLength"] == 1
assert x_prop2["maxLength"] == 10
def test_arg_transform_precedence_over_function_without_kwargs():
"""Test that ArgTransform attributes take precedence over function signature (no **kwargs)."""
@Tool.from_function
def base(x: int, y: str = "default") -> str:
return f"{x}: {y}"
# Function signature says x: int with no default, y: str = "function_default"
# ArgTransform should override these
def custom_fn(x: str = "transform_default", y: int = 99) -> str:
return f"custom: {x}, {y}"
tool = Tool.from_tool(
base,
transform_fn=custom_fn,
transform_args={
"x": ArgTransform(type=str, default="transform_default"),
"y": ArgTransform(type=int, default=99),
},
)
# ArgTransform should take precedence
x_prop = get_property(tool, "x")
y_prop = get_property(tool, "y")
assert x_prop["type"] == "string" # ArgTransform type wins
assert x_prop["default"] == "transform_default" # ArgTransform default wins
assert y_prop["type"] == "integer" # ArgTransform type wins
assert y_prop["default"] == 99 # ArgTransform default wins
# Neither parameter should be required due to ArgTransform defaults
assert "x" not in tool.parameters["required"]
assert "y" not in tool.parameters["required"]
async def test_arg_transform_precedence_over_function_with_kwargs():
"""Test that ArgTransform attributes take precedence over function signature (with **kwargs)."""
@Tool.from_function
def base(x: int, y: str = "base_default") -> str:
return f"{x}: {y}"
# Function signature has different types/defaults than ArgTransform
async def custom_fn(x: str = "function_default", **kwargs) -> str:
result = await forward(x=x, **kwargs)
return f"custom: {result}"
tool = Tool.from_tool(
base,
transform_fn=custom_fn,
transform_args={
"x": ArgTransform(type=int, default=42), # Different type and default
"y": ArgTransform(description="ArgTransform description"),
},
)
# ArgTransform should take precedence
x_prop = get_property(tool, "x")
y_prop = get_property(tool, "y")
assert x_prop["type"] == "integer" # ArgTransform type wins over function's str
assert x_prop["default"] == 42 # ArgTransform default wins over function's default
assert (
y_prop["description"] == "ArgTransform description"
) # ArgTransform description
# x should not be required due to ArgTransform default
assert "x" not in tool.parameters["required"]
# Test it works at runtime
result = await tool.run(arguments={"y": "test"})
# Should use ArgTransform default of 42
assert "42: test" in result[0].text # type: ignore[attr-defined]
def test_arg_transform_combined_attributes():
"""Test that multiple ArgTransform attributes work together."""
@Tool.from_function
def base(param: int) -> str:
return str(param)
tool = Tool.from_tool(
base,
transform_args={
"param": ArgTransform(
name="renamed_param",
type=str,
description="New description",
default="default_value",
)
},
)
# Check all attributes were applied
assert "renamed_param" in tool.parameters["properties"]
assert "param" not in tool.parameters["properties"]
prop = get_property(tool, "renamed_param")
assert prop["type"] == "string"
assert prop["description"] == "New description"
assert prop["default"] == "default_value"
assert "renamed_param" not in tool.parameters["required"] # Has default
async def test_arg_transform_type_precedence_runtime():
"""Test that ArgTransform type changes work correctly at runtime."""
@Tool.from_function
def base(x: int, y: int = 10) -> int:
return x + y
# Transform x to string type but keep same logic
async def custom_fn(x: str, y: int = 10) -> str:
# Convert string back to int for the original function
result = await forward_raw(x=int(x), y=y)
# Extract the text from the result
result_text = result[0].text
return f"String input '{x}' converted to result: {result_text}"
tool = Tool.from_tool(
base, transform_fn=custom_fn, transform_args={"x": ArgTransform(type=str)}
)
# Verify schema shows string type
assert get_property(tool, "x")["type"] == "string"
# Test it works with string input
result = await tool.run(arguments={"x": "5", "y": 3})
assert "String input '5'" in result[0].text # type: ignore[attr-defined]
assert "result: 8" in result[0].text # type: ignore[attr-defined]
class TestProxy:
@pytest.fixture
def mcp_server(self) -> FastMCP:
mcp = FastMCP()
@mcp.tool
def add(old_x: int, old_y: int = 10) -> int:
return old_x + old_y
return mcp
@pytest.fixture
def proxy_server(self, mcp_server: FastMCP) -> FastMCP:
from fastmcp.client.transports import FastMCPTransport
proxy = FastMCP.as_proxy(Client(transport=FastMCPTransport(mcp_server)))
return proxy
async def test_transform_proxy(self, proxy_server: FastMCP):
# when adding transformed tools to proxy servers. Needs separate investigation.
add_tool = await proxy_server.get_tool("add")
new_add_tool = Tool.from_tool(
add_tool,
name="add_transformed",
transform_args={"old_x": ArgTransform(name="new_x")},
)
proxy_server.add_tool(new_add_tool)
async with Client(proxy_server) as client:
# The tool should be registered with its transformed name
result = await client.call_tool("add_transformed", {"new_x": 1, "old_y": 2})
assert result[0].text == "3" # type: ignore[attr-defined]
async def test_arg_transform_default_factory():
"""Test ArgTransform with default_factory for hidden parameters."""
@Tool.from_function
def base_tool(x: int, timestamp: float) -> str:
return f"{x}_{timestamp}"
# Create a tool with default_factory for hidden timestamp
new_tool = Tool.from_tool(
base_tool,
transform_args={
"timestamp": ArgTransform(hide=True, default_factory=lambda: 12345.0)
},
)
# Only x should be visible since timestamp is hidden
assert sorted(new_tool.parameters["properties"]) == ["x"]
# Should work without providing timestamp (gets value from factory)
result = await new_tool.run(arguments={"x": 42})
assert result[0].text == "42_12345.0" # type: ignore[attr-defined]
async def test_arg_transform_default_factory_called_each_time():
"""Test that default_factory is called for each execution."""
call_count = 0
def counter_factory():
nonlocal call_count
call_count += 1
return call_count
@Tool.from_function
def base_tool(x: int, counter: int = 0) -> str:
return f"{x}_{counter}"
new_tool = Tool.from_tool(
base_tool,
transform_args={
"counter": ArgTransform(hide=True, default_factory=counter_factory)
},
)
# Only x should be visible since counter is hidden
assert sorted(new_tool.parameters["properties"]) == ["x"]
# First call
result1 = await new_tool.run(arguments={"x": 1})
assert result1[0].text == "1_1" # type: ignore[attr-defined]
# Second call should get a different value
result2 = await new_tool.run(arguments={"x": 2})
assert result2[0].text == "2_2" # type: ignore[attr-defined]
async def test_arg_transform_hidden_with_default_factory():
"""Test hidden parameter with default_factory."""
@Tool.from_function
def base_tool(x: int, request_id: str) -> str:
return f"{x}_{request_id}"
def make_request_id():
return "req_123"
new_tool = Tool.from_tool(
base_tool,
transform_args={
"request_id": ArgTransform(hide=True, default_factory=make_request_id)
},
)
# Only x should be visible
assert sorted(new_tool.parameters["properties"]) == ["x"]
# Should pass hidden request_id with factory value
result = await new_tool.run(arguments={"x": 42})
assert result[0].text == "42_req_123" # type: ignore[attr-defined]
async def test_arg_transform_default_and_factory_raises_error():
"""Test that providing both default and default_factory raises an error."""
with pytest.raises(
ValueError, match="Cannot specify both 'default' and 'default_factory'"
):
ArgTransform(default=42, default_factory=lambda: 24)
async def test_arg_transform_default_factory_requires_hide():
"""Test that default_factory requires hide=True."""
with pytest.raises(
ValueError, match="default_factory can only be used with hide=True"
):
ArgTransform(default_factory=lambda: 42) # hide=False by default
async def test_arg_transform_required_true():
"""Test that required=True makes an optional parameter required."""
@Tool.from_function
def base_tool(optional_param: int = 42) -> str:
return f"value: {optional_param}"
# Make the optional parameter required
new_tool = Tool.from_tool(
base_tool, transform_args={"optional_param": ArgTransform(required=True)}
)
# Parameter should now be required (no default in schema)
assert "optional_param" in new_tool.parameters["required"]
assert "default" not in new_tool.parameters["properties"]["optional_param"]
# Should work when parameter is provided
result = await new_tool.run(arguments={"optional_param": 100})
assert result[0].text == "value: 100" # type: ignore
# Should fail when parameter is not provided
with pytest.raises(TypeError, match="Missing required argument"):
await new_tool.run(arguments={})
async def test_arg_transform_required_false():
"""Test that required=False makes a required parameter optional with default."""
@Tool.from_function
def base_tool(required_param: int) -> str:
return f"value: {required_param}"
with pytest.raises(
ValueError,
match="Cannot specify 'required=False'. Set a default value instead.",
):
Tool.from_tool(
base_tool,
transform_args={"required_param": ArgTransform(required=False, default=99)}, # type: ignore
)
async def test_arg_transform_required_with_rename():
"""Test that required works correctly with argument renaming."""
@Tool.from_function
def base_tool(optional_param: int = 42) -> str:
return f"value: {optional_param}"
# Rename and make required
new_tool = Tool.from_tool(
base_tool,
transform_args={
"optional_param": ArgTransform(name="new_param", required=True)
},
)
# New parameter name should be required
assert "new_param" in new_tool.parameters["required"]
assert "optional_param" not in new_tool.parameters["properties"]
assert "new_param" in new_tool.parameters["properties"]
assert "default" not in new_tool.parameters["properties"]["new_param"]
# Should work with new name
result = await new_tool.run(arguments={"new_param": 200})
assert result[0].text == "value: 200" # type: ignore
async def test_arg_transform_required_true_with_default_raises_error():
"""Test that required=True with default raises an error."""
with pytest.raises(
ValueError, match="Cannot specify 'required=True' with 'default'"
):
ArgTransform(required=True, default=42)
async def test_arg_transform_required_true_with_factory_raises_error():
"""Test that required=True with default_factory raises an error."""
with pytest.raises(
ValueError, match="default_factory can only be used with hide=True"
):
ArgTransform(required=True, default_factory=lambda: 42)
async def test_arg_transform_required_no_change():
"""Test that required=... (NotSet) leaves requirement status unchanged."""
@Tool.from_function
def base_tool(required_param: int, optional_param: int = 42) -> str:
return f"values: {required_param}, {optional_param}"
# Transform without changing required status
new_tool = Tool.from_tool(
base_tool,
transform_args={
"required_param": ArgTransform(name="req"),
"optional_param": ArgTransform(name="opt"),
},
)
# Required status should be unchanged
assert "req" in new_tool.parameters["required"]
assert "opt" not in new_tool.parameters["required"]
assert new_tool.parameters["properties"]["opt"]["default"] == 42
# Should work as expected
result = await new_tool.run(arguments={"req": 1})
assert result[0].text == "values: 1, 42" # type: ignore
async def test_arg_transform_hide_and_required_raises_error():
"""Test that hide=True and required=True together raises an error."""
with pytest.raises(
ValueError, match="Cannot specify both 'hide=True' and 'required=True'"
):
ArgTransform(hide=True, required=True)
class TestEnableDisable:
async def test_transform_disabled_tool(self):
"""
Tests that a transformed tool can run even if the parent tool is disabled
"""
mcp = FastMCP()
@mcp.tool(enabled=False)
def add(x: int, y: int = 10) -> int:
return x + y
new_add = Tool.from_tool(add, name="new_add")
mcp.add_tool(new_add)
assert new_add.enabled
async with Client(mcp) as client:
tools = await client.list_tools()
assert {tool.name for tool in tools} == {"new_add"}
result = await client.call_tool("new_add", {"x": 1, "y": 2})
assert result[0].text == "3" # type: ignore[attr-defined]
with pytest.raises(ToolError):
await client.call_tool("add", {"x": 1, "y": 2})
async def test_disable_transformed_tool(self):
mcp = FastMCP()
@mcp.tool(enabled=False)
def add(x: int, y: int = 10) -> int:
return x + y
new_add = Tool.from_tool(add, name="new_add", enabled=False)
mcp.add_tool(new_add)
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 0
with pytest.raises(ToolError):
await client.call_tool("new_add", {"x": 1, "y": 2})

View file

@ -1,6 +1,8 @@
import inspect
from pathlib import Path
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.auth.oauth import OAuthClientProvider
from fastmcp.client.client import Client
from fastmcp.client.transports import (
SSETransport,
@ -136,3 +138,60 @@ async def test_multi_client(tmp_path: Path):
result_2 = await client.call_tool("test_2_add", {"a": 1, "b": 2})
assert result_1[0].text == "3" # type: ignore[attr-dict]
assert result_2[0].text == "3" # type: ignore[attr-dict]
async def test_remote_config_default_no_auth():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert client.transport.transport.auth is None
async def test_remote_config_with_auth_token():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
"auth": "test_token",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert isinstance(client.transport.transport.auth, BearerAuth)
assert client.transport.transport.auth.token.get_secret_value() == "test_token"
async def test_remote_config_sse_with_auth_token():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000/sse",
"auth": "test_token",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, SSETransport)
assert isinstance(client.transport.transport.auth, BearerAuth)
assert client.transport.transport.auth.token.get_secret_value() == "test_token"
async def test_remote_config_with_oauth_literal():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
"auth": "oauth",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert isinstance(client.transport.transport.auth, OAuthClientProvider)

View file

@ -1,4 +1,5 @@
import base64
from types import EllipsisType
from typing import Annotated, Any
import pytest
@ -308,6 +309,14 @@ class TestFindKwargByType:
assert find_kwarg_by_type(func, SENTINEL) is None # type: ignore
def test_ellipsis_annotation(self):
"""Test finding parameter with an ellipsis annotation."""
def func(a: int, b: EllipsisType, c: str): # type: ignore # noqa: F821
pass
assert find_kwarg_by_type(func, EllipsisType) == "b" # type: ignore
def test_missing_type_annotation(self):
"""Test finding parameter with a missing type annotation."""