mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-09 15:19:10 +02:00
Merge branch 'main' into include-exclude
This commit is contained in:
commit
ad45f0572a
70 changed files with 6155 additions and 734 deletions
20
.github/dependabot.yml
vendored
Normal file
20
.github/dependabot.yml
vendored
Normal 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
10
.github/release.yml
vendored
|
|
@ -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:
|
||||
- "*"
|
||||
|
|
|
|||
2
.github/workflows/publish.yml
vendored
2
.github/workflows/publish.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
2
.github/workflows/run-static.yml
vendored
2
.github/workflows/run-static.yml
vendored
|
|
@ -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"
|
||||
|
|
|
|||
2
.github/workflows/run-tests.yml
vendored
2
.github/workflows/run-tests.yml
vendored
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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/)*
|
||||
|
||||
[](https://gofastmcp.com)
|
||||
[](https://pypi.org/project/fastmcp)
|
||||
[](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml)
|
||||
|
|
|
|||
BIN
docs/assets/images/tutorial-rest-api-result.png
Normal file
BIN
docs/assets/images/tutorial-rest-api-result.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 645 KiB |
BIN
docs/assets/updates/release-2-7.png
Normal file
BIN
docs/assets/updates/release-2-7.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 412 KiB |
1062
docs/changelog.mdx
Normal file
1062
docs/changelog.mdx
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -102,7 +102,7 @@ OAuth access tokens are automatically cached in `~/.fastmcp/oauth-mcp-client-cac
|
|||
To clear the tokens for a specific server, instantiate a `FileTokenStorage` instance and call the `clear` method:
|
||||
|
||||
```python
|
||||
from fastmcp.client.auth import FileTokenStorage
|
||||
from fastmcp.client.auth.oauth import FileTokenStorage
|
||||
|
||||
storage = FileTokenStorage(server_url="https://fastmcp.cloud/mcp")
|
||||
await storage.clear()
|
||||
|
|
@ -111,7 +111,7 @@ await storage.clear()
|
|||
To clear *all* tokens for all servers, call the `clear_all` method on the `FileTokenStorage` class:
|
||||
|
||||
```python
|
||||
from fastmcp.client.auth import FileTokenStorage
|
||||
from fastmcp.client.auth.oauth import FileTokenStorage
|
||||
|
||||
FileTokenStorage.clear_all()
|
||||
```
|
||||
```
|
||||
|
|
|
|||
151
docs/docs.json
151
docs/docs.json
|
|
@ -19,14 +19,6 @@
|
|||
"light": "#4cc9f0",
|
||||
"primary": "#2d00f7"
|
||||
},
|
||||
"contextual": {
|
||||
"options": [
|
||||
"copy",
|
||||
"view",
|
||||
"chatgpt",
|
||||
"claude"
|
||||
]
|
||||
},
|
||||
"description": "The fast, Pythonic way to build MCP servers and clients.",
|
||||
"favicon": {
|
||||
"dark": "/assets/favicon.ico",
|
||||
|
|
@ -52,83 +44,106 @@
|
|||
}
|
||||
},
|
||||
"navigation": {
|
||||
"groups": [
|
||||
"anchors": [
|
||||
{
|
||||
"group": "Get Started",
|
||||
"pages": [
|
||||
"getting-started/welcome",
|
||||
"getting-started/installation",
|
||||
"getting-started/quickstart",
|
||||
"updates"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Servers",
|
||||
"pages": [
|
||||
"servers/fastmcp",
|
||||
"anchor": "Documentation",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Core Components",
|
||||
"icon": "toolbox",
|
||||
"group": "Get Started",
|
||||
"pages": [
|
||||
"servers/tools",
|
||||
"servers/resources",
|
||||
"servers/prompts",
|
||||
"servers/context"
|
||||
"getting-started/welcome",
|
||||
"getting-started/installation",
|
||||
"getting-started/quickstart",
|
||||
"updates"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Authentication",
|
||||
"icon": "shield-check",
|
||||
"group": "Servers",
|
||||
"pages": [
|
||||
"servers/auth/bearer"
|
||||
"servers/fastmcp",
|
||||
{
|
||||
"group": "Core Components",
|
||||
"icon": "toolbox",
|
||||
"pages": [
|
||||
"servers/tools",
|
||||
"servers/resources",
|
||||
"servers/prompts",
|
||||
"servers/context"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Authentication",
|
||||
"icon": "shield-check",
|
||||
"pages": [
|
||||
"servers/auth/bearer"
|
||||
]
|
||||
},
|
||||
"servers/openapi",
|
||||
"servers/proxy",
|
||||
"servers/composition",
|
||||
{
|
||||
"group": "Deployment",
|
||||
"icon": "upload",
|
||||
"pages": [
|
||||
"deployment/running-server",
|
||||
"deployment/asgi"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"servers/openapi",
|
||||
"servers/proxy",
|
||||
"servers/composition",
|
||||
{
|
||||
"group": "Deployment",
|
||||
"icon": "upload",
|
||||
"group": "Clients",
|
||||
"pages": [
|
||||
"deployment/running-server",
|
||||
"deployment/asgi"
|
||||
"clients/client",
|
||||
"clients/transports",
|
||||
{
|
||||
"group": "Authentication",
|
||||
"icon": "user-shield",
|
||||
"pages": [
|
||||
"clients/auth/oauth",
|
||||
"clients/auth/bearer"
|
||||
]
|
||||
},
|
||||
"clients/advanced-features"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Integrations",
|
||||
"pages": [
|
||||
"integrations/anthropic",
|
||||
"integrations/claude-desktop",
|
||||
"integrations/openai",
|
||||
"integrations/gemini",
|
||||
"integrations/contrib"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Patterns",
|
||||
"pages": [
|
||||
"patterns/tool-transformation",
|
||||
"patterns/decorating-methods",
|
||||
"patterns/http-requests",
|
||||
"patterns/testing",
|
||||
"patterns/cli"
|
||||
]
|
||||
}
|
||||
],
|
||||
"icon": "book"
|
||||
},
|
||||
{
|
||||
"anchor": "Tutorials",
|
||||
"icon": "graduation-cap",
|
||||
"pages": [
|
||||
"tutorials/mcp",
|
||||
"tutorials/create-mcp-server",
|
||||
"tutorials/rest-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Clients",
|
||||
"anchor": "Changelog",
|
||||
"icon": "list-check",
|
||||
"pages": [
|
||||
"clients/client",
|
||||
"clients/transports",
|
||||
{
|
||||
"group": "Authentication",
|
||||
"icon": "user-shield",
|
||||
"pages": [
|
||||
"clients/auth/oauth",
|
||||
"clients/auth/bearer"
|
||||
]
|
||||
},
|
||||
"clients/advanced-features"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Integrations",
|
||||
"pages": [
|
||||
"integrations/anthropic",
|
||||
"integrations/claude-desktop",
|
||||
"integrations/openai",
|
||||
"integrations/gemini",
|
||||
"integrations/contrib"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Patterns",
|
||||
"pages": [
|
||||
"patterns/decorating-methods",
|
||||
"patterns/http-requests",
|
||||
"patterns/testing",
|
||||
"patterns/cli"
|
||||
"changelog"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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,11 +59,18 @@ 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`
|
||||
|
||||
|
||||
## LLM-Friendly Docs
|
||||
|
||||
This documentation is also available in [llms.txt format](https://llmstxt.org/), which is a simple markdown standard that LLMs can consume easily.
|
||||
|
||||
There are two ways to access the LLM-friendly documentation:
|
||||
- [`llms.txt`](https://gofastmcp.com/llms.txt) is essentially a sitemap, listing all the pages in the documentation.
|
||||
- [`llms-full.txt`](https://gofastmcp.com/llms-full.txt) contains the entire documentation. Note this may exceed the context window of your LLM.
|
||||
- [llms.txt](https://gofastmcp.com/llms.txt) is essentially a sitemap, listing all the pages in the documentation.
|
||||
- [llms-full.txt](https://gofastmcp.com/llms-full.txt) contains the entire documentation. Note this may exceed the context window of your LLM.
|
||||
|
||||
In addition, any page can be accessed as markdown by appending `.md` to the URL. For example, this page would become `https://gofastmcp.com/getting-started/welcome.md`, which you can view [here](/getting-started/welcome.md).
|
||||
|
||||
Finally, you can copy the contents of any page as markdown by pressing "Cmd+C" (or "Ctrl+C" on Windows) on your keyboard.
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: Claude Desktop
|
||||
title: Claude Desktop + FastMCP
|
||||
sidebarTitle: Claude Desktop
|
||||
description: Call FastMCP servers from Claude Desktop
|
||||
icon: desktop
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ FastMCP includes a `contrib` package that holds community-contributed modules. T
|
|||
|
||||
Contrib modules provide additional features, integrations, or patterns that complement the core FastMCP library. They offer a way for the community to share useful extensions while keeping the core library focused and maintainable.
|
||||
|
||||
The available modules can be viewed in the [contrib directory](https://github.com/jlowin/fastmcp/tree/main/src/contrib).
|
||||
The available modules can be viewed in the [contrib directory](https://github.com/jlowin/fastmcp/tree/main/src/fastmcp/contrib).
|
||||
|
||||
## Usage
|
||||
|
||||
|
|
|
|||
|
|
@ -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>"),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
454
docs/patterns/tool-transformation.mdx
Normal file
454
docs/patterns/tool-transformation.mdx
Normal 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.
|
||||
|
|
@ -215,7 +215,7 @@ You can configure the prefix format globally in code:
|
|||
|
||||
```python
|
||||
import fastmcp
|
||||
fastmcp.settings.settings.resource_prefix_format = "protocol"
|
||||
fastmcp.settings.resource_prefix_format = "protocol"
|
||||
```
|
||||
|
||||
Or via environment variable:
|
||||
|
|
|
|||
|
|
@ -41,17 +41,9 @@ That's it! Your entire API is now available as an MCP server. Clients can discov
|
|||
|
||||
## Route Mapping
|
||||
|
||||
By default, FastMCP converts **every endpoint** in your OpenAPI specification into an MCP **Tool**. This provides a simple, predictable starting point that ensures all your API's functionality is immediately available to the vast majority of LLM clients which only support MCP tools.
|
||||
|
||||
|
||||
FastMCP analyzes your API specification and automatically creates MCP components based on HTTP semantics and REST conventions. By default, the following rules are used to determine what MCP component to create for each route:
|
||||
|
||||
| OpenAPI Route | Example | MCP Component |
|
||||
|---------------|---------|---------------|
|
||||
| `GET` with path params | `GET /users/{id}` | **Resource Template** |
|
||||
| `GET` without path params | `GET /stats` | **Resource** |
|
||||
| `POST`, `PUT`, `PATCH`, `DELETE`, etc. | `POST /users` | **Tool** |
|
||||
|
||||
Interally, FastMCP uses an ordered list of `RouteMap` objects to determine how to map OpenAPI routes to various MCP component types.
|
||||
While this is a pragmatic default for maximum compatibility, you can easily customize this behavior. Internally, FastMCP uses an ordered list of `RouteMap` objects to determine how to map OpenAPI routes to various MCP component types.
|
||||
|
||||
Each `RouteMap` specifies a combination of methods, patterns, and tags, as well as a corresponding MCP component type. Each OpenAPI route is checked against each `RouteMap` in order, and the first one that matches every criteria is used to determine its converted MCP type. A special type, `EXCLUDE`, can be used to exclude routes from the MCP server entirely.
|
||||
|
||||
|
|
@ -60,33 +52,14 @@ Each `RouteMap` specifies a combination of methods, patterns, and tags, as well
|
|||
- **Tags**: A set of OpenAPI tags that must all be present. An empty set (`{}`) means no tag filtering, so the route matches regardless of its tags.
|
||||
- **MCP type**: What MCP component type to create (`TOOL`, `RESOURCE`, `RESOURCE_TEMPLATE`, or `EXCLUDE`)
|
||||
|
||||
To illustrate this in practice, here are FastMCP's default rules as a list of `RouteMap` objects:
|
||||
Here is FastMCP's default rule:
|
||||
|
||||
```python
|
||||
from fastmcp.server.openapi import RouteMap, MCPType
|
||||
|
||||
DEFAULT_ROUTE_MAPPINGS = [
|
||||
|
||||
# GET with path parameters → ResourceTemplate
|
||||
RouteMap(
|
||||
methods=["GET"],
|
||||
pattern=r".*\{.*\}.*",
|
||||
mcp_type=MCPType.RESOURCE_TEMPLATE
|
||||
),
|
||||
|
||||
# GET without path parameters → Resource
|
||||
RouteMap(
|
||||
methods=["GET"],
|
||||
pattern=r".*",
|
||||
mcp_type=MCPType.RESOURCE
|
||||
),
|
||||
|
||||
# All other methods → Tool
|
||||
RouteMap(
|
||||
methods=["*"],
|
||||
pattern=r".*",
|
||||
mcp_type=MCPType.TOOL
|
||||
),
|
||||
# All routes become tools
|
||||
RouteMap(mcp_type=MCPType.TOOL),
|
||||
]
|
||||
```
|
||||
|
||||
|
|
@ -94,20 +67,28 @@ DEFAULT_ROUTE_MAPPINGS = [
|
|||
|
||||
When creating your FastMCP server, you can customize routing behavior by providing your own list of `RouteMap` objects. Your custom maps are processed before the default route maps, and routes will be assigned to the first matching custom map.
|
||||
|
||||
For example, the following simple rule will treat every OpenAPI route as a tool:
|
||||
For example, prior to FastMCP 2.8.0, GET requests were automatically mapped to `Resource` and `ResourceTemplate` components based on whether they had path parameters. (This was changed solely for client compatibility reasons.) You can restore this behavior by providing custom route maps:
|
||||
|
||||
```python {7}
|
||||
```python {2, 5-10}
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.openapi import RouteMap, MCPType
|
||||
|
||||
# Restore pre-2.8.0 semantic mapping
|
||||
semantic_maps = [
|
||||
# GET requests with path parameters become ResourceTemplates
|
||||
RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE),
|
||||
# All other GET requests become Resources
|
||||
RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
|
||||
]
|
||||
|
||||
mcp = FastMCP.from_openapi(
|
||||
...,
|
||||
route_maps=[
|
||||
RouteMap(mcp_type=MCPType.TOOL),
|
||||
],
|
||||
route_maps=semantic_maps,
|
||||
)
|
||||
```
|
||||
|
||||
With these maps, `GET` requests are handled semantically, and all other methods (`POST`, `PUT`, etc.) will fall through to the default rule and become `Tool`s.
|
||||
|
||||
Here is a more complete example that uses custom route maps to convert all `GET` endpoints under `/analytics/` to tools while excluding all admin endpoints and all routes tagged "internal". All other routes will be handled by the default rules:
|
||||
|
||||
```python
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
198
docs/tutorials/create-mcp-server.mdx
Normal file
198
docs/tutorials/create-mcp-server.mdx
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
---
|
||||
title: "How to Create an MCP Server in Python"
|
||||
sidebarTitle: "Creating an MCP Server"
|
||||
description: "A step-by-step guide to building a Model Context Protocol (MCP) server using Python and FastMCP, from basic tools to dynamic resources."
|
||||
icon: server
|
||||
---
|
||||
|
||||
So you want to build a Model Context Protocol (MCP) server in Python. The goal is to create a service that can provide tools and data to AI models like Claude, Gemini, or others that support the protocol. While the [MCP specification](https://modelcontextprotocol.io/specification/) is powerful, implementing it from scratch involves a lot of boilerplate: handling JSON-RPC, managing session state, and correctly formatting requests and responses.
|
||||
|
||||
This is where **FastMCP** comes in. It's a high-level framework that handles all the protocol complexities for you, letting you focus on what matters: writing the Python functions that power your server.
|
||||
|
||||
This guide will walk you through creating a fully-featured MCP server from scratch using FastMCP.
|
||||
|
||||
<Tip>
|
||||
Every code block in this tutorial is a complete, runnable example. You can copy and paste it into a file and run it, or paste it directly into a Python REPL like IPython to try it out.
|
||||
</Tip>
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Make sure you have FastMCP installed. If not, follow the [installation guide](/getting-started/installation).
|
||||
|
||||
```bash
|
||||
pip install fastmcp
|
||||
```
|
||||
|
||||
|
||||
## Step 1: Create the Basic Server
|
||||
|
||||
Every FastMCP application starts with an instance of the `FastMCP` class. This object acts as the container for all your tools and resources.
|
||||
|
||||
Create a new file called `my_mcp_server.py`:
|
||||
|
||||
```python my_mcp_server.py
|
||||
from fastmcp import FastMCP
|
||||
|
||||
# Create a server instance with a descriptive name
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
```
|
||||
|
||||
That's it! You have a valid (though empty) MCP server. Now, let's add some functionality.
|
||||
|
||||
## Step 2: Add a Tool
|
||||
|
||||
Tools are functions that an LLM can execute. Let's create a simple tool that adds two numbers.
|
||||
|
||||
To do this, simply write a standard Python function and decorate it with `@mcp.tool`.
|
||||
|
||||
```python my_mcp_server.py {5-8}
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
|
||||
@mcp.tool
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Adds two integer numbers together."""
|
||||
return a + b
|
||||
```
|
||||
|
||||
FastMCP automatically handles the rest:
|
||||
- **Tool Name:** It uses the function name (`add`) as the tool's name.
|
||||
- **Description:** It uses the function's docstring as the tool's description for the LLM.
|
||||
- **Schema:** It inspects the type hints (`a: int`, `b: int`) to generate a JSON schema for the inputs.
|
||||
|
||||
This is the core philosophy of FastMCP: **write Python, not protocol boilerplate.**
|
||||
|
||||
## Step 3: Expose Data with Resources
|
||||
|
||||
Resources provide read-only data to the LLM. You can define a resource by decorating a function with `@mcp.resource`, providing a unique URI.
|
||||
|
||||
Let's expose a simple configuration dictionary as a resource.
|
||||
|
||||
```python my_mcp_server.py {10-13}
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
|
||||
@mcp.tool
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Adds two integer numbers together."""
|
||||
return a + b
|
||||
|
||||
@mcp.resource("resource://config")
|
||||
def get_config() -> dict:
|
||||
"""Provides the application's configuration."""
|
||||
return {"version": "1.0", "author": "MyTeam"}
|
||||
```
|
||||
|
||||
When a client requests the URI `resource://config`, FastMCP will execute the `get_config` function and return its output (serialized as JSON) to the client. The function is only called when the resource is requested, enabling lazy-loading of data.
|
||||
|
||||
## Step 4: Generate Dynamic Content with Resource Templates
|
||||
|
||||
Sometimes, you need to generate resources based on parameters. This is what **Resource Templates** are for. You define them using the same `@mcp.resource` decorator but with placeholders in the URI.
|
||||
|
||||
Let's create a template that provides a personalized greeting.
|
||||
|
||||
```python my_mcp_server.py {15-17}
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
|
||||
@mcp.tool
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Adds two integer numbers together."""
|
||||
return a + b
|
||||
|
||||
@mcp.resource("resource://config")
|
||||
def get_config() -> dict:
|
||||
"""Provides the application's configuration."""
|
||||
return {"version": "1.0", "author": "MyTeam"}
|
||||
|
||||
@mcp.resource("greetings://{name}")
|
||||
def personalized_greeting(name: str) -> str:
|
||||
"""Generates a personalized greeting for the given name."""
|
||||
return f"Hello, {name}! Welcome to the MCP server."
|
||||
```
|
||||
|
||||
Now, clients can request dynamic URIs:
|
||||
- `greetings://Ford` will call `personalized_greeting(name="Ford")`.
|
||||
- `greetings://Marvin` will call `personalized_greeting(name="Marvin")`.
|
||||
|
||||
FastMCP automatically maps the `{name}` placeholder in the URI to the `name` parameter in your function.
|
||||
|
||||
## Step 5: Run the Server
|
||||
|
||||
To make your server executable, add a `__main__` block to your script that calls `mcp.run()`.
|
||||
|
||||
```python my_mcp_server.py {19-20}
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
|
||||
@mcp.tool
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Adds two integer numbers together."""
|
||||
return a + b
|
||||
|
||||
@mcp.resource("resource://config")
|
||||
def get_config() -> dict:
|
||||
"""Provides the application's configuration."""
|
||||
return {"version": "1.0", "author": "MyTeam"}
|
||||
|
||||
@mcp.resource("greetings://{name}")
|
||||
def personalized_greeting(name: str) -> str:
|
||||
"""Generates a personalized greeting for the given name."""
|
||||
return f"Hello, {name}! Welcome to the MCP server."
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
```
|
||||
|
||||
Now you can run your server from the command line:
|
||||
```bash
|
||||
python my_mcp_server.py
|
||||
```
|
||||
This starts the server using the default **STDIO transport**, which is how clients like Claude Desktop communicate with local servers. To learn about other transports, like HTTP, see the [Running Your Server](/deployment/running-server) guide.
|
||||
|
||||
## The Complete Server
|
||||
|
||||
Here is the full code for `my_mcp_server.py` (click to expand):
|
||||
|
||||
```python my_mcp_server.py [expandable]
|
||||
from fastmcp import FastMCP
|
||||
|
||||
# 1. Create the server
|
||||
mcp = FastMCP(name="My First MCP Server")
|
||||
|
||||
# 2. Add a tool
|
||||
@mcp.tool
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Adds two integer numbers together."""
|
||||
return a + b
|
||||
|
||||
# 3. Add a static resource
|
||||
@mcp.resource("resource://config")
|
||||
def get_config() -> dict:
|
||||
"""Provides the application's configuration."""
|
||||
return {"version": "1.0", "author": "MyTeam"}
|
||||
|
||||
# 4. Add a resource template for dynamic content
|
||||
@mcp.resource("greetings://{name}")
|
||||
def personalized_greeting(name: str) -> str:
|
||||
"""Generates a personalized greeting for the given name."""
|
||||
return f"Hello, {name}! Welcome to the MCP server."
|
||||
|
||||
# 5. Make the server runnable
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
You've successfully built an MCP server! From here, you can explore more advanced topics:
|
||||
|
||||
- [**Tools in Depth**](/servers/tools): Learn about asynchronous tools, error handling, and custom return types.
|
||||
- [**Resources & Templates**](/servers/resources): Discover different resource types, including files and HTTP endpoints.
|
||||
- [**Prompts**](/servers/prompts): Create reusable prompt templates for your LLM.
|
||||
- [**Running Your Server**](/deployment/running-server): Deploy your server with different transports like HTTP.
|
||||
|
||||
120
docs/tutorials/mcp.mdx
Normal file
120
docs/tutorials/mcp.mdx
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
---
|
||||
title: "What is the Model Context Protocol (MCP)?"
|
||||
sidebarTitle: "What is MCP?"
|
||||
description: "An introduction to the core concepts of the Model Context Protocol (MCP), explaining what it is, why it's useful, and how it works."
|
||||
icon: "diagram-project"
|
||||
---
|
||||
|
||||
The Model Context Protocol (MCP) is an open standard designed to solve a fundamental problem in AI development: how can Large Language Models (LLMs) reliably and securely interact with external tools, data, and services?
|
||||
|
||||
It's the **bridge between the probabilistic, non-deterministic world of AI and the deterministic, reliable world of your code and data.**
|
||||
|
||||
While you could build a custom REST API for your LLM, MCP provides a specialized, standardized "port" for AI-native communication. Think of it as **USB-C for AI**: a single, well-defined interface for connecting any compliant LLM to any compliant tool or data source.
|
||||
|
||||
This guide provides a high-level overview of the protocol itself. We'll use **FastMCP**, the leading Python framework for MCP, to illustrate the concepts with simple code examples.
|
||||
|
||||
## Why Do We Need a Protocol?
|
||||
|
||||
With countless APIs already in existence, the most common question is: "Why do we need another one?"
|
||||
|
||||
The answer lies in **standardization**. The AI ecosystem is fragmented. Every model provider has its own way of defining and calling tools. MCP's goal is to create a common language that offers several key advantages:
|
||||
|
||||
1. **Interoperability:** Build one MCP server, and it can be used by any MCP-compliant client (Claude, Gemini, OpenAI, custom agents, etc.) without custom integration code. This is the protocol's most important promise.
|
||||
2. **Discoverability:** Clients can dynamically ask a server what it's capable of at runtime. They receive a structured, machine-readable "menu" of tools and resources.
|
||||
3. **Security & Safety:** MCP provides a clear, sandboxed boundary. An LLM can't execute arbitrary code on your server; it can only *request* to run the specific, typed, and validated functions you explicitly expose.
|
||||
4. **Composability:** You can build small, specialized MCP servers and combine them to create powerful, complex applications.
|
||||
|
||||
## Core MCP Components
|
||||
|
||||
An MCP server exposes its capabilities through three primary components: Tools, Resources, and Prompts.
|
||||
|
||||
### Tools: Executable Actions
|
||||
|
||||
Tools are functions that the LLM can ask the server to execute. They are the action-oriented part of MCP.
|
||||
|
||||
In the spirit of a REST API, you can think of **Tools as being like `POST` requests.** They are used to *perform an action*, *change state*, or *trigger a side effect*, like sending an email, adding a user to a database, or making a calculation.
|
||||
|
||||
With FastMCP, creating a tool is as simple as decorating a Python function.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP()
|
||||
|
||||
# This function is now an MCP tool named "get_weather"
|
||||
@mcp.tool
|
||||
def get_weather(city: str) -> dict:
|
||||
"""Gets the current weather for a specific city."""
|
||||
# In a real app, this would call a weather API
|
||||
return {"city": city, "temperature": "72F", "forecast": "Sunny"}
|
||||
```
|
||||
|
||||
[**Learn more about Tools →**](/servers/tools)
|
||||
|
||||
### Resources: Read-Only Data
|
||||
|
||||
Resources are data sources that the LLM can read. They are used to load information into the LLM's context, providing it with knowledge it doesn't have from its training data.
|
||||
|
||||
Following the REST API analogy, **Resources are like `GET` requests.** Their purpose is to *retrieve information* idempotently, ideally without causing side effects. A resource can be anything from a static text file to a dynamic piece of data from a database. Each resource is identified by a unique URI.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP()
|
||||
|
||||
# This function provides a resource at the URI "system://status"
|
||||
@mcp.resource("system://status")
|
||||
def get_system_status() -> dict:
|
||||
"""Returns the current operational status of the service."""
|
||||
return {"status": "all systems normal"}
|
||||
```
|
||||
|
||||
#### Resource Templates
|
||||
|
||||
You can also create **Resource Templates** for dynamic data. A client could request `users://42/profile` to get the profile for a specific user.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP()
|
||||
|
||||
# This template provides user data for any given user ID
|
||||
@mcp.resource("users://{user_id}/profile")
|
||||
def get_user_profile(user_id: str) -> dict:
|
||||
"""Returns the profile for a specific user."""
|
||||
# Fetch user from a database...
|
||||
return {"id": user_id, "name": "Zaphod Beeblebrox"}
|
||||
```
|
||||
|
||||
[**Learn more about Resources & Templates →**](/servers/resources)
|
||||
|
||||
### Prompts: Reusable Instructions
|
||||
|
||||
Prompts are reusable, parameterized message templates. They provide a way to define consistent, structured instructions that a client can request to guide the LLM's behavior for a specific task.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt
|
||||
def summarize_text(text_to_summarize: str) -> str:
|
||||
"""Creates a prompt asking the LLM to summarize a piece of text."""
|
||||
return f"""
|
||||
Please provide a concise, one-paragraph summary of the following text:
|
||||
|
||||
{text_to_summarize}
|
||||
"""
|
||||
```
|
||||
|
||||
[**Learn more about Prompts →**](/servers/prompts)
|
||||
|
||||
## Advanced Capabilities
|
||||
|
||||
Beyond the core components, MCP also supports more advanced interaction patterns, such as a server requesting that the *client's* LLM generate a completion (known as **sampling**), or a server sending asynchronous **notifications** to a client. These features enable more complex, bidirectional workflows and are fully supported by FastMCP.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you understand the core concepts of the Model Context Protocol, you're ready to start building. The best place to begin is our step-by-step tutorial.
|
||||
|
||||
[**Tutorial: How to Create an MCP Server in Python →**](/tutorials/create-mcp-server)
|
||||
203
docs/tutorials/rest-api.mdx
Normal file
203
docs/tutorials/rest-api.mdx
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
---
|
||||
title: "How to Connect an LLM to a REST API"
|
||||
sidebarTitle: "Connect LLMs to REST APIs"
|
||||
description: "A step-by-step guide to making any REST API with an OpenAPI spec available to LLMs using FastMCP."
|
||||
icon: "plug"
|
||||
---
|
||||
|
||||
You've built a powerful REST API, and now you want your LLM to be able to use it. Manually writing a wrapper function for every single endpoint is tedious, error-prone, and hard to maintain.
|
||||
|
||||
This is where **FastMCP** shines. If your API has an OpenAPI (or Swagger) specification, FastMCP can automatically convert your entire API into a fully-featured MCP server, making every endpoint available as a secure, typed tool for your AI model.
|
||||
|
||||
This guide will walk you through converting a public REST API into an MCP server in just a few lines of code.
|
||||
|
||||
<Tip>
|
||||
Every code block in this tutorial is a complete, runnable example. You can copy and paste it into a file and run it, or paste it directly into a Python REPL like IPython to try it out.
|
||||
</Tip>
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Make sure you have FastMCP installed. If not, follow the [installation guide](/getting-started/installation).
|
||||
|
||||
```bash
|
||||
pip install fastmcp
|
||||
```
|
||||
|
||||
## Step 1: Choose a Target API
|
||||
|
||||
For this tutorial, we'll use the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/), a free, fake online REST API for testing and prototyping. It's perfect because it's simple and has a public OpenAPI specification.
|
||||
|
||||
- **API Base URL:** `https://jsonplaceholder.typicode.com`
|
||||
- **OpenAPI Spec URL:** We'll use a community-provided spec for it.
|
||||
|
||||
## Step 2: Create the MCP Server
|
||||
|
||||
Now for the magic. We'll use `FastMCP.from_openapi`. This method takes an `httpx.AsyncClient` configured for your API and its OpenAPI specification, and automatically converts **every endpoint** into a callable MCP `Tool`.
|
||||
|
||||
<Tip>
|
||||
Learn more about working with OpenAPI specs in the [OpenAPI integration docs](/servers/openapi).
|
||||
</Tip>
|
||||
|
||||
<Note>
|
||||
For this tutorial, we'll use a simplified OpenAPI spec directly in the code. In a real project, you would typically load the spec from a URL or local file.
|
||||
</Note>
|
||||
|
||||
Create a file named `api_server.py`:
|
||||
|
||||
```python api_server.py {31-35}
|
||||
import httpx
|
||||
from fastmcp import FastMCP
|
||||
|
||||
# Create an HTTP client for the target API
|
||||
client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com")
|
||||
|
||||
# Define a simplified OpenAPI spec for JSONPlaceholder
|
||||
openapi_spec = {
|
||||
"openapi": "3.0.0",
|
||||
"info": {"title": "JSONPlaceholder API", "version": "1.0"},
|
||||
"paths": {
|
||||
"/users": {
|
||||
"get": {
|
||||
"summary": "Get all users",
|
||||
"operationId": "get_users",
|
||||
"responses": {"200": {"description": "A list of users."}}
|
||||
}
|
||||
},
|
||||
"/users/{id}": {
|
||||
"get": {
|
||||
"summary": "Get a user by ID",
|
||||
"operationId": "get_user_by_id",
|
||||
"parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
|
||||
"responses": {"200": {"description": "A single user."}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create the MCP server from the OpenAPI spec
|
||||
mcp = FastMCP.from_openapi(
|
||||
openapi_spec=openapi_spec,
|
||||
client=client,
|
||||
name="JSONPlaceholder MCP Server"
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
```
|
||||
|
||||
And that's it! With just a few lines of code, you've created an MCP server that exposes the entire JSONPlaceholder API as a collection of tools.
|
||||
|
||||
## Step 3: Test the Generated Server
|
||||
|
||||
Let's verify that our new MCP server works. We can use the `fastmcp.Client` to connect to it and inspect its tools.
|
||||
|
||||
<Tip>
|
||||
Learn more about the FastMCP client in the [client docs](/clients/client).
|
||||
</Tip>
|
||||
|
||||
Create a separate file, `api_client.py`:
|
||||
|
||||
```python api_client.py {2, 6, 9, 16}
|
||||
import asyncio
|
||||
from fastmcp import Client
|
||||
|
||||
async def main():
|
||||
# Connect to the MCP server we just created
|
||||
async with Client("http://127.0.0.1:8000/mcp") as client:
|
||||
|
||||
# List the tools that were automatically generated
|
||||
tools = await client.list_tools()
|
||||
print("Generated Tools:")
|
||||
for tool in tools:
|
||||
print(f"- {tool.name}")
|
||||
|
||||
# Call one of the generated tools
|
||||
print("\n\nCalling tool 'get_user_by_id'...")
|
||||
user = await client.call_tool("get_user_by_id", {"id": 1})
|
||||
print(f"Result:\n{user[0].text}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
First, run your server:
|
||||
```bash
|
||||
python api_server.py
|
||||
```
|
||||
|
||||
Then, in another terminal, run the client:
|
||||
```bash
|
||||
python api_client.py
|
||||
```
|
||||
|
||||
You should see a list of generated tools (`get_users`, `get_user_by_id`) and the result of calling the `get_user_by_id` tool, which fetches data from the live JSONPlaceholder API.
|
||||
|
||||

|
||||
|
||||
|
||||
## Step 4: Customizing Route Maps
|
||||
|
||||
By default, FastMCP converts every API endpoint into an MCP `Tool`. This ensures maximum compatibility with contemporary LLM clients, many of which **only support the `tools` part of the MCP specification.**
|
||||
|
||||
However, for clients that support the full MCP spec, representing `GET` requests as `Resources` can be more semantically correct and efficient.
|
||||
|
||||
FastMCP allows users to customize this behavior using the concept of "route maps". A `RouteMap` is a mapping of an API route to an MCP type. FastMCP checks each API route against your custom maps in order. If a route matches a map, it's converted to the specified `mcp_type`. Any route that doesn't match your custom maps will fall back to the default behavior (becoming a `Tool`).
|
||||
|
||||
<Tip>
|
||||
Learn more about route maps in the [OpenAPI integration docs](/servers/openapi#route-mapping).
|
||||
</Tip>
|
||||
|
||||
Here’s how you can add custom route maps to turn `GET` requests into `Resources` and `ResourceTemplates` (if they have path parameters):
|
||||
|
||||
```python api_server_with_resources.py {3, 37-42}
|
||||
import httpx
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.openapi import RouteMap, MCPType
|
||||
|
||||
|
||||
# Create an HTTP client for the target API
|
||||
client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com")
|
||||
|
||||
# Define a simplified OpenAPI spec for JSONPlaceholder
|
||||
openapi_spec = {
|
||||
"openapi": "3.0.0",
|
||||
"info": {"title": "JSONPlaceholder API", "version": "1.0"},
|
||||
"paths": {
|
||||
"/users": {
|
||||
"get": {
|
||||
"summary": "Get all users",
|
||||
"operationId": "get_users",
|
||||
"responses": {"200": {"description": "A list of users."}}
|
||||
}
|
||||
},
|
||||
"/users/{id}": {
|
||||
"get": {
|
||||
"summary": "Get a user by ID",
|
||||
"operationId": "get_user_by_id",
|
||||
"parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
|
||||
"responses": {"200": {"description": "A single user."}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create the MCP server with custom route mapping
|
||||
mcp = FastMCP.from_openapi(
|
||||
openapi_spec=openapi_spec,
|
||||
client=client,
|
||||
name="JSONPlaceholder MCP Server",
|
||||
route_maps=[
|
||||
# Map GET requests with path parameters (e.g., /users/{id}) to ResourceTemplate
|
||||
RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE),
|
||||
# Map all other GET requests to Resource
|
||||
RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE),
|
||||
]
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
```
|
||||
With this configuration:
|
||||
- `GET /users/{id}` becomes a `ResourceTemplate`.
|
||||
- `GET /users` becomes a `Resource`.
|
||||
- Any `POST`, `PUT`, etc. endpoints would still become `Tools` by default.
|
||||
130
docs/updates.mdx
130
docs/updates.mdx
|
|
@ -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. Here’s to what’s 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. It’s 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. FastMCP’s 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>
|
||||
|
||||
|
|
|
|||
|
|
@ -114,3 +114,5 @@ extend-select = ["I", "UP"]
|
|||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"__init__.py" = ["F401", "I001", "RUF013"]
|
||||
# allow imports not at the top of the file
|
||||
"src/fastmcp/__init__.py" = ["E402"]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
"""FastMCP - An ergonomic MCP interface."""
|
||||
|
||||
from importlib.metadata import version
|
||||
from fastmcp.settings import Settings
|
||||
|
||||
settings = Settings()
|
||||
|
||||
from fastmcp.server.server import FastMCP
|
||||
from fastmcp.server.context import Context
|
||||
|
|
@ -8,7 +11,7 @@ import fastmcp.server
|
|||
|
||||
from fastmcp.client import Client
|
||||
from fastmcp.utilities.types import Image
|
||||
from . import client, settings
|
||||
from . import client
|
||||
|
||||
__version__ = version("fastmcp")
|
||||
__all__ = [
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ from typer import Context, Exit
|
|||
import fastmcp
|
||||
from fastmcp.cli import claude
|
||||
from fastmcp.cli import run as run_module
|
||||
from fastmcp.server.server import FastMCP
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
|
||||
logger = get_logger("cli")
|
||||
|
|
@ -165,8 +166,8 @@ def dev(
|
|||
|
||||
try:
|
||||
# Import server to get dependencies
|
||||
server = run_module.import_server(file, server_object)
|
||||
if hasattr(server, "dependencies") and server.dependencies is not None:
|
||||
server: FastMCP = run_module.import_server(file, server_object)
|
||||
if server.dependencies is not None:
|
||||
with_packages = list(set(with_packages + server.dependencies))
|
||||
|
||||
env_vars = {}
|
||||
|
|
|
|||
|
|
@ -23,10 +23,10 @@ from mcp.shared.auth import (
|
|||
)
|
||||
from pydantic import AnyHttpUrl, ValidationError
|
||||
|
||||
from fastmcp import settings as fastmcp_global_settings
|
||||
from fastmcp.client.oauth_callback import (
|
||||
create_oauth_callback_server,
|
||||
)
|
||||
from fastmcp.settings import settings as fastmcp_global_settings
|
||||
from fastmcp.utilities.http import find_available_port
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
@ -165,7 +166,7 @@ class Client(Generic[ClientTransportT]):
|
|||
|
||||
# handle init handshake timeout
|
||||
if init_timeout is None:
|
||||
init_timeout = fastmcp.settings.settings.client_init_timeout
|
||||
init_timeout = fastmcp.settings.client_init_timeout
|
||||
if isinstance(init_timeout, datetime.timedelta):
|
||||
init_timeout = init_timeout.total_seconds()
|
||||
elif not init_timeout:
|
||||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -33,3 +33,7 @@ class ClientError(Exception):
|
|||
|
||||
class NotFoundError(Exception):
|
||||
"""Object not found."""
|
||||
|
||||
|
||||
class DisabledError(Exception):
|
||||
"""Object is disabled."""
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any
|
|||
|
||||
from mcp import GetPromptResult
|
||||
|
||||
from fastmcp import settings
|
||||
from fastmcp.exceptions import NotFoundError, PromptError
|
||||
from fastmcp.prompts.prompt import FunctionPrompt, Prompt, PromptResult
|
||||
from fastmcp.settings import DuplicateBehavior
|
||||
|
|
@ -23,10 +24,10 @@ class PromptManager:
|
|||
def __init__(
|
||||
self,
|
||||
duplicate_behavior: DuplicateBehavior | None = None,
|
||||
mask_error_details: bool = False,
|
||||
mask_error_details: bool | None = None,
|
||||
):
|
||||
self._prompts: dict[str, Prompt] = {}
|
||||
self.mask_error_details = mask_error_details
|
||||
self.mask_error_details = mask_error_details or settings.mask_error_details
|
||||
|
||||
# Default to "warn" if None is provided
|
||||
if duplicate_behavior is None:
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from typing import Any
|
|||
|
||||
from pydantic import AnyUrl
|
||||
|
||||
from fastmcp import settings
|
||||
from fastmcp.exceptions import NotFoundError, ResourceError
|
||||
from fastmcp.resources.resource import Resource
|
||||
from fastmcp.resources.template import (
|
||||
|
|
@ -25,7 +26,7 @@ class ResourceManager:
|
|||
def __init__(
|
||||
self,
|
||||
duplicate_behavior: DuplicateBehavior | None = None,
|
||||
mask_error_details: bool = False,
|
||||
mask_error_details: bool | None = None,
|
||||
):
|
||||
"""Initialize the ResourceManager.
|
||||
|
||||
|
|
@ -37,7 +38,7 @@ class ResourceManager:
|
|||
"""
|
||||
self._resources: dict[str, Resource] = {}
|
||||
self._templates: dict[str, ResourceTemplate] = {}
|
||||
self.mask_error_details = mask_error_details
|
||||
self.mask_error_details = mask_error_details or settings.mask_error_details
|
||||
|
||||
# Default to "warn" if None is provided
|
||||
if duplicate_behavior is None:
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -155,16 +155,10 @@ class RouteMap:
|
|||
self.route_type = self.mcp_type
|
||||
|
||||
|
||||
# Default route mappings as a list, where order determines priority
|
||||
# Default route mapping: all routes become tools.
|
||||
# Users can provide custom route_maps to override this behavior.
|
||||
DEFAULT_ROUTE_MAPPINGS = [
|
||||
# GET requests with path parameters go to ResourceTemplate
|
||||
RouteMap(
|
||||
methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE
|
||||
),
|
||||
# GET requests without path parameters go to Resource
|
||||
RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
|
||||
# All other HTTP methods go to Tool
|
||||
RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL),
|
||||
RouteMap(mcp_type=MCPType.TOOL),
|
||||
]
|
||||
|
||||
|
||||
|
|
@ -226,7 +220,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 +228,6 @@ class OpenAPITool(Tool):
|
|||
parameters=parameters,
|
||||
tags=tags,
|
||||
annotations=annotations,
|
||||
exclude_args=exclude_args,
|
||||
serializer=serializer,
|
||||
)
|
||||
self._client = client
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -43,8 +43,7 @@ from starlette.routing import BaseRoute, Route
|
|||
|
||||
import fastmcp
|
||||
import fastmcp.server
|
||||
import fastmcp.settings
|
||||
from fastmcp.exceptions import NotFoundError
|
||||
from fastmcp.exceptions import DisabledError, NotFoundError
|
||||
from fastmcp.prompts import Prompt, PromptManager
|
||||
from fastmcp.prompts.prompt import FunctionPrompt
|
||||
from fastmcp.resources import Resource, ResourceManager
|
||||
|
|
@ -56,9 +55,11 @@ from fastmcp.server.http import (
|
|||
create_sse_app,
|
||||
create_streamable_http_app,
|
||||
)
|
||||
from fastmcp.settings import Settings
|
||||
from fastmcp.tools import ToolManager
|
||||
from fastmcp.tools.tool import FunctionTool, Tool
|
||||
from fastmcp.utilities.cache import TimedCache
|
||||
from fastmcp.utilities.components import FastMCPComponent
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
from fastmcp.utilities.mcp_config import MCPConfig
|
||||
|
||||
|
|
@ -121,7 +122,6 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
| None
|
||||
) = None,
|
||||
tags: set[str] | None = None,
|
||||
dependencies: list[str] | None = None,
|
||||
tool_serializer: Callable[[Any], str] | None = None,
|
||||
cache_expiration_seconds: float | None = None,
|
||||
on_duplicate_tools: DuplicateBehavior | None = None,
|
||||
|
|
@ -130,6 +130,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
resource_prefix_format: Literal["protocol", "path"] | None = None,
|
||||
mask_error_details: bool | None = None,
|
||||
tools: list[Tool | Callable[..., Any]] | None = None,
|
||||
dependencies: list[str] | None = None,
|
||||
include_tags: set[str]
|
||||
| set[tuple[str, ...]]
|
||||
| set[str | tuple[str, ...]]
|
||||
|
|
@ -138,47 +139,43 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
| set[tuple[str, ...]]
|
||||
| set[str | tuple[str, ...]]
|
||||
| None = None,
|
||||
**settings: Any,
|
||||
# ---
|
||||
# ---
|
||||
# --- The following arguments are DEPRECATED ---
|
||||
# ---
|
||||
# ---
|
||||
log_level: str | None = None,
|
||||
debug: bool | None = None,
|
||||
host: str | None = None,
|
||||
port: int | None = None,
|
||||
sse_path: str | None = None,
|
||||
message_path: str | None = None,
|
||||
streamable_http_path: str | None = None,
|
||||
json_response: bool | None = None,
|
||||
stateless_http: bool | None = None,
|
||||
):
|
||||
if cache_expiration_seconds is not None:
|
||||
settings["cache_expiration_seconds"] = cache_expiration_seconds
|
||||
self.settings = fastmcp.settings.ServerSettings(
|
||||
include_tags=include_tags, exclude_tags=exclude_tags, **settings
|
||||
self.resource_prefix_format: Literal["protocol", "path"] = (
|
||||
resource_prefix_format or fastmcp.settings.resource_prefix_format
|
||||
)
|
||||
|
||||
# If mask_error_details is provided, override the settings value
|
||||
if mask_error_details is not None:
|
||||
self.settings.mask_error_details = mask_error_details
|
||||
|
||||
self.resource_prefix_format: Literal["protocol", "path"]
|
||||
if resource_prefix_format is None:
|
||||
self.resource_prefix_format = (
|
||||
fastmcp.settings.settings.resource_prefix_format
|
||||
)
|
||||
else:
|
||||
self.resource_prefix_format = resource_prefix_format
|
||||
|
||||
self.tags: set[str] = tags or set()
|
||||
|
||||
self.dependencies = dependencies
|
||||
self._cache = TimedCache(
|
||||
expiration=datetime.timedelta(
|
||||
seconds=self.settings.cache_expiration_seconds
|
||||
)
|
||||
expiration=datetime.timedelta(seconds=cache_expiration_seconds or 0)
|
||||
)
|
||||
self._mounted_servers: dict[str, MountedServer] = {}
|
||||
self._additional_http_routes: list[BaseRoute] = []
|
||||
self._tool_manager = ToolManager(
|
||||
duplicate_behavior=on_duplicate_tools,
|
||||
mask_error_details=self.settings.mask_error_details,
|
||||
mask_error_details=mask_error_details,
|
||||
)
|
||||
self._resource_manager = ResourceManager(
|
||||
duplicate_behavior=on_duplicate_resources,
|
||||
mask_error_details=self.settings.mask_error_details,
|
||||
mask_error_details=mask_error_details,
|
||||
)
|
||||
self._prompt_manager = PromptManager(
|
||||
duplicate_behavior=on_duplicate_prompts,
|
||||
mask_error_details=self.settings.mask_error_details,
|
||||
mask_error_details=mask_error_details,
|
||||
)
|
||||
self._tool_serializer = tool_serializer
|
||||
|
||||
|
|
@ -193,7 +190,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
lifespan=_lifespan_wrapper(self, lifespan),
|
||||
)
|
||||
|
||||
if auth is None and self.settings.default_auth_provider == "bearer_env":
|
||||
if auth is None and fastmcp.settings.default_auth_provider == "bearer_env":
|
||||
auth = EnvBearerAuthProvider()
|
||||
self.auth = auth
|
||||
|
||||
|
|
@ -203,12 +200,67 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
tool = Tool.from_function(tool, serializer=self._tool_serializer)
|
||||
self.add_tool(tool)
|
||||
|
||||
self.include_tags = include_tags
|
||||
self.exclude_tags = exclude_tags
|
||||
|
||||
# Set up MCP protocol handlers
|
||||
self._setup_handlers()
|
||||
self.dependencies = dependencies or fastmcp.settings.server_dependencies
|
||||
|
||||
# handle deprecated settings
|
||||
self._handle_deprecated_settings(
|
||||
log_level=log_level,
|
||||
debug=debug,
|
||||
host=host,
|
||||
port=port,
|
||||
sse_path=sse_path,
|
||||
message_path=message_path,
|
||||
streamable_http_path=streamable_http_path,
|
||||
json_response=json_response,
|
||||
stateless_http=stateless_http,
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"{type(self).__name__}({self.name!r})"
|
||||
|
||||
def _handle_deprecated_settings(
|
||||
self,
|
||||
log_level: str | None,
|
||||
debug: bool | None,
|
||||
host: str | None,
|
||||
port: int | None,
|
||||
sse_path: str | None,
|
||||
message_path: str | None,
|
||||
streamable_http_path: str | None,
|
||||
json_response: bool | None,
|
||||
stateless_http: bool | None,
|
||||
) -> None:
|
||||
"""Handle deprecated settings. Deprecated in 2.8.0."""
|
||||
deprecated_settings: dict[str, Any] = {}
|
||||
|
||||
for name, arg in [
|
||||
("log_level", log_level),
|
||||
("debug", debug),
|
||||
("host", host),
|
||||
("port", port),
|
||||
("sse_path", sse_path),
|
||||
("message_path", message_path),
|
||||
("streamable_http_path", streamable_http_path),
|
||||
("json_response", json_response),
|
||||
("stateless_http", stateless_http),
|
||||
]:
|
||||
if arg is not None:
|
||||
# Deprecated in 2.8.0
|
||||
warnings.warn(
|
||||
f"Providing `{name}` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
deprecated_settings[name] = arg
|
||||
|
||||
combined_settings = fastmcp.settings.model_dump() | deprecated_settings
|
||||
self._deprecated_settings = Settings(**combined_settings)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self._mcp_server.name
|
||||
|
|
@ -279,6 +331,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:
|
||||
|
|
@ -296,6 +354,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 (
|
||||
|
|
@ -316,6 +380,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.
|
||||
|
|
@ -335,6 +405,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,
|
||||
|
|
@ -389,7 +465,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
|
||||
mcp_tools: list[MCPTool] = []
|
||||
for key, tool in tools.items():
|
||||
if self.should_include_component(tool):
|
||||
if self._should_enable_component(tool):
|
||||
mcp_tools.append(tool.to_mcp_tool(name=key))
|
||||
|
||||
return mcp_tools
|
||||
|
|
@ -403,7 +479,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
resources = await self.get_resources()
|
||||
mcp_resources: list[MCPResource] = []
|
||||
for key, resource in resources.items():
|
||||
if self.should_include_component(resource):
|
||||
if self._should_enable_component(resource):
|
||||
mcp_resources.append(resource.to_mcp_resource(uri=key))
|
||||
return mcp_resources
|
||||
|
||||
|
|
@ -416,7 +492,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
templates = await self.get_resource_templates()
|
||||
mcp_templates: list[MCPResourceTemplate] = []
|
||||
for key, template in templates.items():
|
||||
if self.should_include_component(template):
|
||||
if self._should_enable_component(template):
|
||||
mcp_templates.append(template.to_mcp_template(uriTemplate=key))
|
||||
return mcp_templates
|
||||
|
||||
|
|
@ -429,14 +505,17 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
prompts = await self.get_prompts()
|
||||
mcp_prompts: list[MCPPrompt] = []
|
||||
for key, prompt in prompts.items():
|
||||
if self.should_include_component(prompt):
|
||||
if self._should_enable_component(prompt):
|
||||
mcp_prompts.append(prompt.to_mcp_prompt(name=key))
|
||||
return mcp_prompts
|
||||
|
||||
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
|
||||
|
|
@ -449,48 +528,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):
|
||||
tool = self._tool_manager.get_tool(key)
|
||||
if not self.should_include_component(tool):
|
||||
raise NotFoundError(f"Unknown 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)
|
||||
if not self.should_include_component(resource):
|
||||
raise NotFoundError(f"Unknown 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.
|
||||
|
||||
|
|
@ -503,22 +643,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):
|
||||
prompt = self._prompt_manager.get_prompt(name)
|
||||
if not self.should_include_component(prompt):
|
||||
raise NotFoundError(f"Unknown 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.
|
||||
|
|
@ -554,6 +692,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
|
||||
|
|
@ -566,6 +705,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(
|
||||
|
|
@ -577,6 +717,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.
|
||||
|
||||
|
|
@ -593,11 +734,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
|
||||
|
|
@ -650,6 +792,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
annotations=annotations,
|
||||
exclude_args=exclude_args,
|
||||
serializer=self._tool_serializer,
|
||||
enabled=enabled,
|
||||
)
|
||||
self.add_tool(tool)
|
||||
return tool
|
||||
|
|
@ -678,6 +821,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:
|
||||
|
|
@ -744,6 +888,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.
|
||||
|
||||
|
|
@ -766,6 +911,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")
|
||||
|
|
@ -830,6 +976,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
description=description,
|
||||
mime_type=mime_type,
|
||||
tags=tags,
|
||||
enabled=enabled,
|
||||
)
|
||||
self.add_template(template)
|
||||
return template
|
||||
|
|
@ -841,6 +988,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
description=description,
|
||||
mime_type=mime_type,
|
||||
tags=tags,
|
||||
enabled=enabled,
|
||||
)
|
||||
self.add_resource(resource)
|
||||
return resource
|
||||
|
|
@ -869,6 +1017,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
tags: set[str] | None = None,
|
||||
enabled: bool | None = None,
|
||||
) -> FunctionPrompt: ...
|
||||
|
||||
@overload
|
||||
|
|
@ -879,6 +1028,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(
|
||||
|
|
@ -888,6 +1038,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.
|
||||
|
||||
|
|
@ -897,16 +1048,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
|
||||
|
|
@ -919,7 +1071,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)
|
||||
|
|
@ -979,6 +1131,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
name=prompt_name,
|
||||
description=description,
|
||||
tags=tags,
|
||||
enabled=enabled,
|
||||
)
|
||||
self.add_prompt(prompt)
|
||||
|
||||
|
|
@ -1006,6 +1159,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
name=prompt_name,
|
||||
description=description,
|
||||
tags=tags,
|
||||
enabled=enabled,
|
||||
)
|
||||
|
||||
async def run_stdio_async(self) -> None:
|
||||
|
|
@ -1040,9 +1194,11 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
path: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path)
|
||||
uvicorn_config: Additional configuration for the Uvicorn server
|
||||
"""
|
||||
host = host or self.settings.host
|
||||
port = port or self.settings.port
|
||||
default_log_level_to_use = (log_level or self.settings.log_level).lower()
|
||||
host = host or self._deprecated_settings.host
|
||||
port = port or self._deprecated_settings.port
|
||||
default_log_level_to_use = (
|
||||
log_level or self._deprecated_settings.log_level
|
||||
).lower()
|
||||
|
||||
app = self.http_app(path=path, transport=transport, middleware=middleware)
|
||||
|
||||
|
|
@ -1116,10 +1272,10 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
)
|
||||
return create_sse_app(
|
||||
server=self,
|
||||
message_path=message_path or self.settings.message_path,
|
||||
sse_path=path or self.settings.sse_path,
|
||||
message_path=message_path or self._deprecated_settings.message_path,
|
||||
sse_path=path or self._deprecated_settings.sse_path,
|
||||
auth=self.auth,
|
||||
debug=self.settings.debug,
|
||||
debug=self._deprecated_settings.debug,
|
||||
middleware=middleware,
|
||||
)
|
||||
|
||||
|
|
@ -1147,6 +1303,8 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
self,
|
||||
path: str | None = None,
|
||||
middleware: list[Middleware] | None = None,
|
||||
json_response: bool | None = None,
|
||||
stateless_http: bool | None = None,
|
||||
transport: Literal["streamable-http", "sse"] = "streamable-http",
|
||||
) -> StarletteWithLifespan:
|
||||
"""Create a Starlette app using the specified HTTP transport.
|
||||
|
|
@ -1163,21 +1321,22 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
if transport == "streamable-http":
|
||||
return create_streamable_http_app(
|
||||
server=self,
|
||||
streamable_http_path=path or self.settings.streamable_http_path,
|
||||
streamable_http_path=path
|
||||
or self._deprecated_settings.streamable_http_path,
|
||||
event_store=None,
|
||||
auth=self.auth,
|
||||
json_response=self.settings.json_response,
|
||||
stateless_http=self.settings.stateless_http,
|
||||
debug=self.settings.debug,
|
||||
json_response=self._deprecated_settings.json_response,
|
||||
stateless_http=self._deprecated_settings.stateless_http,
|
||||
debug=self._deprecated_settings.debug,
|
||||
middleware=middleware,
|
||||
)
|
||||
elif transport == "sse":
|
||||
return create_sse_app(
|
||||
server=self,
|
||||
message_path=self.settings.message_path,
|
||||
sse_path=path or self.settings.sse_path,
|
||||
message_path=self._deprecated_settings.message_path,
|
||||
sse_path=path or self._deprecated_settings.sse_path,
|
||||
auth=self.auth,
|
||||
debug=self.settings.debug,
|
||||
debug=self._deprecated_settings.debug,
|
||||
middleware=middleware,
|
||||
)
|
||||
|
||||
|
|
@ -1408,28 +1567,12 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
route_map_fn: OpenAPIRouteMapFn | None = None,
|
||||
mcp_component_fn: OpenAPIComponentFn | None = None,
|
||||
mcp_names: dict[str, str] | None = None,
|
||||
all_routes_as_tools: bool = False,
|
||||
**settings: Any,
|
||||
) -> FastMCPOpenAPI:
|
||||
"""
|
||||
Create a FastMCP server from an OpenAPI specification.
|
||||
"""
|
||||
from .openapi import FastMCPOpenAPI, MCPType, RouteMap
|
||||
|
||||
# Deprecated since 2.5.0
|
||||
if all_routes_as_tools:
|
||||
warnings.warn(
|
||||
"The 'all_routes_as_tools' parameter is deprecated and will be removed in a future version. "
|
||||
'Use \'route_maps=[RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)]\' instead.',
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if all_routes_as_tools and route_maps:
|
||||
raise ValueError("Cannot specify both all_routes_as_tools and route_maps")
|
||||
|
||||
elif all_routes_as_tools:
|
||||
route_maps = [RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)]
|
||||
from .openapi import FastMCPOpenAPI
|
||||
|
||||
return FastMCPOpenAPI(
|
||||
openapi_spec=openapi_spec,
|
||||
|
|
@ -1450,7 +1593,6 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
route_map_fn: OpenAPIRouteMapFn | None = None,
|
||||
mcp_component_fn: OpenAPIComponentFn | None = None,
|
||||
mcp_names: dict[str, str] | None = None,
|
||||
all_routes_as_tools: bool = False,
|
||||
httpx_client_kwargs: dict[str, Any] | None = None,
|
||||
**settings: Any,
|
||||
) -> FastMCPOpenAPI:
|
||||
|
|
@ -1458,22 +1600,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
Create a FastMCP server from a FastAPI application.
|
||||
"""
|
||||
|
||||
from .openapi import FastMCPOpenAPI, MCPType, RouteMap
|
||||
|
||||
# Deprecated since 2.5.0
|
||||
if all_routes_as_tools:
|
||||
warnings.warn(
|
||||
"The 'all_routes_as_tools' parameter is deprecated and will be removed in a future version. "
|
||||
'Use \'route_maps=[RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)]\' instead.',
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if all_routes_as_tools and route_maps:
|
||||
raise ValueError("Cannot specify both all_routes_as_tools and route_maps")
|
||||
|
||||
elif all_routes_as_tools:
|
||||
route_maps = [RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)]
|
||||
from .openapi import FastMCPOpenAPI
|
||||
|
||||
if httpx_client_kwargs is None:
|
||||
httpx_client_kwargs = {}
|
||||
|
|
@ -1543,14 +1670,15 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
|
||||
return cls.as_proxy(client, **settings)
|
||||
|
||||
def should_include_component(
|
||||
def _should_enable_component(
|
||||
self,
|
||||
component: Tool | Resource | ResourceTemplate | Prompt,
|
||||
component: FastMCPComponent,
|
||||
) -> bool:
|
||||
"""
|
||||
Given a set of tags, determine if the tags match the include and exclude tags. Returns True if it should be included; False if it should not.
|
||||
Given a component, determine if it should be enabled. Returns True if it should be enabled; False if it should not.
|
||||
|
||||
Rules:
|
||||
• If the component's enabled property is False, always return False.
|
||||
• If both include_tags and exclude_tags are None, return True.
|
||||
• If exclude_tags is provided, check each exclude tag:
|
||||
- If the exclude tag is a tuple, all tags in the tuple must be present in the input tags to exclude.
|
||||
|
|
@ -1561,11 +1689,14 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
• If include_tags is provided and none of the include tags match, return False.
|
||||
• If include_tags is not provided, return True.
|
||||
"""
|
||||
if self.settings.include_tags is None and self.settings.exclude_tags is None:
|
||||
if not component.enabled:
|
||||
return False
|
||||
|
||||
if self.include_tags is None and self.exclude_tags is None:
|
||||
return True
|
||||
|
||||
if self.settings.exclude_tags is not None:
|
||||
for etag in self.settings.exclude_tags:
|
||||
if self.exclude_tags is not None:
|
||||
for etag in self.exclude_tags:
|
||||
if isinstance(etag, tuple):
|
||||
if all(et in component.tags for et in etag):
|
||||
return False
|
||||
|
|
@ -1573,8 +1704,8 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
if etag in component.tags:
|
||||
return False
|
||||
|
||||
if self.settings.include_tags is not None:
|
||||
for itag in self.settings.include_tags:
|
||||
if self.include_tags is not None:
|
||||
for itag in self.include_tags:
|
||||
if isinstance(itag, tuple):
|
||||
if all(it in component.tags for it in itag):
|
||||
return True
|
||||
|
|
@ -1672,7 +1803,7 @@ def add_resource_prefix(
|
|||
# Get the server settings to check for legacy format preference
|
||||
|
||||
if prefix_format is None:
|
||||
prefix_format = fastmcp.settings.settings.resource_prefix_format
|
||||
prefix_format = fastmcp.settings.resource_prefix_format
|
||||
|
||||
if prefix_format == "protocol":
|
||||
# Legacy style: prefix+protocol://path
|
||||
|
|
@ -1721,7 +1852,7 @@ def remove_resource_prefix(
|
|||
return uri
|
||||
|
||||
if prefix_format is None:
|
||||
prefix_format = fastmcp.settings.settings.resource_prefix_format
|
||||
prefix_format = fastmcp.settings.resource_prefix_format
|
||||
|
||||
if prefix_format == "protocol":
|
||||
# Legacy style: prefix+protocol://path
|
||||
|
|
@ -1781,7 +1912,7 @@ def has_resource_prefix(
|
|||
# Get the server settings to check for legacy format preference
|
||||
|
||||
if prefix_format is None:
|
||||
prefix_format = fastmcp.settings.settings.resource_prefix_format
|
||||
prefix_format = fastmcp.settings.resource_prefix_format
|
||||
|
||||
if prefix_format == "protocol":
|
||||
# Legacy style: prefix+protocol://path
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
from __future__ import annotations as _annotations
|
||||
|
||||
import inspect
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic.fields import FieldInfo
|
||||
from pydantic_settings import (
|
||||
BaseSettings,
|
||||
EnvSettingsSource,
|
||||
PydanticBaseSettingsSource,
|
||||
SettingsConfigDict,
|
||||
)
|
||||
from typing_extensions import Self
|
||||
|
|
@ -16,17 +20,82 @@ LOG_LEVEL = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
|
|||
DuplicateBehavior = Literal["warn", "error", "replace", "ignore"]
|
||||
|
||||
|
||||
class ExtendedEnvSettingsSource(EnvSettingsSource):
|
||||
"""
|
||||
A special EnvSettingsSource that allows for multiple env var prefixes to be used.
|
||||
|
||||
Raises a deprecation warning if the old `FASTMCP_SERVER_` prefix is used.
|
||||
"""
|
||||
|
||||
def get_field_value(
|
||||
self, field: FieldInfo, field_name: str
|
||||
) -> tuple[Any, str, bool]:
|
||||
if prefixes := self.config.get("env_prefixes"):
|
||||
for prefix in prefixes:
|
||||
self.env_prefix = prefix
|
||||
env_val, field_key, value_is_complex = super().get_field_value(
|
||||
field, field_name
|
||||
)
|
||||
if env_val is not None:
|
||||
if prefix == "FASTMCP_SERVER_":
|
||||
# Deprecated in 2.8.0
|
||||
warnings.warn(
|
||||
"Using `FASTMCP_SERVER_` environment variables is deprecated. Use `FASTMCP_` instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return env_val, field_key, value_is_complex
|
||||
|
||||
return super().get_field_value(field, field_name)
|
||||
|
||||
|
||||
class ExtendedSettingsConfigDict(SettingsConfigDict, total=False):
|
||||
env_prefixes: list[str] | None
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""FastMCP settings."""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="FASTMCP_",
|
||||
model_config = ExtendedSettingsConfigDict(
|
||||
env_prefixes=["FASTMCP_", "FASTMCP_SERVER_"],
|
||||
env_file=".env",
|
||||
extra="ignore",
|
||||
env_nested_delimiter="__",
|
||||
nested_model_default_partial_update=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
settings_cls: type[BaseSettings],
|
||||
init_settings: PydanticBaseSettingsSource,
|
||||
env_settings: PydanticBaseSettingsSource,
|
||||
dotenv_settings: PydanticBaseSettingsSource,
|
||||
file_secret_settings: PydanticBaseSettingsSource,
|
||||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||
# can remove this classmethod after deprecated FASTMCP_SERVER_ prefix is
|
||||
# removed
|
||||
return (
|
||||
init_settings,
|
||||
ExtendedEnvSettingsSource(settings_cls),
|
||||
dotenv_settings,
|
||||
file_secret_settings,
|
||||
)
|
||||
|
||||
@property
|
||||
def settings(self) -> Self:
|
||||
"""
|
||||
This property is for backwards compatibility with FastMCP < 2.8.0,
|
||||
which accessed fastmcp.settings.settings
|
||||
"""
|
||||
# Deprecated in 2.8.0
|
||||
warnings.warn(
|
||||
"Using fastmcp.settings.settings is deprecated. Use fastmcp.settings instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
home: Path = Path.home() / ".fastmcp"
|
||||
|
||||
test_mode: bool = False
|
||||
|
|
@ -107,27 +176,6 @@ class Settings(BaseSettings):
|
|||
|
||||
return self
|
||||
|
||||
|
||||
class ServerSettings(BaseSettings):
|
||||
"""FastMCP server settings.
|
||||
|
||||
All settings can be configured via environment variables with the prefix FASTMCP_.
|
||||
For example, FASTMCP_DEBUG=true will set debug=True.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="FASTMCP_SERVER_",
|
||||
env_file=".env",
|
||||
extra="ignore",
|
||||
env_nested_delimiter="__",
|
||||
nested_model_default_partial_update=True,
|
||||
)
|
||||
|
||||
log_level: Annotated[
|
||||
LOG_LEVEL,
|
||||
Field(default_factory=lambda: Settings().log_level),
|
||||
]
|
||||
|
||||
# HTTP settings
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 8000
|
||||
|
|
@ -136,15 +184,6 @@ class ServerSettings(BaseSettings):
|
|||
streamable_http_path: str = "/mcp"
|
||||
debug: bool = False
|
||||
|
||||
# resource settings
|
||||
on_duplicate_resources: DuplicateBehavior = "warn"
|
||||
|
||||
# tool settings
|
||||
on_duplicate_tools: DuplicateBehavior = "warn"
|
||||
|
||||
# prompt settings
|
||||
on_duplicate_prompts: DuplicateBehavior = "warn"
|
||||
|
||||
# error handling
|
||||
mask_error_details: Annotated[
|
||||
bool,
|
||||
|
|
@ -162,7 +201,7 @@ class ServerSettings(BaseSettings):
|
|||
),
|
||||
] = False
|
||||
|
||||
dependencies: Annotated[
|
||||
server_dependencies: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
default_factory=list,
|
||||
|
|
@ -170,9 +209,6 @@ class ServerSettings(BaseSettings):
|
|||
),
|
||||
] = []
|
||||
|
||||
# cache settings (for getting attributes from servers, used to avoid repeated calls)
|
||||
cache_expiration_seconds: float = 0
|
||||
|
||||
# StreamableHTTP settings
|
||||
json_response: bool = False
|
||||
stateless_http: bool = (
|
||||
|
|
|
|||
|
|
@ -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"]
|
||||
|
|
|
|||
|
|
@ -2,28 +2,29 @@ from __future__ import annotations
|
|||
|
||||
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__)
|
||||
|
||||
|
|
@ -32,24 +33,13 @@ def default_serializer(data: Any) -> str:
|
|||
return pydantic_core.to_json(data, fallback=str, indent=2).decode()
|
||||
|
||||
|
||||
class Tool(FastMCPBaseModel):
|
||||
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"
|
||||
)
|
||||
|
|
@ -72,6 +62,7 @@ class Tool(FastMCPBaseModel):
|
|||
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(
|
||||
|
|
@ -82,20 +73,43 @@ class Tool(FastMCPBaseModel):
|
|||
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]
|
||||
) -> list[TextContent | ImageContent | EmbeddedResource]:
|
||||
"""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]
|
||||
|
|
@ -110,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(
|
||||
|
|
@ -183,7 +156,7 @@ class FunctionTool(Tool):
|
|||
if context_kwarg and context_kwarg not in arguments:
|
||||
arguments[context_kwarg] = get_context()
|
||||
|
||||
if fastmcp.settings.settings.tool_attempt_parse_json_args:
|
||||
if fastmcp.settings.tool_attempt_parse_json_args:
|
||||
# Pre-parse data from JSON in order to handle cases like `["a", "b", "c"]`
|
||||
# being passed in as JSON inside a string rather than an actual list.
|
||||
#
|
||||
|
|
@ -220,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,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any
|
|||
|
||||
from mcp.types import EmbeddedResource, ImageContent, TextContent, ToolAnnotations
|
||||
|
||||
from fastmcp import settings
|
||||
from fastmcp.exceptions import NotFoundError, ToolError
|
||||
from fastmcp.settings import DuplicateBehavior
|
||||
from fastmcp.tools.tool import Tool
|
||||
|
|
@ -23,10 +24,10 @@ class ToolManager:
|
|||
def __init__(
|
||||
self,
|
||||
duplicate_behavior: DuplicateBehavior | None = None,
|
||||
mask_error_details: bool = False,
|
||||
mask_error_details: bool | None = None,
|
||||
):
|
||||
self._tools: dict[str, Tool] = {}
|
||||
self.mask_error_details = mask_error_details
|
||||
self.mask_error_details = mask_error_details or settings.mask_error_details
|
||||
|
||||
# Default to "warn" if None is provided
|
||||
if duplicate_behavior is None:
|
||||
|
|
|
|||
665
src/fastmcp/tools/tool_transform.py
Normal file
665
src/fastmcp/tools/tool_transform.py
Normal 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()
|
||||
)
|
||||
55
src/fastmcp/utilities/components.py
Normal file
55
src/fastmcp/utilities/components.py
Normal 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
|
||||
|
|
@ -43,7 +43,7 @@ def get_catch_handlers() -> Mapping[
|
|||
type[BaseException] | Iterable[type[BaseException]],
|
||||
Callable[[BaseExceptionGroup[Any]], Any],
|
||||
]:
|
||||
if fastmcp.settings.settings.client_raise_first_exceptiongroup_error:
|
||||
if fastmcp.settings.client_raise_first_exceptiongroup_error:
|
||||
return _catch_handlers
|
||||
else:
|
||||
return {}
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Literal
|
|||
|
||||
import uvicorn
|
||||
|
||||
from fastmcp.settings import settings
|
||||
from fastmcp import settings
|
||||
from fastmcp.utilities.http import find_available_port
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -32,8 +32,8 @@ def temporary_settings(**kwargs: Any):
|
|||
from fastmcp.utilities.tests import temporary_settings
|
||||
|
||||
with temporary_settings(log_level='DEBUG'):
|
||||
assert fastmcp.settings.settings.log_level == 'DEBUG'
|
||||
assert fastmcp.settings.settings.log_level == 'INFO'
|
||||
assert fastmcp.settings.log_level == 'DEBUG'
|
||||
assert fastmcp.settings.log_level == 'INFO'
|
||||
```
|
||||
"""
|
||||
old_settings = copy.deepcopy(settings.model_dump())
|
||||
|
|
|
|||
|
|
@ -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."""
|
||||
|
||||
|
|
|
|||
|
|
@ -4,16 +4,19 @@ from pydantic import AnyHttpUrl, ValidationError
|
|||
from fastmcp import FastMCP
|
||||
from fastmcp.server.auth.providers.bearer import BearerAuthProvider
|
||||
from fastmcp.server.auth.providers.bearer_env import EnvBearerAuthProvider
|
||||
from fastmcp.settings import Settings
|
||||
from fastmcp.utilities.tests import temporary_settings
|
||||
|
||||
|
||||
def test_load_bearer_env_from_env_var(monkeypatch):
|
||||
mcp = FastMCP()
|
||||
assert mcp.auth is None
|
||||
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
|
||||
|
||||
mcp_with_auth = FastMCP()
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
mcp_with_auth = FastMCP()
|
||||
assert isinstance(mcp_with_auth.auth, EnvBearerAuthProvider)
|
||||
|
||||
|
||||
|
|
@ -21,16 +24,17 @@ def test_load_bearer_env_from_env_var_requires_public_key_or_jwks_uri(monkeypatc
|
|||
mcp = FastMCP()
|
||||
assert mcp.auth is None
|
||||
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="Either public_key or jwks_uri must be provided"
|
||||
):
|
||||
FastMCP()
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
with pytest.raises(
|
||||
ValueError, match="Either public_key or jwks_uri must be provided"
|
||||
):
|
||||
FastMCP()
|
||||
|
||||
|
||||
def test_configure_bearer_env_from_env_var(monkeypatch):
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_ISSUER", "http://test-issuer")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_AUDIENCE", "test-audience")
|
||||
|
|
@ -38,7 +42,8 @@ def test_configure_bearer_env_from_env_var(monkeypatch):
|
|||
"FASTMCP_AUTH_BEARER_REQUIRED_SCOPES", '["test-scope1", "test-scope2"]'
|
||||
)
|
||||
|
||||
mcp = FastMCP()
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
mcp = FastMCP()
|
||||
assert isinstance(mcp.auth, EnvBearerAuthProvider)
|
||||
assert mcp.auth.public_key == "test-public-key"
|
||||
assert mcp.auth.issuer_url == AnyHttpUrl("http://test-issuer")
|
||||
|
|
@ -47,36 +52,40 @@ def test_configure_bearer_env_from_env_var(monkeypatch):
|
|||
|
||||
|
||||
def test_list_of_scopes_must_be_a_list(monkeypatch):
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_REQUIRED_SCOPES", "test-scope1")
|
||||
|
||||
with pytest.raises(ValidationError, match="Input should be a valid list"):
|
||||
FastMCP()
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
with pytest.raises(ValidationError, match="Input should be a valid list"):
|
||||
FastMCP()
|
||||
|
||||
|
||||
def test_configure_bearer_env_jwks_uri_from_env_var(monkeypatch):
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_JWKS_URI", "test-jwks-uri")
|
||||
|
||||
mcp = FastMCP()
|
||||
assert isinstance(mcp.auth, EnvBearerAuthProvider)
|
||||
assert mcp.auth.jwks_uri == "test-jwks-uri"
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
mcp = FastMCP()
|
||||
assert isinstance(mcp.auth, EnvBearerAuthProvider)
|
||||
assert mcp.auth.jwks_uri == "test-jwks-uri"
|
||||
|
||||
|
||||
def test_configure_bearer_env_public_key_and_jwks_uri_error(monkeypatch):
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_JWKS_URI", "test-jwks-uri")
|
||||
|
||||
with pytest.raises(ValueError, match="Provide either public_key or jwks_uri"):
|
||||
FastMCP()
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
with pytest.raises(ValueError, match="Provide either public_key or jwks_uri"):
|
||||
FastMCP()
|
||||
|
||||
|
||||
def test_provided_auth_takes_precedence_over_env_vars(monkeypatch):
|
||||
monkeypatch.setenv("FASTMCP_SERVER_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_DEFAULT_AUTH_PROVIDER", "bearer_env")
|
||||
monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
|
||||
|
||||
mcp = FastMCP(auth=BearerAuthProvider(public_key="test-public-key-2"))
|
||||
assert isinstance(mcp.auth, BearerAuthProvider)
|
||||
assert not isinstance(mcp.auth, EnvBearerAuthProvider)
|
||||
assert mcp.auth.public_key == "test-public-key-2"
|
||||
with temporary_settings(**Settings().model_dump()):
|
||||
mcp = FastMCP(auth=BearerAuthProvider(public_key="test-public-key-2"))
|
||||
assert isinstance(mcp.auth, BearerAuthProvider)
|
||||
assert not isinstance(mcp.auth, EnvBearerAuthProvider)
|
||||
assert mcp.auth.public_key == "test-public-key-2"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from fastapi import FastAPI, Request
|
|||
|
||||
from fastmcp import Client, FastMCP
|
||||
from fastmcp.client.transports import SSETransport, StreamableHttpTransport
|
||||
from fastmcp.server.openapi import MCPType, RouteMap
|
||||
from fastmcp.utilities.tests import run_server_in_process
|
||||
|
||||
|
||||
|
|
@ -27,6 +28,16 @@ def fastmcp_server_for_headers() -> FastMCP:
|
|||
mcp = FastMCP.from_fastapi(
|
||||
app,
|
||||
httpx_client_kwargs={"headers": {"x-server-header": "test-abc"}},
|
||||
route_maps=[
|
||||
# GET requests with path parameters go to ResourceTemplate
|
||||
RouteMap(
|
||||
methods=["GET"],
|
||||
pattern=r".*\{.*\}.*",
|
||||
mcp_type=MCPType.RESOURCE_TEMPLATE,
|
||||
),
|
||||
# GET requests without path parameters go to Resource
|
||||
RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
|
||||
],
|
||||
)
|
||||
|
||||
return mcp
|
||||
|
|
|
|||
351
tests/deprecated/test_settings.py
Normal file
351
tests/deprecated/test_settings.py
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
import os
|
||||
import warnings
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.settings import Settings
|
||||
|
||||
# reset deprecation warnings for this module
|
||||
pytestmark = pytest.mark.filterwarnings("default::DeprecationWarning")
|
||||
|
||||
|
||||
class TestDeprecatedServerInitKwargs:
|
||||
"""Test deprecated server initialization keyword arguments."""
|
||||
|
||||
def test_log_level_deprecation_warning(self):
|
||||
"""Test that log_level raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `log_level` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", log_level="DEBUG")
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.log_level == "DEBUG"
|
||||
|
||||
def test_debug_deprecation_warning(self):
|
||||
"""Test that debug raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `debug` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", debug=True)
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.debug is True
|
||||
|
||||
def test_host_deprecation_warning(self):
|
||||
"""Test that host raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `host` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", host="0.0.0.0")
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.host == "0.0.0.0"
|
||||
|
||||
def test_port_deprecation_warning(self):
|
||||
"""Test that port raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `port` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", port=8080)
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.port == 8080
|
||||
|
||||
def test_sse_path_deprecation_warning(self):
|
||||
"""Test that sse_path raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `sse_path` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", sse_path="/custom-sse")
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.sse_path == "/custom-sse"
|
||||
|
||||
def test_message_path_deprecation_warning(self):
|
||||
"""Test that message_path raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `message_path` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", message_path="/custom-message")
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.message_path == "/custom-message"
|
||||
|
||||
def test_streamable_http_path_deprecation_warning(self):
|
||||
"""Test that streamable_http_path raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `streamable_http_path` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", streamable_http_path="/custom-http")
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.streamable_http_path == "/custom-http"
|
||||
|
||||
def test_json_response_deprecation_warning(self):
|
||||
"""Test that json_response raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `json_response` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", json_response=True)
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.json_response is True
|
||||
|
||||
def test_stateless_http_deprecation_warning(self):
|
||||
"""Test that stateless_http raises a deprecation warning."""
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Providing `stateless_http` when creating a server is deprecated\. Provide it when calling `run` or as a global setting instead\.",
|
||||
):
|
||||
server = FastMCP("TestServer", stateless_http=True)
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert server._deprecated_settings.stateless_http is True
|
||||
|
||||
def test_multiple_deprecated_kwargs_warnings(self):
|
||||
"""Test that multiple deprecated kwargs each raise their own warning."""
|
||||
with warnings.catch_warnings(record=True) as recorded_warnings:
|
||||
warnings.simplefilter("always")
|
||||
server = FastMCP(
|
||||
"TestServer",
|
||||
log_level="INFO",
|
||||
debug=False,
|
||||
host="127.0.0.1",
|
||||
port=9999,
|
||||
sse_path="/sse",
|
||||
message_path="/msg",
|
||||
streamable_http_path="/http",
|
||||
json_response=False,
|
||||
stateless_http=False,
|
||||
)
|
||||
|
||||
# Should have 9 deprecation warnings (one for each deprecated parameter)
|
||||
deprecation_warnings = [
|
||||
w for w in recorded_warnings if issubclass(w.category, DeprecationWarning)
|
||||
]
|
||||
assert len(deprecation_warnings) == 9
|
||||
|
||||
# Verify all expected parameters are mentioned in warnings
|
||||
expected_params = {
|
||||
"log_level",
|
||||
"debug",
|
||||
"host",
|
||||
"port",
|
||||
"sse_path",
|
||||
"message_path",
|
||||
"streamable_http_path",
|
||||
"json_response",
|
||||
"stateless_http",
|
||||
}
|
||||
mentioned_params = set()
|
||||
for warning in deprecation_warnings:
|
||||
message = str(warning.message)
|
||||
for param in expected_params:
|
||||
if f"Providing `{param}`" in message:
|
||||
mentioned_params.add(param)
|
||||
|
||||
assert mentioned_params == expected_params
|
||||
|
||||
# Verify all settings are still applied
|
||||
assert server._deprecated_settings.log_level == "INFO"
|
||||
assert server._deprecated_settings.debug is False
|
||||
assert server._deprecated_settings.host == "127.0.0.1"
|
||||
assert server._deprecated_settings.port == 9999
|
||||
assert server._deprecated_settings.sse_path == "/sse"
|
||||
assert server._deprecated_settings.message_path == "/msg"
|
||||
assert server._deprecated_settings.streamable_http_path == "/http"
|
||||
assert server._deprecated_settings.json_response is False
|
||||
assert server._deprecated_settings.stateless_http is False
|
||||
|
||||
def test_non_deprecated_kwargs_no_warnings(self):
|
||||
"""Test that non-deprecated kwargs don't raise warnings."""
|
||||
with warnings.catch_warnings(record=True) as recorded_warnings:
|
||||
warnings.simplefilter("always")
|
||||
server = FastMCP(
|
||||
name="TestServer",
|
||||
instructions="Test instructions",
|
||||
tags={"test", "server"},
|
||||
cache_expiration_seconds=60.0,
|
||||
on_duplicate_tools="warn",
|
||||
on_duplicate_resources="error",
|
||||
on_duplicate_prompts="replace",
|
||||
resource_prefix_format="path",
|
||||
mask_error_details=True,
|
||||
)
|
||||
|
||||
# Should have no deprecation warnings
|
||||
deprecation_warnings = [
|
||||
w for w in recorded_warnings if issubclass(w.category, DeprecationWarning)
|
||||
]
|
||||
assert len(deprecation_warnings) == 0
|
||||
|
||||
# Verify server was created successfully
|
||||
assert server.name == "TestServer"
|
||||
assert server.instructions == "Test instructions"
|
||||
assert server.tags == {"test", "server"}
|
||||
|
||||
def test_none_values_no_warnings(self):
|
||||
"""Test that None values for deprecated kwargs don't raise warnings."""
|
||||
with warnings.catch_warnings(record=True) as recorded_warnings:
|
||||
warnings.simplefilter("always")
|
||||
FastMCP(
|
||||
"TestServer",
|
||||
log_level=None,
|
||||
debug=None,
|
||||
host=None,
|
||||
port=None,
|
||||
sse_path=None,
|
||||
message_path=None,
|
||||
streamable_http_path=None,
|
||||
json_response=None,
|
||||
stateless_http=None,
|
||||
)
|
||||
|
||||
# Should have no deprecation warnings for None values
|
||||
deprecation_warnings = [
|
||||
w for w in recorded_warnings if issubclass(w.category, DeprecationWarning)
|
||||
]
|
||||
assert len(deprecation_warnings) == 0
|
||||
|
||||
def test_deprecated_settings_inheritance_from_global(self):
|
||||
"""Test that deprecated settings inherit from global settings when not provided."""
|
||||
# Mock fastmcp.settings to test inheritance
|
||||
with patch("fastmcp.settings") as mock_settings:
|
||||
mock_settings.model_dump.return_value = {
|
||||
"log_level": "WARNING",
|
||||
"debug": True,
|
||||
"host": "0.0.0.0",
|
||||
"port": 3000,
|
||||
"sse_path": "/events",
|
||||
"message_path": "/messages",
|
||||
"streamable_http_path": "/stream",
|
||||
"json_response": True,
|
||||
"stateless_http": True,
|
||||
}
|
||||
|
||||
server = FastMCP("TestServer")
|
||||
|
||||
# Verify settings are inherited from global settings
|
||||
assert server._deprecated_settings.log_level == "WARNING"
|
||||
assert server._deprecated_settings.debug is True
|
||||
assert server._deprecated_settings.host == "0.0.0.0"
|
||||
assert server._deprecated_settings.port == 3000
|
||||
assert server._deprecated_settings.sse_path == "/events"
|
||||
assert server._deprecated_settings.message_path == "/messages"
|
||||
assert server._deprecated_settings.streamable_http_path == "/stream"
|
||||
assert server._deprecated_settings.json_response is True
|
||||
assert server._deprecated_settings.stateless_http is True
|
||||
|
||||
def test_deprecated_settings_override_global(self):
|
||||
"""Test that deprecated settings override global settings when provided."""
|
||||
# Mock fastmcp.settings to test override behavior
|
||||
with patch("fastmcp.settings") as mock_settings:
|
||||
mock_settings.model_dump.return_value = {
|
||||
"log_level": "WARNING",
|
||||
"debug": True,
|
||||
"host": "0.0.0.0",
|
||||
"port": 3000,
|
||||
"sse_path": "/events",
|
||||
"message_path": "/messages",
|
||||
"streamable_http_path": "/stream",
|
||||
"json_response": True,
|
||||
"stateless_http": True,
|
||||
}
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore") # Ignore warnings for this test
|
||||
server = FastMCP(
|
||||
"TestServer",
|
||||
log_level="ERROR",
|
||||
debug=False,
|
||||
host="127.0.0.1",
|
||||
port=8080,
|
||||
)
|
||||
|
||||
# Verify provided settings override global settings
|
||||
assert server._deprecated_settings.log_level == "ERROR"
|
||||
assert server._deprecated_settings.debug is False
|
||||
assert server._deprecated_settings.host == "127.0.0.1"
|
||||
assert server._deprecated_settings.port == 8080
|
||||
# Non-overridden settings should still come from global
|
||||
assert server._deprecated_settings.sse_path == "/events"
|
||||
assert server._deprecated_settings.message_path == "/messages"
|
||||
assert server._deprecated_settings.streamable_http_path == "/stream"
|
||||
assert server._deprecated_settings.json_response is True
|
||||
assert server._deprecated_settings.stateless_http is True
|
||||
|
||||
def test_stacklevel_points_to_constructor_call(self):
|
||||
"""Test that deprecation warnings point to the FastMCP constructor call."""
|
||||
with warnings.catch_warnings(record=True) as recorded_warnings:
|
||||
warnings.simplefilter("always")
|
||||
|
||||
FastMCP("TestServer", log_level="DEBUG")
|
||||
|
||||
# Should have exactly one deprecation warning
|
||||
deprecation_warnings = [
|
||||
w for w in recorded_warnings if issubclass(w.category, DeprecationWarning)
|
||||
]
|
||||
assert len(deprecation_warnings) == 1
|
||||
|
||||
# The warning should point to the server.py file where FastMCP.__init__ is called
|
||||
# This verifies the stacklevel is working as intended (pointing to constructor)
|
||||
warning = deprecation_warnings[0]
|
||||
assert "server.py" in warning.filename
|
||||
|
||||
|
||||
class TestDeprecatedEnvironmentVariables:
|
||||
"""Test deprecated environment variable prefixes."""
|
||||
|
||||
def test_fastmcp_server_env_var_deprecation_warning(self):
|
||||
"""Test that FASTMCP_SERVER_ environment variables emit deprecation warnings."""
|
||||
env_var_name = "FASTMCP_SERVER_HOST"
|
||||
original_value = os.environ.get(env_var_name)
|
||||
|
||||
try:
|
||||
os.environ[env_var_name] = "192.168.1.1"
|
||||
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Using `FASTMCP_SERVER_` environment variables is deprecated\. Use `FASTMCP_` instead\.",
|
||||
):
|
||||
settings = Settings()
|
||||
|
||||
# Verify the setting is still applied
|
||||
assert settings.host == "192.168.1.1"
|
||||
|
||||
finally:
|
||||
# Clean up environment variable
|
||||
if original_value is not None:
|
||||
os.environ[env_var_name] = original_value
|
||||
else:
|
||||
os.environ.pop(env_var_name, None)
|
||||
|
||||
|
||||
class TestDeprecatedSettingsProperty:
|
||||
"""Test deprecated settings property access."""
|
||||
|
||||
def test_settings_property_deprecation_warning(self):
|
||||
"""Test that accessing fastmcp.settings.settings raises a deprecation warning."""
|
||||
from fastmcp import settings
|
||||
|
||||
with pytest.warns(
|
||||
DeprecationWarning,
|
||||
match=r"Using fastmcp\.settings\.settings is deprecated\. Use fastmcp\.settings instead\.",
|
||||
):
|
||||
# Access the deprecated property
|
||||
deprecated_settings = settings.settings
|
||||
|
||||
# Verify it still returns the same settings object
|
||||
assert deprecated_settings is settings
|
||||
assert isinstance(deprecated_settings, Settings)
|
||||
|
|
@ -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"),
|
||||
|
|
|
|||
|
|
@ -46,6 +46,20 @@ def users_db() -> dict[int, User]:
|
|||
}
|
||||
|
||||
|
||||
# route maps for GET requests
|
||||
# use these to create components of all types instead of just tools
|
||||
GET_ROUTE_MAPS = [
|
||||
# GET requests with path parameters go to ResourceTemplate
|
||||
RouteMap(
|
||||
methods=["GET"],
|
||||
pattern=r".*\{.*\}.*",
|
||||
mcp_type=MCPType.RESOURCE_TEMPLATE,
|
||||
),
|
||||
# GET requests without path parameters go to Resource
|
||||
RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fastapi_app(users_db: dict[int, User]) -> FastAPI:
|
||||
app = FastAPI(title="FastAPI App")
|
||||
|
|
@ -122,7 +136,7 @@ def api_client(fastapi_app: FastAPI) -> AsyncClient:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
async def fastmcp_openapi_server(
|
||||
async def fastmcp_openapi_server_with_all_types(
|
||||
fastapi_app: FastAPI, api_client: httpx.AsyncClient
|
||||
) -> FastMCPOpenAPI:
|
||||
openapi_spec = fastapi_app.openapi()
|
||||
|
|
@ -131,6 +145,7 @@ async def fastmcp_openapi_server(
|
|||
openapi_spec=openapi_spec,
|
||||
client=api_client,
|
||||
name="Test App",
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -169,6 +184,7 @@ async def test_create_openapi_server_with_timeout(
|
|||
client=api_client,
|
||||
name="Test App",
|
||||
timeout=1.0,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
assert server._timeout == 1.0
|
||||
|
||||
|
|
@ -186,11 +202,24 @@ async def test_create_openapi_server_with_timeout(
|
|||
|
||||
|
||||
class TestTools:
|
||||
async def test_list_tools(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_default_behavior_converts_everything_to_tools(
|
||||
self, fastapi_app: FastAPI
|
||||
):
|
||||
"""
|
||||
By default, tools exclude GET methods
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
server = FastMCPOpenAPI.from_fastapi(fastapi_app)
|
||||
assert len(await server.get_tools()) == 8
|
||||
assert len(await server.get_resources()) == 0
|
||||
assert len(await server.get_resource_templates()) == 0
|
||||
|
||||
async def test_list_tools(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""
|
||||
By default, tools exclude GET methods
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 2
|
||||
|
||||
|
|
@ -224,12 +253,14 @@ class TestTools:
|
|||
)
|
||||
|
||||
async def test_call_create_user_tool(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI, api_client
|
||||
self,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""
|
||||
The tool created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
tool_response = await client.call_tool(
|
||||
"create_user_users_post", {"name": "David", "active": False}
|
||||
)
|
||||
|
|
@ -243,19 +274,21 @@ class TestTools:
|
|||
assert len(response.json()) == 4
|
||||
|
||||
# Check that the user was created via MCP
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
user_response = await client.read_resource("resource://get_user_users/4")
|
||||
response_text = user_response[0].text # type: ignore[attr-defined]
|
||||
user = json.loads(response_text)
|
||||
assert user == expected_user
|
||||
|
||||
async def test_call_update_user_name_tool(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI, api_client
|
||||
self,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""
|
||||
The tool created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
tool_response = await client.call_tool(
|
||||
"update_user_name_users",
|
||||
{"user_id": 1, "name": "XYZ"},
|
||||
|
|
@ -270,7 +303,7 @@ class TestTools:
|
|||
assert expected_data in response.json()
|
||||
|
||||
# Check that the user was updated via MCP
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
user_response = await client.read_resource("resource://get_user_users/1")
|
||||
response_text = user_response[0].text # type: ignore[attr-defined]
|
||||
user = json.loads(response_text)
|
||||
|
|
@ -302,11 +335,13 @@ class TestTools:
|
|||
|
||||
|
||||
class TestResources:
|
||||
async def test_list_resources(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_list_resources(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""
|
||||
By default, resources exclude GET methods without parameters
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 4
|
||||
assert resources[0].uri == AnyUrl("resource://get_users_users_get")
|
||||
|
|
@ -314,7 +349,7 @@ class TestResources:
|
|||
|
||||
async def test_get_resource(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
users_db: dict[int, User],
|
||||
):
|
||||
|
|
@ -325,7 +360,7 @@ class TestResources:
|
|||
json_users = TypeAdapter(list[User]).dump_python(
|
||||
sorted(users_db.values(), key=lambda x: x.id)
|
||||
)
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://get_users_users_get"
|
||||
)
|
||||
|
|
@ -337,11 +372,11 @@ class TestResources:
|
|||
|
||||
async def test_get_bytes_resource(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""Test reading a resource that returns bytes."""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://ping_bytes_ping_bytes_get"
|
||||
)
|
||||
|
|
@ -350,23 +385,23 @@ class TestResources:
|
|||
|
||||
async def test_get_str_resource(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""Test reading a resource that returns a string."""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource("resource://ping_ping_get")
|
||||
assert resource_response[0].text == "pong" # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class TestResourceTemplates:
|
||||
async def test_list_resource_templates(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""
|
||||
By default, resource templates exclude GET methods without parameters
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_templates = await client.list_resource_templates()
|
||||
assert len(resource_templates) == 2
|
||||
assert resource_templates[0].name == "get_user_users"
|
||||
|
|
@ -381,7 +416,7 @@ class TestResourceTemplates:
|
|||
|
||||
async def test_get_resource_template(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
users_db: dict[int, User],
|
||||
):
|
||||
|
|
@ -389,7 +424,7 @@ class TestResourceTemplates:
|
|||
The resource template created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
user_id = 2
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource(
|
||||
f"resource://get_user_users/{user_id}"
|
||||
)
|
||||
|
|
@ -402,7 +437,7 @@ class TestResourceTemplates:
|
|||
|
||||
async def test_get_resource_template_multi_param(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
|
||||
api_client,
|
||||
users_db: dict[int, User],
|
||||
):
|
||||
|
|
@ -411,7 +446,7 @@ class TestResourceTemplates:
|
|||
"""
|
||||
user_id = 2
|
||||
is_active = True
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource(
|
||||
f"resource://get_user_active_state_users/{is_active}/{user_id}"
|
||||
)
|
||||
|
|
@ -424,11 +459,13 @@ class TestResourceTemplates:
|
|||
|
||||
|
||||
class TestPrompts:
|
||||
async def test_list_prompts(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_list_prompts(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""
|
||||
By default, there are no prompts.
|
||||
"""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
async with Client(fastmcp_openapi_server_with_all_types) as client:
|
||||
prompts = await client.list_prompts()
|
||||
assert len(prompts) == 0
|
||||
|
||||
|
|
@ -437,11 +474,11 @@ class TestTagTransfer:
|
|||
"""Tests for transferring tags from OpenAPI routes to MCP objects."""
|
||||
|
||||
async def test_tags_transferred_to_tools(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that tags from OpenAPI routes are correctly transferred to Tools."""
|
||||
# Get internal tools directly (not the public API which returns MCP.Content)
|
||||
tools = fastmcp_openapi_server._tool_manager.list_tools()
|
||||
tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()
|
||||
|
||||
# Find the create_user and update_user_name tools
|
||||
create_user_tool = next(
|
||||
|
|
@ -465,12 +502,12 @@ class TestTagTransfer:
|
|||
assert len(update_user_tool.tags) == 2
|
||||
|
||||
async def test_tags_transferred_to_resources(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that tags from OpenAPI routes are correctly transferred to Resources."""
|
||||
# Get internal resources directly
|
||||
resources = list(
|
||||
fastmcp_openapi_server._resource_manager.get_resources().values()
|
||||
fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
|
||||
)
|
||||
|
||||
# Find the get_users resource
|
||||
|
|
@ -486,12 +523,12 @@ class TestTagTransfer:
|
|||
assert len(get_users_resource.tags) == 2
|
||||
|
||||
async def test_tags_transferred_to_resource_templates(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that tags from OpenAPI routes are correctly transferred to ResourceTemplates."""
|
||||
# Get internal resource templates directly
|
||||
templates = list(
|
||||
fastmcp_openapi_server._resource_manager.get_templates().values()
|
||||
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
|
||||
# Find the get_user template
|
||||
|
|
@ -507,12 +544,12 @@ class TestTagTransfer:
|
|||
assert len(get_user_template.tags) == 2
|
||||
|
||||
async def test_tags_preserved_in_resources_created_from_templates(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that tags are preserved when creating resources from templates."""
|
||||
# Get internal resource templates directly
|
||||
templates = list(
|
||||
fastmcp_openapi_server._resource_manager.get_templates().values()
|
||||
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
|
||||
# Find the get_user template
|
||||
|
|
@ -624,46 +661,49 @@ class TestOpenAPI30Compatibility:
|
|||
return httpx.AsyncClient(transport=transport, base_url="http://test")
|
||||
|
||||
@pytest.fixture
|
||||
async def openapi_30_server(
|
||||
async def openapi_30_server_with_all_types(
|
||||
self, openapi_30_spec, mock_30_client
|
||||
) -> FastMCPOpenAPI:
|
||||
"""Create a FastMCPOpenAPI server from the OpenAPI 3.0 spec."""
|
||||
return FastMCPOpenAPI(
|
||||
openapi_spec=openapi_30_spec, client=mock_30_client, name="Product API 3.0"
|
||||
openapi_spec=openapi_30_spec,
|
||||
client=mock_30_client,
|
||||
name="Product API 3.0",
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
async def test_server_creation(self, openapi_30_server):
|
||||
async def test_server_creation(self, openapi_30_server_with_all_types):
|
||||
"""Test that a server can be created from an OpenAPI 3.0 spec."""
|
||||
assert isinstance(openapi_30_server, FastMCP)
|
||||
assert openapi_30_server.name == "Product API 3.0"
|
||||
assert isinstance(openapi_30_server_with_all_types, FastMCP)
|
||||
assert openapi_30_server_with_all_types.name == "Product API 3.0"
|
||||
|
||||
async def test_resource_discovery(self, openapi_30_server):
|
||||
async def test_resource_discovery(self, openapi_30_server_with_all_types):
|
||||
"""Test that resources are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 1
|
||||
assert resources[0].uri == AnyUrl("resource://listProducts")
|
||||
|
||||
async def test_resource_template_discovery(self, openapi_30_server):
|
||||
async def test_resource_template_discovery(self, openapi_30_server_with_all_types):
|
||||
"""Test that resource templates are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "getProduct"
|
||||
assert templates[0].uriTemplate == r"resource://getProduct/{product_id}"
|
||||
|
||||
async def test_tool_discovery(self, openapi_30_server):
|
||||
async def test_tool_discovery(self, openapi_30_server_with_all_types):
|
||||
"""Test that tools are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 1
|
||||
assert tools[0].name == "createProduct"
|
||||
assert "name" in tools[0].inputSchema["properties"]
|
||||
assert "price" in tools[0].inputSchema["properties"]
|
||||
|
||||
async def test_resource_access(self, openapi_30_server):
|
||||
async def test_resource_access(self, openapi_30_server_with_all_types):
|
||||
"""Test reading a resource from an OpenAPI 3.0 server."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource("resource://listProducts")
|
||||
response_text = resource_response[0].text # type: ignore[attr-defined]
|
||||
content = json.loads(response_text)
|
||||
|
|
@ -671,9 +711,9 @@ class TestOpenAPI30Compatibility:
|
|||
assert content[0]["name"] == "Product 1"
|
||||
assert content[1]["name"] == "Product 2"
|
||||
|
||||
async def test_resource_template_access(self, openapi_30_server):
|
||||
async def test_resource_template_access(self, openapi_30_server_with_all_types):
|
||||
"""Test reading a resource from template from an OpenAPI 3.0 server."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource("resource://getProduct/p1")
|
||||
response_text = resource_response[0].text # type: ignore[attr-defined]
|
||||
content = json.loads(response_text)
|
||||
|
|
@ -681,9 +721,9 @@ class TestOpenAPI30Compatibility:
|
|||
assert content["name"] == "Product 1"
|
||||
assert content["price"] == 19.99
|
||||
|
||||
async def test_tool_execution(self, openapi_30_server):
|
||||
async def test_tool_execution(self, openapi_30_server_with_all_types):
|
||||
"""Test executing a tool from an OpenAPI 3.0 server."""
|
||||
async with Client(openapi_30_server) as client:
|
||||
async with Client(openapi_30_server_with_all_types) as client:
|
||||
result = await client.call_tool(
|
||||
"createProduct", {"name": "New Product", "price": 39.99}
|
||||
)
|
||||
|
|
@ -797,46 +837,49 @@ class TestOpenAPI31Compatibility:
|
|||
return httpx.AsyncClient(transport=transport, base_url="http://test")
|
||||
|
||||
@pytest.fixture
|
||||
async def openapi_31_server(
|
||||
async def openapi_31_server_with_all_types(
|
||||
self, openapi_31_spec, mock_31_client
|
||||
) -> FastMCPOpenAPI:
|
||||
"""Create a FastMCPOpenAPI server from the OpenAPI 3.1 spec."""
|
||||
return FastMCPOpenAPI(
|
||||
openapi_spec=openapi_31_spec, client=mock_31_client, name="Order API 3.1"
|
||||
openapi_spec=openapi_31_spec,
|
||||
client=mock_31_client,
|
||||
name="Order API 3.1",
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
async def test_server_creation(self, openapi_31_server):
|
||||
async def test_server_creation(self, openapi_31_server_with_all_types):
|
||||
"""Test that a server can be created from an OpenAPI 3.1 spec."""
|
||||
assert isinstance(openapi_31_server, FastMCP)
|
||||
assert openapi_31_server.name == "Order API 3.1"
|
||||
assert isinstance(openapi_31_server_with_all_types, FastMCP)
|
||||
assert openapi_31_server_with_all_types.name == "Order API 3.1"
|
||||
|
||||
async def test_resource_discovery(self, openapi_31_server):
|
||||
async def test_resource_discovery(self, openapi_31_server_with_all_types):
|
||||
"""Test that resources are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 1
|
||||
assert resources[0].uri == AnyUrl("resource://listOrders")
|
||||
|
||||
async def test_resource_template_discovery(self, openapi_31_server):
|
||||
async def test_resource_template_discovery(self, openapi_31_server_with_all_types):
|
||||
"""Test that resource templates are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "getOrder"
|
||||
assert templates[0].uriTemplate == r"resource://getOrder/{order_id}"
|
||||
|
||||
async def test_tool_discovery(self, openapi_31_server):
|
||||
async def test_tool_discovery(self, openapi_31_server_with_all_types):
|
||||
"""Test that tools are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 1
|
||||
assert tools[0].name == "createOrder"
|
||||
assert "customer" in tools[0].inputSchema["properties"]
|
||||
assert "items" in tools[0].inputSchema["properties"]
|
||||
|
||||
async def test_resource_access(self, openapi_31_server):
|
||||
async def test_resource_access(self, openapi_31_server_with_all_types):
|
||||
"""Test reading a resource from an OpenAPI 3.1 server."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource("resource://listOrders")
|
||||
response_text = resource_response[0].text # type: ignore[attr-defined]
|
||||
content = json.loads(response_text)
|
||||
|
|
@ -844,9 +887,9 @@ class TestOpenAPI31Compatibility:
|
|||
assert content[0]["customer"] == "Alice"
|
||||
assert content[1]["customer"] == "Bob"
|
||||
|
||||
async def test_resource_template_access(self, openapi_31_server):
|
||||
async def test_resource_template_access(self, openapi_31_server_with_all_types):
|
||||
"""Test reading a resource from template from an OpenAPI 3.1 server."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
resource_response = await client.read_resource("resource://getOrder/o1")
|
||||
response_text = resource_response[0].text # type: ignore[attr-defined]
|
||||
content = json.loads(response_text)
|
||||
|
|
@ -854,9 +897,9 @@ class TestOpenAPI31Compatibility:
|
|||
assert content["customer"] == "Alice"
|
||||
assert content["items"] == ["item1", "item2"]
|
||||
|
||||
async def test_tool_execution(self, openapi_31_server):
|
||||
async def test_tool_execution(self, openapi_31_server_with_all_types):
|
||||
"""Test executing a tool from an OpenAPI 3.1 server."""
|
||||
async with Client(openapi_31_server) as client:
|
||||
async with Client(openapi_31_server_with_all_types) as client:
|
||||
result = await client.call_tool(
|
||||
"createOrder", {"customer": "Charlie", "items": ["item4", "item5"]}
|
||||
)
|
||||
|
|
@ -871,11 +914,13 @@ class TestOpenAPI31Compatibility:
|
|||
class TestMountFastMCP:
|
||||
"""Tests for mounting FastMCP servers."""
|
||||
|
||||
async def test_mount_fastmcp(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_mount_fastmcp(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test mounting an OpenAPI server."""
|
||||
mcp = FastMCP("MainApp")
|
||||
|
||||
await mcp.import_server("fastapi", fastmcp_openapi_server)
|
||||
await mcp.import_server("fastapi", fastmcp_openapi_server_with_all_types)
|
||||
|
||||
# Check that resources are available with prefixed URIs
|
||||
async with Client(mcp) as client:
|
||||
|
|
@ -1144,19 +1189,24 @@ class TestDescriptionPropagation:
|
|||
return httpx.AsyncClient(transport=transport, base_url="http://test")
|
||||
|
||||
@pytest.fixture
|
||||
async def test_server(self, simple_openapi_spec, mock_client):
|
||||
async def simple_server_with_all_types(self, simple_openapi_spec, mock_client):
|
||||
"""Create a FastMCPOpenAPI server with the simple test spec."""
|
||||
return FastMCPOpenAPI(
|
||||
openapi_spec=simple_openapi_spec,
|
||||
client=mock_client,
|
||||
name="Test API",
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
# --- RESOURCE TESTS ---
|
||||
|
||||
async def test_resource_includes_route_description(self, test_server):
|
||||
async def test_resource_includes_route_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a Resource includes the route description."""
|
||||
resources = list(test_server._resource_manager.get_resources().values())
|
||||
resources = list(
|
||||
simple_server_with_all_types._resource_manager.get_resources().values()
|
||||
)
|
||||
list_resource = next((r for r in resources if r.name == "listItems"), None)
|
||||
|
||||
assert list_resource is not None, "listItems resource wasn't created"
|
||||
|
|
@ -1164,9 +1214,13 @@ class TestDescriptionPropagation:
|
|||
"Route description missing from Resource"
|
||||
)
|
||||
|
||||
async def test_resource_includes_response_description(self, test_server):
|
||||
async def test_resource_includes_response_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a Resource includes the response description."""
|
||||
resources = list(test_server._resource_manager.get_resources().values())
|
||||
resources = list(
|
||||
simple_server_with_all_types._resource_manager.get_resources().values()
|
||||
)
|
||||
list_resource = next((r for r in resources if r.name == "listItems"), None)
|
||||
|
||||
assert list_resource is not None, "listItems resource wasn't created"
|
||||
|
|
@ -1174,9 +1228,13 @@ class TestDescriptionPropagation:
|
|||
"Response description missing from Resource"
|
||||
)
|
||||
|
||||
async def test_resource_includes_response_model_fields(self, test_server):
|
||||
async def test_resource_includes_response_model_fields(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a Resource description includes response model field descriptions."""
|
||||
resources = list(test_server._resource_manager.get_resources().values())
|
||||
resources = list(
|
||||
simple_server_with_all_types._resource_manager.get_resources().values()
|
||||
)
|
||||
list_resource = next((r for r in resources if r.name == "listItems"), None)
|
||||
|
||||
assert list_resource is not None, "listItems resource wasn't created"
|
||||
|
|
@ -1193,9 +1251,13 @@ class TestDescriptionPropagation:
|
|||
|
||||
# --- RESOURCE TEMPLATE TESTS ---
|
||||
|
||||
async def test_template_includes_route_description(self, test_server):
|
||||
async def test_template_includes_route_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a ResourceTemplate includes the route description."""
|
||||
templates = list(test_server._resource_manager.get_templates().values())
|
||||
templates = list(
|
||||
simple_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
assert get_template is not None, "getItem template wasn't created"
|
||||
|
|
@ -1203,9 +1265,13 @@ class TestDescriptionPropagation:
|
|||
"Route description missing from ResourceTemplate"
|
||||
)
|
||||
|
||||
async def test_template_includes_function_docstring(self, test_server):
|
||||
async def test_template_includes_function_docstring(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a ResourceTemplate includes the function docstring."""
|
||||
templates = list(test_server._resource_manager.get_templates().values())
|
||||
templates = list(
|
||||
simple_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
assert get_template is not None, "getItem template wasn't created"
|
||||
|
|
@ -1213,9 +1279,13 @@ class TestDescriptionPropagation:
|
|||
"Function docstring missing from ResourceTemplate"
|
||||
)
|
||||
|
||||
async def test_template_includes_path_parameter_description(self, test_server):
|
||||
async def test_template_includes_path_parameter_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a ResourceTemplate includes path parameter descriptions."""
|
||||
templates = list(test_server._resource_manager.get_templates().values())
|
||||
templates = list(
|
||||
simple_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
assert get_template is not None, "getItem template wasn't created"
|
||||
|
|
@ -1223,9 +1293,13 @@ class TestDescriptionPropagation:
|
|||
"Path parameter description missing from ResourceTemplate description"
|
||||
)
|
||||
|
||||
async def test_template_includes_query_parameter_description(self, test_server):
|
||||
async def test_template_includes_query_parameter_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a ResourceTemplate includes query parameter descriptions."""
|
||||
templates = list(test_server._resource_manager.get_templates().values())
|
||||
templates = list(
|
||||
simple_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
assert get_template is not None, "getItem template wasn't created"
|
||||
|
|
@ -1233,9 +1307,13 @@ class TestDescriptionPropagation:
|
|||
"Query parameter description missing from ResourceTemplate description"
|
||||
)
|
||||
|
||||
async def test_template_parameter_schema_includes_description(self, test_server):
|
||||
async def test_template_parameter_schema_includes_description(
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a ResourceTemplate's parameter schema includes parameter descriptions."""
|
||||
templates = list(test_server._resource_manager.get_templates().values())
|
||||
templates = list(
|
||||
simple_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
assert get_template is not None, "getItem template wasn't created"
|
||||
|
|
@ -1255,9 +1333,9 @@ class TestDescriptionPropagation:
|
|||
|
||||
# --- TOOL TESTS ---
|
||||
|
||||
async def test_tool_includes_route_description(self, test_server):
|
||||
async def test_tool_includes_route_description(self, simple_server_with_all_types):
|
||||
"""Test that a Tool includes the route description."""
|
||||
tools = test_server._tool_manager.list_tools()
|
||||
tools = simple_server_with_all_types._tool_manager.list_tools()
|
||||
create_tool = next((t for t in tools if t.name == "createItem"), None)
|
||||
|
||||
assert create_tool is not None, "createItem tool wasn't created"
|
||||
|
|
@ -1265,9 +1343,9 @@ class TestDescriptionPropagation:
|
|||
"Route description missing from Tool"
|
||||
)
|
||||
|
||||
async def test_tool_includes_function_docstring(self, test_server):
|
||||
async def test_tool_includes_function_docstring(self, simple_server_with_all_types):
|
||||
"""Test that a Tool includes the function docstring."""
|
||||
tools = test_server._tool_manager.list_tools()
|
||||
tools = simple_server_with_all_types._tool_manager.list_tools()
|
||||
create_tool = next((t for t in tools if t.name == "createItem"), None)
|
||||
|
||||
assert create_tool is not None, "createItem tool wasn't created"
|
||||
|
|
@ -1277,10 +1355,10 @@ class TestDescriptionPropagation:
|
|||
)
|
||||
|
||||
async def test_tool_parameter_schema_includes_property_description(
|
||||
self, test_server
|
||||
self, simple_server_with_all_types
|
||||
):
|
||||
"""Test that a Tool's parameter schema includes property descriptions from request model."""
|
||||
tools = test_server._tool_manager.list_tools()
|
||||
tools = simple_server_with_all_types._tool_manager.list_tools()
|
||||
create_tool = next((t for t in tools if t.name == "createItem"), None)
|
||||
|
||||
assert create_tool is not None, "createItem tool wasn't created"
|
||||
|
|
@ -1300,9 +1378,9 @@ class TestDescriptionPropagation:
|
|||
|
||||
# --- CLIENT API TESTS ---
|
||||
|
||||
async def test_client_api_resource_description(self, test_server):
|
||||
async def test_client_api_resource_description(self, simple_server_with_all_types):
|
||||
"""Test that Resource descriptions are accessible via the client API."""
|
||||
async with Client(test_server) as client:
|
||||
async with Client(simple_server_with_all_types) as client:
|
||||
resources = await client.list_resources()
|
||||
list_resource = next((r for r in resources if r.name == "listItems"), None)
|
||||
|
||||
|
|
@ -1314,9 +1392,9 @@ class TestDescriptionPropagation:
|
|||
"Route description missing in Resource from client API"
|
||||
)
|
||||
|
||||
async def test_client_api_template_description(self, test_server):
|
||||
async def test_client_api_template_description(self, simple_server_with_all_types):
|
||||
"""Test that ResourceTemplate descriptions are accessible via the client API."""
|
||||
async with Client(test_server) as client:
|
||||
async with Client(simple_server_with_all_types) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
get_template = next((t for t in templates if t.name == "getItem"), None)
|
||||
|
||||
|
|
@ -1328,9 +1406,9 @@ class TestDescriptionPropagation:
|
|||
"Route description missing in ResourceTemplate from client API"
|
||||
)
|
||||
|
||||
async def test_client_api_tool_description(self, test_server):
|
||||
async def test_client_api_tool_description(self, simple_server_with_all_types):
|
||||
"""Test that Tool descriptions are accessible via the client API."""
|
||||
async with Client(test_server) as client:
|
||||
async with Client(simple_server_with_all_types) as client:
|
||||
tools = await client.list_tools()
|
||||
create_tool = next((t for t in tools if t.name == "createItem"), None)
|
||||
|
||||
|
|
@ -1342,9 +1420,9 @@ class TestDescriptionPropagation:
|
|||
"Function docstring missing in Tool from client API"
|
||||
)
|
||||
|
||||
async def test_client_api_tool_parameter_schema(self, test_server):
|
||||
async def test_client_api_tool_parameter_schema(self, simple_server_with_all_types):
|
||||
"""Test that Tool parameter schemas are accessible via the client API."""
|
||||
async with Client(test_server) as client:
|
||||
async with Client(simple_server_with_all_types) as client:
|
||||
tools = await client.list_tools()
|
||||
create_tool = next((t for t in tools if t.name == "createItem"), None)
|
||||
|
||||
|
|
@ -1699,9 +1777,11 @@ class TestFastAPIDescriptionPropagation:
|
|||
class TestReprMethods:
|
||||
"""Tests for the custom __repr__ methods of OpenAPI objects."""
|
||||
|
||||
async def test_openapi_tool_repr(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_openapi_tool_repr(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that OpenAPITool's __repr__ method works without recursion errors."""
|
||||
tools = fastmcp_openapi_server._tool_manager.list_tools()
|
||||
tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()
|
||||
tool = next(iter(tools))
|
||||
|
||||
# Verify repr doesn't cause recursion and contains expected elements
|
||||
|
|
@ -1711,10 +1791,12 @@ class TestReprMethods:
|
|||
assert "method=" in tool_repr
|
||||
assert "path=" in tool_repr
|
||||
|
||||
async def test_openapi_resource_repr(self, fastmcp_openapi_server: FastMCPOpenAPI):
|
||||
async def test_openapi_resource_repr(
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that OpenAPIResource's __repr__ method works without recursion errors."""
|
||||
resources = list(
|
||||
fastmcp_openapi_server._resource_manager.get_resources().values()
|
||||
fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
|
||||
)
|
||||
resource = next(iter(resources))
|
||||
|
||||
|
|
@ -1726,11 +1808,11 @@ class TestReprMethods:
|
|||
assert "path=" in resource_repr
|
||||
|
||||
async def test_openapi_resource_template_repr(
|
||||
self, fastmcp_openapi_server: FastMCPOpenAPI
|
||||
self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
|
||||
):
|
||||
"""Test that OpenAPIResourceTemplate's __repr__ method works without recursion errors."""
|
||||
templates = list(
|
||||
fastmcp_openapi_server._resource_manager.get_templates().values()
|
||||
fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
|
||||
)
|
||||
template = next(iter(templates))
|
||||
|
||||
|
|
@ -2182,6 +2264,7 @@ class TestMCPNames:
|
|||
openapi_spec=mcp_names_openapi_spec,
|
||||
client=mock_client,
|
||||
mcp_names=mcp_names,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
# Check tools use custom names
|
||||
|
|
@ -2212,6 +2295,7 @@ class TestMCPNames:
|
|||
openapi_spec=mcp_names_openapi_spec,
|
||||
client=mock_client,
|
||||
mcp_names=mcp_names,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
tools = server._tool_manager.list_tools()
|
||||
|
|
@ -2235,6 +2319,7 @@ class TestMCPNames:
|
|||
server = FastMCPOpenAPI(
|
||||
openapi_spec=mcp_names_openapi_spec,
|
||||
client=mock_client,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
resources = list(server._resource_manager.get_resources().values())
|
||||
|
|
@ -2261,6 +2346,7 @@ class TestMCPNames:
|
|||
server = FastMCPOpenAPI(
|
||||
openapi_spec=mcp_names_openapi_spec,
|
||||
client=mock_client,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
# Check all component types
|
||||
|
|
@ -2299,9 +2385,9 @@ class TestMCPNames:
|
|||
mcp_names=mcp_names,
|
||||
)
|
||||
|
||||
resources = list(server._resource_manager.get_resources().values())
|
||||
resource_names = {resource.name for resource in resources}
|
||||
assert "openapi_user_list" in resource_names
|
||||
tools = server._tool_manager.list_tools()
|
||||
tool_names = {tool.name for tool in tools}
|
||||
assert "openapi_user_list" in tool_names
|
||||
|
||||
async def test_mcp_names_with_from_fastapi_classmethod(self):
|
||||
"""Test mcp_names works with FastMCP.from_fastapi() classmethod."""
|
||||
|
|
@ -2334,11 +2420,8 @@ class TestMCPNames:
|
|||
tools = server._tool_manager.list_tools()
|
||||
tool_names = {tool.name for tool in tools}
|
||||
|
||||
resources = list(server._resource_manager.get_resources().values())
|
||||
resource_names = {resource.name for resource in resources}
|
||||
|
||||
assert "fastapi_create_user" in tool_names
|
||||
assert "fastapi_user_list" in resource_names
|
||||
assert "fastapi_user_list" in tool_names
|
||||
|
||||
async def test_mcp_names_custom_names_are_also_truncated(
|
||||
self, mcp_names_openapi_spec, mock_client
|
||||
|
|
@ -2355,6 +2438,7 @@ class TestMCPNames:
|
|||
openapi_spec=mcp_names_openapi_spec,
|
||||
client=mock_client,
|
||||
mcp_names=mcp_names,
|
||||
route_maps=GET_ROUTE_MAPS,
|
||||
)
|
||||
|
||||
resources = list(server._resource_manager.get_resources().values())
|
||||
|
|
|
|||
|
|
@ -161,15 +161,15 @@ def test_route_map_fn_returns_none(sample_openapi_spec, http_client):
|
|||
|
||||
# Should have default behavior
|
||||
assert server.name == "Test Server"
|
||||
# Check that components were created with default types
|
||||
# Check that components were created with default mapping
|
||||
tools = server._tool_manager._tools
|
||||
resources = server._resource_manager._resources
|
||||
templates = server._resource_manager._templates
|
||||
|
||||
# Should have tools, resources, and templates based on default mapping
|
||||
assert len(tools) > 0
|
||||
assert len(resources) > 0
|
||||
assert len(templates) > 0
|
||||
assert len(resources) == 0
|
||||
assert len(templates) == 0
|
||||
|
||||
|
||||
def test_route_map_fn_called_for_excluded_routes(sample_openapi_spec, http_client):
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -701,7 +701,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."""
|
||||
|
|
@ -716,7 +716,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."""
|
||||
|
|
@ -780,7 +780,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:
|
||||
|
|
@ -931,7 +1027,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:
|
||||
|
|
@ -1236,7 +1428,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()
|
||||
|
|
@ -1252,7 +1444,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:
|
||||
|
|
@ -1441,6 +1726,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()
|
||||
|
|
@ -1470,7 +1851,7 @@ 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]
|
||||
|
||||
|
||||
class TestPromptTags:
|
||||
|
|
|
|||
|
|
@ -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():
|
||||
|
|
|
|||
989
tests/tools/test_tool_transform.py
Normal file
989
tests/tools/test_tool_transform.py
Normal 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})
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ from fastmcp.utilities.tests import temporary_settings
|
|||
|
||||
class TestTemporarySettings:
|
||||
def test_temporary_settings(self):
|
||||
assert fastmcp.settings.settings.log_level == "DEBUG"
|
||||
assert fastmcp.settings.log_level == "DEBUG"
|
||||
with temporary_settings(log_level="ERROR"):
|
||||
assert fastmcp.settings.settings.log_level == "ERROR"
|
||||
assert fastmcp.settings.settings.log_level == "DEBUG"
|
||||
assert fastmcp.settings.log_level == "ERROR"
|
||||
assert fastmcp.settings.log_level == "DEBUG"
|
||||
|
|
|
|||
|
|
@ -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."""
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue