mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-23 14:04:18 +02:00
Merge branch 'main' into nits
This commit is contained in:
commit
bbf396f514
29 changed files with 2858 additions and 1183 deletions
38
README.md
38
README.md
|
|
@ -112,7 +112,7 @@ FastMCP aims to be:
|
|||
### Servers
|
||||
- **Create** servers with minimal boilerplate using intuitive decorators
|
||||
- **Proxy** existing servers to modify configuration or transport
|
||||
- **Compose** servers by into complex applications
|
||||
- **Compose** servers into complex applications
|
||||
- **Generate** servers from OpenAPI specs or FastAPI objects
|
||||
|
||||
### Clients
|
||||
|
|
@ -332,32 +332,32 @@ The `Context` object provides:
|
|||
|
||||
### Images
|
||||
|
||||
Easily handle image input and output using the `fastmcp.Image` helper class.
|
||||
Easily handle image outputs using the `fastmcp.Image` helper class.
|
||||
|
||||
<Tip>
|
||||
The below code requires the `pillow` library to be installed.
|
||||
</Tip>
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP, Image
|
||||
from PIL import Image as PILImage
|
||||
import io
|
||||
from mcp.server.fastmcp import FastMCP, Image
|
||||
from io import BytesIO
|
||||
try:
|
||||
from PIL import Image as PILImage
|
||||
except ImportError:
|
||||
raise ImportError("Please install the `pillow` library to run this example.")
|
||||
|
||||
mcp = FastMCP("Image Demo")
|
||||
mcp = FastMCP("My App")
|
||||
|
||||
@mcp.tool()
|
||||
def create_thumbnail(image_data: Image) -> Image:
|
||||
"""Creates a 100x100 thumbnail from the provided image."""
|
||||
img = PILImage.open(io.BytesIO(image_data.data)) # Assumes image_data received as Image with bytes
|
||||
img.thumbnail((100, 100))
|
||||
buffer = io.BytesIO()
|
||||
def create_thumbnail(image_path: str) -> Image:
|
||||
"""Create a thumbnail from an image"""
|
||||
img = PILImage.open(image_path)
|
||||
img.thumbnail((100, 100))
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, format="PNG")
|
||||
# Return a new Image object with the thumbnail data
|
||||
return Image(data=buffer.getvalue(), format="png")
|
||||
|
||||
@mcp.tool()
|
||||
def load_image_from_disk(path: str) -> Image:
|
||||
"""Loads an image from the specified path."""
|
||||
# Handles reading file and detecting format based on extension
|
||||
return Image(path=path)
|
||||
```
|
||||
FastMCP handles the conversion to/from the base64-encoded format required by the MCP protocol.
|
||||
Return the `Image` helper class from your tool to send an image to the client. The `Image` helper class handles the conversion to/from the base64-encoded format required by the MCP protocol. It works with either a path to an image file, or a bytes object.
|
||||
|
||||
|
||||
### MCP Clients
|
||||
|
|
|
|||
|
|
@ -5,6 +5,10 @@ description: Understand the different ways FastMCP Clients can connect to server
|
|||
icon: link
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
The FastMCP `Client` relies on a `ClientTransport` object to handle the specifics of connecting to and communicating with an MCP server. FastMCP provides several built-in transport implementations for common connection methods.
|
||||
|
||||
While the `Client` often infers the correct transport automatically (see [Client Overview](/clients/client#transport-inference)), you can also instantiate transports explicitly for more control.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ description: "Community-contributed modules extending FastMCP"
|
|||
icon: "cubes"
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="2.2.1" />
|
||||
|
||||
FastMCP includes a `contrib` package that holds community-contributed modules. These modules extend FastMCP's functionality but aren't officially maintained by the core team.
|
||||
|
||||
|
|
|
|||
|
|
@ -14,18 +14,20 @@ FastMCP provides a powerful proxying capability that allows one FastMCP server i
|
|||
|
||||
Proxying means setting up a FastMCP server that doesn't implement its own tools or resources directly. Instead, when it receives a request (like `tools/call` or `resources/read`), it forwards that request to a *backend* MCP server, receives the response, and then relays that response back to the original client.
|
||||
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant ProxyServer as FastMCP Proxy Server
|
||||
participant BackendServer as Backend MCP Server
|
||||
participant ClientApp as Your Client (e.g., Claude Desktop)
|
||||
participant FastMCPProxy as FastMCP Proxy Server
|
||||
participant BackendServer as Backend MCP Server (e.g., remote SSE)
|
||||
|
||||
Client->>ProxyServer: Request (e.g., stdio)
|
||||
ProxyServer->>BackendServer: Request (e.g., sse)
|
||||
BackendServer-->>ProxyServer: Response (e.g., sse)
|
||||
ProxyServer-->>Client: Response (e.g., stdio)
|
||||
ClientApp->>FastMCPProxy: MCP Request (e.g. stdio)
|
||||
Note over FastMCPProxy, BackendServer: Proxy forwards the request
|
||||
FastMCPProxy->>BackendServer: MCP Request (e.g. sse)
|
||||
BackendServer-->>FastMCPProxy: MCP Response (e.g. sse)
|
||||
Note over ClientApp, FastMCPProxy: Proxy relays the response
|
||||
FastMCPProxy-->>ClientApp: MCP Response (e.g. stdio)
|
||||
```
|
||||
|
||||
### Use Cases
|
||||
|
||||
- **Transport Bridging**: Expose a server running on one transport (e.g., a remote SSE server) via a different transport (e.g., local Stdio for Claude Desktop).
|
||||
|
|
|
|||
|
|
@ -1,16 +1,16 @@
|
|||
---
|
||||
title: MCP Context
|
||||
sidebarTitle: Context
|
||||
description: Access MCP capabilities like logging, progress, and resources within your tools.
|
||||
description: Access MCP capabilities like logging, progress, and resources within your MCP objects.
|
||||
icon: rectangle-code
|
||||
---
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
When defining FastMCP [tools](/servers/tools), your functions might need to interact with the underlying MCP session or access server capabilities. FastMCP provides the `Context` object for this purpose.
|
||||
When defining FastMCP [tools](/servers/tools), [resources](/servers/resources), resource templates, or [prompts](/servers/prompts), your functions might need to interact with the underlying MCP session or access server capabilities. FastMCP provides the `Context` object for this purpose.
|
||||
|
||||
## What Is Context?
|
||||
|
||||
The `Context` object provides a clean interface to access MCP features within your tool functions, including:
|
||||
The `Context` object provides a clean interface to access MCP features within your functions, including:
|
||||
|
||||
- **Logging**: Send debug, info, warning, and error messages back to the client
|
||||
- **Progress Reporting**: Update the client on the progress of long-running operations
|
||||
|
|
@ -19,9 +19,9 @@ The `Context` object provides a clean interface to access MCP features within yo
|
|||
- **Request Information**: Access metadata about the current request
|
||||
- **Server Access**: When needed, access the underlying FastMCP server instance
|
||||
|
||||
## Accessing Context
|
||||
## Accessing the Context
|
||||
|
||||
To use the context object within your tool function, simply add a parameter to your function signature and type-hint it as `Context`. FastMCP will automatically inject the context instance when your tool is called.
|
||||
To use the context object within any of your functions, simply add a parameter to your function signature and type-hint it as `Context`. FastMCP will automatically inject the context instance when your function is called.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP, Context
|
||||
|
|
@ -65,15 +65,15 @@ async def process_file(file_uri: str, ctx: Context) -> str:
|
|||
|
||||
- The parameter name (e.g., `ctx`, `context`) doesn't matter, only the type hint `Context` is important.
|
||||
- The context parameter can be placed anywhere in your function's signature.
|
||||
- The context is optional - tools that don't need it can omit the parameter.
|
||||
- Context is only available within tool functions during a request; attempting to use context methods outside a request will raise errors.
|
||||
- Context methods are async, so your tool function usually needs to be async as well.
|
||||
- The context is optional - functions that don't need it can omit the parameter.
|
||||
- Context is only available during a request; attempting to use context methods outside a request will raise errors.
|
||||
- Context methods are async, so your function usually needs to be async as well.
|
||||
|
||||
## Context Capabilities
|
||||
|
||||
### Logging
|
||||
|
||||
Send log messages back to the MCP client. This is useful for debugging and providing visibility into tool execution during a request.
|
||||
Send log messages back to the MCP client. This is useful for debugging and providing visibility into function execution during a request.
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
|
|
@ -97,14 +97,14 @@ async def analyze_data(data: list[float], ctx: Context) -> dict:
|
|||
**Available Logging Methods:**
|
||||
|
||||
- **`ctx.debug(message: str)`**: Low-level details useful for debugging
|
||||
- **`ctx.info(message: str)`**: General information about tool execution
|
||||
- **`ctx.info(message: str)`**: General information about execution
|
||||
- **`ctx.warning(message: str)`**: Potential issues that didn't prevent execution
|
||||
- **`ctx.error(message: str)`**: Errors that occurred during execution
|
||||
- **`ctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None)`**: Generic log method supporting custom logger names
|
||||
|
||||
### Progress Reporting
|
||||
|
||||
For long-running tools, notify the client about the progress of the operation. This allows clients to display progress indicators and provide a better user experience.
|
||||
For long-running operations, notify the client about the progress. This allows clients to display progress indicators and provide a better user experience.
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
|
|
@ -137,7 +137,7 @@ Progress reporting requires the client to have sent a `progressToken` in the ini
|
|||
|
||||
### Resource Access
|
||||
|
||||
Read data from resources registered with your FastMCP server. This allows tools to access files, configuration, or dynamically generated content.
|
||||
Read data from resources registered with your FastMCP server. This allows functions to access files, configuration, or dynamically generated content.
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
|
|
@ -177,7 +177,7 @@ The returned content is typically accessed via `content_list[0].content` and can
|
|||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Request the client's LLM to generate text based on provided messages. This is useful when your tool needs to leverage the LLM's capabilities to process data or generate responses.
|
||||
Request the client's LLM to generate text based on provided messages. This is useful when your function needs to leverage the LLM's capabilities to process data or generate responses.
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
|
|
@ -279,6 +279,60 @@ async def advanced_tool(ctx: Context) -> str:
|
|||
Direct use of `session` or `request_context` requires understanding the low-level MCP Python SDK and may be less stable than using the methods provided directly on the `Context` object.
|
||||
</Warning>
|
||||
|
||||
## Using Context in Other Components
|
||||
## Using Context in Different Components
|
||||
|
||||
Currently, Context is primarily designed for use within tool functions. Support for Context in other components like resources and prompts is planned for future releases.
|
||||
All FastMCP components (tools, resources, templates, and prompts) can use the Context object following the same pattern - simply add a parameter with the `Context` type annotation.
|
||||
|
||||
### Context in Resources and Templates
|
||||
|
||||
Resources and resource templates can access context to customize their behavior:
|
||||
|
||||
```python
|
||||
@mcp.resource("resource://user-data")
|
||||
async def get_user_data(ctx: Context) -> dict:
|
||||
"""Fetch personalized user data based on the request context."""
|
||||
user_id = ctx.client_id or "anonymous"
|
||||
await ctx.info(f"Fetching data for user {user_id}")
|
||||
|
||||
# Example of using context for dynamic resource generation
|
||||
return {
|
||||
"user_id": user_id,
|
||||
"last_access": datetime.now().isoformat(),
|
||||
"request_id": ctx.request_id
|
||||
}
|
||||
|
||||
@mcp.resource("resource://users/{user_id}/profile")
|
||||
async def get_user_profile(user_id: str, ctx: Context) -> dict:
|
||||
"""Fetch user profile from database with context-aware logging."""
|
||||
await ctx.info(f"Fetching profile for user {user_id}")
|
||||
|
||||
# Example of using context in a template resource
|
||||
# In a real implementation, you might query a database
|
||||
return {
|
||||
"id": user_id,
|
||||
"name": f"User {user_id}",
|
||||
"request_id": ctx.request_id
|
||||
}
|
||||
```
|
||||
|
||||
### Context in Prompts
|
||||
|
||||
Prompts can use context to generate more dynamic templates:
|
||||
|
||||
```python
|
||||
@mcp.prompt()
|
||||
async def data_analysis_request(dataset: str, ctx: Context) -> str:
|
||||
"""Generate a request to analyze data with contextual information."""
|
||||
await ctx.info(f"Generating data analysis prompt for {dataset}")
|
||||
|
||||
# Could use context to read configuration or personalize the prompt
|
||||
return f"""Please analyze the following dataset: {dataset}
|
||||
|
||||
Request initiated at: {datetime.now().isoformat()}
|
||||
Request ID: {ctx.request_id}
|
||||
"""
|
||||
```
|
||||
|
||||
<VersionBadge version="2.3.0" />
|
||||
|
||||
All FastMCP objects now support context injection using the same consistent pattern, making it easy to add session-aware capabilities to all aspects of your MCP server.
|
||||
|
|
@ -5,6 +5,8 @@ description: Learn about the core FastMCP server class and how to run it.
|
|||
icon: server
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
The central piece of a FastMCP application is the `FastMCP` server class. This class acts as the main container for your application's tools, resources, and prompts, and manages communication with MCP clients.
|
||||
|
||||
## Creating a Server
|
||||
|
|
@ -225,6 +227,8 @@ The CLI can dynamically find and run FastMCP server objects in your files, but i
|
|||
|
||||
## Composing Servers
|
||||
|
||||
<VersionBadge version="2.2.0" />
|
||||
|
||||
FastMCP supports composing multiple servers together using `import_server` (static copy) and `mount` (live link). This allows you to organize large applications into modular components or reuse existing servers.
|
||||
|
||||
See the [Server Composition](/patterns/composition) guide for full details, best practices, and examples.
|
||||
|
|
@ -246,6 +250,8 @@ main.mount("sub", sub)
|
|||
|
||||
## Proxying Servers
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
FastMCP can act as a proxy for any MCP server (local or remote) using `FastMCP.from_client`, letting you bridge transports or add a frontend to existing servers. For example, you can expose a remote SSE server locally via stdio, or vice versa.
|
||||
|
||||
See the [Proxying Servers](/patterns/proxy) guide for details and advanced usage.
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ description: Create reusable, parameterized prompt templates for MCP clients.
|
|||
icon: message-lines
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
Prompts are reusable message templates that help LLMs generate structured, purposeful responses. FastMCP simplifies defining these templates, primarily using the `@mcp.prompt` decorator.
|
||||
|
||||
## What Are Prompts?
|
||||
|
|
@ -18,7 +20,7 @@ Prompts provide parameterized message templates for LLMs. When a client requests
|
|||
|
||||
This allows you to define consistent, reusable templates that LLMs can use across different clients and contexts.
|
||||
|
||||
## Defining Prompts
|
||||
## Prompts
|
||||
|
||||
### The `@prompt` Decorator
|
||||
|
||||
|
|
@ -169,38 +171,31 @@ async def data_based_prompt(data_id: str) -> str:
|
|||
|
||||
Use `async def` when your prompt function performs I/O operations like network requests, database queries, file I/O, or external service calls.
|
||||
|
||||
### The MCP Session
|
||||
### Accessing MCP Context
|
||||
|
||||
Prompts can access the MCP features via the `Context` object, just like tools.
|
||||
<VersionBadge version="2.2.5" />
|
||||
|
||||
```python
|
||||
from fastmcp import Context
|
||||
Prompts can access additional MCP information and features through the `Context` object. To access it, add a parameter to your prompt function with a type annotation of `Context`:
|
||||
|
||||
```python {6}
|
||||
from fastmcp import FastMCP, Context
|
||||
|
||||
mcp = FastMCP(name="PromptServer")
|
||||
|
||||
@mcp.prompt()
|
||||
async def generate_report_request(report_type: str, ctx: Context) -> str:
|
||||
"""Generates a request for a report based on available data."""
|
||||
# Log the request
|
||||
await ctx.info(f"Generating prompt for report type: {report_type}")
|
||||
|
||||
# Could potentially use ctx.read_resource to fetch data
|
||||
# Or ctx.sample to get additional input from the LLM
|
||||
|
||||
return f"Please create a {report_type} report based on the available data."
|
||||
"""Generates a request for a report."""
|
||||
return f"Please create a {report_type} report. Request ID: {ctx.request_id}"
|
||||
```
|
||||
|
||||
Using the `ctx` parameter (based on its `Context` type hint), you can access:
|
||||
|
||||
- **Logging:** `ctx.debug()`, `ctx.info()`, etc.
|
||||
- **Resource Access:** `ctx.read_resource(uri)`
|
||||
- **LLM Sampling:** `ctx.sample(...)`
|
||||
- **Request Info:** `ctx.request_id`, `ctx.client_id`
|
||||
|
||||
Refer to the [Context documentation](/servers/context) for more details on these capabilities.
|
||||
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
|
||||
|
||||
## Server Behavior
|
||||
|
||||
### Duplicate Prompts
|
||||
|
||||
<VersionBadge version="2.1.0" />
|
||||
|
||||
You can configure how the FastMCP server handles attempts to register multiple prompts with the same name. Use the `on_duplicate_prompts` setting during `FastMCP` initialization.
|
||||
|
||||
```python
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
---
|
||||
title: Resources & Templates
|
||||
sidebarTitle: Resources & Templates
|
||||
sidebarTitle: Resources
|
||||
description: Expose data sources and dynamic content generators to your MCP client.
|
||||
icon: database
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
Resources represent data or files that an MCP client can read, and resource templates extend this concept by allowing clients to request dynamically generated resources based on parameters passed in the URI.
|
||||
|
||||
FastMCP simplifies defining both static and dynamic resources, primarily using the `@mcp.resource` decorator.
|
||||
|
|
@ -19,7 +21,7 @@ Resources provide read-only access to data for the LLM or client application. Wh
|
|||
|
||||
This allows LLMs to access files, database content, configuration, or dynamically generated information relevant to the conversation.
|
||||
|
||||
## Defining Resources
|
||||
## Resources
|
||||
|
||||
### The `@resource` Decorator
|
||||
|
||||
|
|
@ -93,6 +95,36 @@ def get_application_status() -> dict:
|
|||
- **`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.
|
||||
|
||||
### Accessing MCP Context
|
||||
|
||||
<VersionBadge version="2.2.5" />
|
||||
|
||||
Resources and resource templates can access additional MCP information and features through the `Context` object. To access it, add a parameter to your resource function with a type annotation of `Context`:
|
||||
|
||||
```python {6, 14}
|
||||
from fastmcp import FastMCP, Context
|
||||
|
||||
mcp = FastMCP(name="DataServer")
|
||||
|
||||
@mcp.resource("resource://system-status")
|
||||
async def get_system_status(ctx: Context) -> dict:
|
||||
"""Provides system status information."""
|
||||
return {
|
||||
"status": "operational",
|
||||
"request_id": ctx.request_id
|
||||
}
|
||||
|
||||
@mcp.resource("resource://{name}/details")
|
||||
async def get_details(name: str, ctx: Context) -> dict:
|
||||
"""Get details for a specific name."""
|
||||
return {
|
||||
"name": name,
|
||||
"accessed_at": ctx.request_id
|
||||
}
|
||||
```
|
||||
|
||||
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
|
||||
|
||||
|
||||
### Asynchronous Resources
|
||||
|
||||
|
|
@ -183,6 +215,8 @@ Use these when the content is static or sourced directly from a file/URL, bypass
|
|||
|
||||
#### Custom Resource Keys
|
||||
|
||||
<VersionBadge version="2.2.0" />
|
||||
|
||||
When adding resources directly with `mcp.add_resource()`, you can optionally provide a custom storage key:
|
||||
|
||||
```python
|
||||
|
|
@ -197,10 +231,16 @@ mcp.add_resource(special_resource, key="internal://data-v2") # Will be stored a
|
|||
|
||||
Note that this parameter is only available when using `add_resource()` directly and not through the `@resource` decorator, as URIs are provided explicitly when using the decorator.
|
||||
|
||||
## Defining Resource Templates
|
||||
## Resource Templates
|
||||
|
||||
Resource Templates allow clients to request resources whose content depends on parameters embedded in the URI. Define a template using the **same `@mcp.resource` decorator**, but include `{parameter_name}` placeholders in the URI string and add corresponding arguments to your function signature.
|
||||
|
||||
Resource templates share most configuration options with regular resources (name, description, mime_type, tags), but add the ability to define URI parameters that map to function parameters.
|
||||
|
||||
Resource templates generate a new resource for each unique set of parameters, which means that resources can be dynamically created on-demand. For example, if the resource template `"user://profile/{name}"` is registered, MCP clients could request `"user://profile/ford"` or `"user://profile/marvin"` to retrieve either of those two user profiles as resources, without having to register each resource individually.
|
||||
|
||||
Here is a complete example that shows how to define two resource templates:
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
||||
|
|
@ -233,11 +273,69 @@ def get_repo_info(owner: str, repo: str) -> dict:
|
|||
}
|
||||
```
|
||||
|
||||
With these templates defined, clients can request:
|
||||
With these two templates defined, clients can request a variety of resources:
|
||||
- `weather://london/current` → Returns weather for London
|
||||
- `repos://fastmcp/docs/info` → Returns info about the fastmcp/docs repository
|
||||
- `weather://paris/current` → Returns weather for Paris
|
||||
- `repos://jlowin/fastmcp/info` → Returns info about the jlowin/fastmcp repository
|
||||
- `repos://prefecthq/prefect/info` → Returns info about the prefecthq/prefect repository
|
||||
|
||||
### Parameters and Default Values
|
||||
### Wildcard Parameters
|
||||
|
||||
<VersionBadge version="2.2.4" />
|
||||
|
||||
<Tip>
|
||||
Please note: FastMCP's support for wildcard parameters is an **extension** of the Model Context Protocol standard, which otherwise follows RFC 6570. Since all template processing happens in the FastMCP server, this should not cause any compatibility issues with other MCP implementations.
|
||||
</Tip>
|
||||
|
||||
|
||||
Resource templates support wildcard parameters that can match multiple path segments. While standard parameters (`{param}`) only match a single path segment and don't cross "/" boundaries, wildcard parameters (`{param*}`) can capture multiple segments including slashes. Wildcards capture all subsequent path segments *up until* the defined part of the URI template (whether literal or another parameter). This allows you to have multiple wildcard parameters in a single URI template.
|
||||
|
||||
```python {15, 23}
|
||||
from fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP(name="DataServer")
|
||||
|
||||
|
||||
# Standard parameter only matches one segment
|
||||
@mcp.resource("files://{filename}")
|
||||
def get_file(filename: str) -> str:
|
||||
"""Retrieves a file by name."""
|
||||
# Will only match files://<single-segment>
|
||||
return f"File content for: {filename}"
|
||||
|
||||
|
||||
# Wildcard parameter can match multiple segments
|
||||
@mcp.resource("path://{filepath*}")
|
||||
def get_path_content(filepath: str) -> str:
|
||||
"""Retrieves content at a specific path."""
|
||||
# Can match path://docs/server/resources.mdx
|
||||
return f"Content at path: {filepath}"
|
||||
|
||||
|
||||
# Mixing standard and wildcard parameters
|
||||
@mcp.resource("repo://{owner}/{path*}/template.py")
|
||||
def get_template_file(owner: str, path: str) -> dict:
|
||||
"""Retrieves a file from a specific repository and path, but
|
||||
only if the resource ends with `template.py`"""
|
||||
# Can match repo://jlowin/fastmcp/src/resources/template.py
|
||||
return {
|
||||
"owner": owner,
|
||||
"path": path + "/template.py",
|
||||
"content": f"File at {path}/template.py in {owner}'s repository"
|
||||
}
|
||||
```
|
||||
|
||||
Wildcard parameters are useful when:
|
||||
|
||||
- Working with file paths or hierarchical data
|
||||
- Creating APIs that need to capture variable-length path segments
|
||||
- Building URL-like patterns similar to REST APIs
|
||||
|
||||
Note that like regular parameters, each wildcard parameter must still be a named parameter in your function signature, and all required function parameters must appear in the URI template.
|
||||
|
||||
### Default Values
|
||||
|
||||
<VersionBadge version="2.2.0" />
|
||||
|
||||
When creating resource templates, FastMCP enforces two rules for the relationship between URI template parameters and function parameters:
|
||||
|
||||
|
|
@ -313,30 +411,12 @@ In this stacked decorator pattern:
|
|||
|
||||
Templates provide a powerful way to expose parameterized data access points following REST-like principles.
|
||||
|
||||
### Custom Template Keys
|
||||
|
||||
Similar to resources, you can provide custom keys when directly adding templates:
|
||||
|
||||
```python
|
||||
from fastmcp.resources import ResourceTemplate
|
||||
|
||||
# Create a template with a function
|
||||
template = ResourceTemplate.from_function(
|
||||
my_function,
|
||||
uri_template="data://{id}/details",
|
||||
name="Data Details"
|
||||
)
|
||||
|
||||
# Register with a custom key
|
||||
mcp._resource_manager.add_template(template, key="custom://{id}/view")
|
||||
```
|
||||
|
||||
This allows accessing the same template implementation through different URI patterns.
|
||||
|
||||
## Server Behavior
|
||||
|
||||
### Duplicate Resources
|
||||
|
||||
<VersionBadge version="2.1.0" />
|
||||
|
||||
You can configure how the FastMCP server handles attempts to register multiple resources or templates with the same URI. Use the `on_duplicate_resources` setting during `FastMCP` initialization.
|
||||
|
||||
```python
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ Tools in FastMCP transform regular Python functions into capabilities that LLMs
|
|||
|
||||
This allows LLMs to perform tasks like querying databases, calling APIs, making calculations, or accessing files—extending their capabilities beyond what's in their training data.
|
||||
|
||||
## Defining Tools
|
||||
## Tools
|
||||
|
||||
### The `@tool` Decorator
|
||||
|
||||
|
|
@ -44,114 +44,105 @@ When this tool is registered, FastMCP automatically:
|
|||
|
||||
The way you define your Python function dictates how the tool appears and behaves for the LLM client.
|
||||
|
||||
### Type Annotations
|
||||
### Parameters
|
||||
|
||||
Type annotations are crucial. They:
|
||||
1. Inform the LLM about the expected type for each parameter.
|
||||
2. Allow FastMCP to validate the data received from the client.
|
||||
3. Are used to generate the tool's input schema for the MCP protocol.
|
||||
#### Annotations
|
||||
|
||||
FastMCP supports standard Python type annotations, including those from the `typing` module and Pydantic.
|
||||
Type annotations for parameters are essential for proper tool functionality. They:
|
||||
1. Inform the LLM about the expected data types for each parameter
|
||||
2. Enable FastMCP to validate input data from clients
|
||||
3. Generate accurate JSON schemas for the MCP protocol
|
||||
|
||||
Use standard Python type annotations for parameters:
|
||||
|
||||
```python
|
||||
from typing import Literal, Optional, Union
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# Example using various type hints
|
||||
@mcp.tool()
|
||||
def process_data(
|
||||
data: list[float], # List of floats
|
||||
operation: Literal["sum", "average", "max"], # Fixed choices
|
||||
precision: int = 2, # Optional int with default
|
||||
description: str | None = None # Optional string (can be None)
|
||||
def analyze_text(
|
||||
text: str,
|
||||
max_tokens: int = 100,
|
||||
language: str | None = None
|
||||
) -> dict:
|
||||
"""Process numerical data with the specified operation."""
|
||||
result = 0.0
|
||||
if operation == "sum":
|
||||
result = sum(data)
|
||||
elif operation == "average":
|
||||
result = sum(data) / len(data) if data else 0.0
|
||||
elif operation == "max":
|
||||
result = float(max(data)) if data else 0.0
|
||||
|
||||
return {
|
||||
"operation": operation,
|
||||
"result": round(result, precision),
|
||||
"description": description
|
||||
}
|
||||
"""Analyze the provided text."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
**Supported Type Annotation Examples:**
|
||||
#### Parameter Metadata
|
||||
|
||||
You can provide additional metadata about parameters using Pydantic's `Field` class with `Annotated`. This approach is preferred as it's more modern and keeps type hints separate from validation rules:
|
||||
|
||||
```python
|
||||
from typing import Annotated
|
||||
from pydantic import Field
|
||||
|
||||
@mcp.tool()
|
||||
def process_image(
|
||||
image_url: Annotated[str, Field(description="URL of the image to process")],
|
||||
resize: Annotated[bool, Field(description="Whether to resize the image")] = False,
|
||||
width: Annotated[int, Field(description="Target width in pixels", ge=1, le=2000)] = 800,
|
||||
format: Annotated[
|
||||
Literal["jpeg", "png", "webp"],
|
||||
Field(description="Output image format")
|
||||
] = "jpeg"
|
||||
) -> dict:
|
||||
"""Process an image with optional resizing."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
You can also use the Field as a default value, though the Annotated approach is preferred:
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def search_database(
|
||||
query: str = Field(description="Search query string"),
|
||||
limit: int = Field(10, description="Maximum number of results", ge=1, le=100)
|
||||
) -> list:
|
||||
"""Search the database with the provided query."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
Field provides several validation and documentation features:
|
||||
- `description`: Human-readable explanation of the parameter (shown to LLMs)
|
||||
- `ge`/`gt`/`le`/`lt`: Greater/less than (or equal) constraints
|
||||
- `min_length`/`max_length`: String or collection length constraints
|
||||
- `pattern`: Regex pattern for string validation
|
||||
- `default`: Default value if parameter is omitted
|
||||
|
||||
#### Supported Types
|
||||
|
||||
FastMCP supports a wide range of type annotations, including all Pydantic types:
|
||||
|
||||
| Type Annotation | Example | Description |
|
||||
| :---------------------- | :---------------------------- | :---------------------------------- |
|
||||
| Basic types | `int`, `float`, `str`, `bool` | Simple scalar values |
|
||||
| Container types | `list[str]`, `dict[str, int]` | Collections of items |
|
||||
| Optional types | `Optional[float]`, `float\|None`| Parameters that may be null/omitted |
|
||||
| Union types | `str \| int`, `Union[str, int]`| Parameters accepting multiple types |
|
||||
| Literal types | `Literal["A", "B"]` | Parameters with specific allowed values |
|
||||
| Pydantic models | `UserData` | Complex structured data (see below) |
|
||||
| Basic types | `int`, `float`, `str`, `bool` | Simple scalar values - see [Built-in Types](#built-in-types) |
|
||||
| Binary data | `bytes` | Binary content - see [Binary Data](#binary-data) |
|
||||
| Date and Time | `datetime`, `date`, `timedelta` | Date and time objects - see [Date and Time Types](#date-and-time-types) |
|
||||
| Collection types | `list[str]`, `dict[str, int]`, `set[int]` | Collections of items - see [Collection Types](#collection-types) |
|
||||
| Optional types | `float \| None`, `Optional[float]`| Parameters that may be null/omitted - see [Union and Optional Types](#union-and-optional-types) |
|
||||
| Union types | `str \| int`, `Union[str, int]`| Parameters accepting multiple types - see [Union and Optional Types](#union-and-optional-types) |
|
||||
| Constrained types | `Literal["A", "B"]`, `Enum` | Parameters with specific allowed values - see [Constrained Types](#constrained-types) |
|
||||
| Paths | `Path` | File system paths - see [Paths](#paths) |
|
||||
| UUIDs | `UUID` | Universally unique identifiers - see [UUIDs](#uuids) |
|
||||
| Pydantic models | `UserData` | Complex structured data - see [Pydantic Models](#pydantic-models) |
|
||||
|
||||
<Tip>
|
||||
**Automatic JSON Parsing:** FastMCP intelligently handles arguments. If a client sends a string that looks like valid JSON (e.g., `"['a', 'b']"`) for a parameter hinted as a structured type (like `list[str]` or a Pydantic model), FastMCP will automatically attempt to parse the JSON string into the expected Python object before validation. This improves robustness when interacting with various clients.
|
||||
</Tip>
|
||||
For additional type annotations not listed here, see the [Parameter Types](#parameter-types) section below for more detailed information and examples.
|
||||
|
||||
### Required vs. Optional Parameters
|
||||
#### Optional Arguments
|
||||
|
||||
Parameters in your function signature are considered **required** unless they have a default value.
|
||||
FastMCP follows Python's standard function parameter conventions. Parameters without default values are required, while those with default values are optional.
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def search_products(
|
||||
query: str, # Required - no default value
|
||||
max_results: int = 10, # Optional - has default value
|
||||
sort_by: str = "relevance" # Optional - has default value
|
||||
query: str, # Required - no default value
|
||||
max_results: int = 10, # Optional - has default value
|
||||
sort_by: str = "relevance", # Optional - has default value
|
||||
category: str | None = None # Optional - can be None
|
||||
) -> list[dict]:
|
||||
"""Search the product catalog."""
|
||||
# Implementation...
|
||||
print(f"Searching for '{query}', max {max_results}, sorted by {sort_by}")
|
||||
return [{"id": 1, "name": "Sample Product"}]
|
||||
```
|
||||
|
||||
In this example, the LLM *must* provide a `query`. If `max_results` or `sort_by` are omitted, their default values will be used.
|
||||
|
||||
### Structured Inputs
|
||||
|
||||
For tools requiring complex, nested, or well-validated inputs, use Pydantic models. Define a `BaseModel` and use it as a type hint for a parameter.
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
from datetime import date
|
||||
|
||||
class ReservationRequest(BaseModel):
|
||||
guest_name: str = Field(description="Full name of the guest making the reservation.")
|
||||
check_in: date
|
||||
check_out: date
|
||||
room_type: Literal["standard", "deluxe", "suite"] = Field(default="standard", description="Type of room requested.")
|
||||
guests: int = Field(gt=0, description="Number of guests (must be positive).")
|
||||
special_requests: Optional[str] = Field(default=None, description="Any special requests for the stay.")
|
||||
|
||||
@mcp.tool()
|
||||
def make_reservation(request: ReservationRequest) -> dict:
|
||||
"""Creates a new hotel reservation based on the provided details."""
|
||||
# Pydantic automatically validates the incoming 'request' data
|
||||
# against the ReservationRequest model before this function runs.
|
||||
print(f"Making reservation for {request.guest_name}...")
|
||||
# Implementation...
|
||||
return {
|
||||
"reservation_id": "R12345",
|
||||
"status": "confirmed",
|
||||
"guest": request.guest_name,
|
||||
"dates": f"{request.check_in} to {request.check_out}"
|
||||
}
|
||||
```
|
||||
|
||||
Using Pydantic models provides:
|
||||
- Clear, self-documenting structure for complex inputs.
|
||||
- Built-in data validation (e.g., `gt=0`, date parsing).
|
||||
- Automatic generation of detailed JSON schemas for the LLM.
|
||||
- Easy handling of optional fields and default values.
|
||||
In this example, the LLM must provide a `query` parameter, while `max_results`, `sort_by`, and `category` will use their default values if not explicitly provided.
|
||||
|
||||
### Metadata
|
||||
|
||||
|
|
@ -209,13 +200,24 @@ FastMCP automatically converts the value returned by your function into the appr
|
|||
- **`str`**: Sent as `TextContent`.
|
||||
- **`dict`, `list`, Pydantic `BaseModel`**: Serialized to a JSON string and sent as `TextContent`.
|
||||
- **`bytes`**: Base64 encoded and sent as `BlobResourceContents` (often within an `EmbeddedResource`).
|
||||
- **`fastmcp.utilities.types.Image`**: A helper class to easily return image data. Sent as `ImageContent`.
|
||||
- **`fastmcp.Image`**: A helper class for easily returning image data. Sent as `ImageContent`.
|
||||
- **`None`**: Results in an empty response (no content is sent back to the client).
|
||||
|
||||
FastMCP will attempt to serialize other types to a string if possible.
|
||||
|
||||
<Tip>
|
||||
At this time, FastMCP responds only to your tool's return *value*, not its return *annotation*.
|
||||
</Tip>
|
||||
|
||||
```python
|
||||
from fastmcp.utilities.types import Image
|
||||
from PIL import Image as PILImage
|
||||
from fastmcp import FastMCP, Image
|
||||
import io
|
||||
try:
|
||||
from PIL import Image as PILImage
|
||||
except ImportError:
|
||||
raise ImportError("Please install the `pillow` library to run this example.")
|
||||
|
||||
mcp = FastMCP("Image Demo")
|
||||
|
||||
@mcp.tool()
|
||||
def generate_image(width: int, height: int, color: str) -> Image:
|
||||
|
|
@ -261,7 +263,8 @@ FastMCP automatically catches exceptions raised within your tool function:
|
|||
|
||||
Using informative exceptions helps the LLM understand failures and react appropriately.
|
||||
|
||||
### Using Context in Tools
|
||||
## MCP Context
|
||||
|
||||
|
||||
Tools can access MCP features like logging, reading resources, or reporting progress through the `Context` object. To use it, add a parameter to your tool function with the type hint `Context`.
|
||||
|
||||
|
|
@ -302,10 +305,339 @@ The Context object provides access to:
|
|||
|
||||
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
|
||||
|
||||
## Parameter Types
|
||||
|
||||
FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools.
|
||||
|
||||
FastMCP generally supports all types that Pydantic supports as fields, including all Pydantic custom types. This means you can use any type that can be validated and parsed by Pydantic in your tool parameters.
|
||||
|
||||
FastMCP supports **type coercion** when possible. This means that if a client sends data that doesn't match the expected type, FastMCP will attempt to convert it to the appropriate type. For example, if a client sends a string for a parameter annotated as `int`, FastMCP will attempt to convert it to an integer. If the conversion is not possible, FastMCP will return a validation error.
|
||||
|
||||
### Built-in Types
|
||||
|
||||
The most common parameter types are Python's built-in scalar types:
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def process_values(
|
||||
name: str, # Text data
|
||||
count: int, # Integer numbers
|
||||
amount: float, # Floating point numbers
|
||||
enabled: bool # Boolean values (True/False)
|
||||
):
|
||||
"""Process various value types."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
These types provide clear expectations to the LLM about what values are acceptable and allow FastMCP to validate inputs properly. Even if a client provides a string like "42", it will be coerced to an integer for parameters annotated as `int`.
|
||||
|
||||
### Date and Time Types
|
||||
|
||||
FastMCP supports various date and time types from the `datetime` module:
|
||||
|
||||
```python
|
||||
from datetime import datetime, date, timedelta
|
||||
|
||||
@mcp.tool()
|
||||
def process_date_time(
|
||||
event_date: date, # ISO format date string or date object
|
||||
event_time: datetime, # ISO format datetime string or datetime object
|
||||
duration: timedelta = timedelta(hours=1) # Integer seconds or timedelta
|
||||
) -> str:
|
||||
"""Process date and time information."""
|
||||
# Types are automatically converted from strings
|
||||
assert isinstance(event_date, date)
|
||||
assert isinstance(event_time, datetime)
|
||||
assert isinstance(duration, timedelta)
|
||||
|
||||
return f"Event on {event_date} at {event_time} for {duration}"
|
||||
```
|
||||
|
||||
- `datetime` - Accepts ISO format strings (e.g., "2023-04-15T14:30:00")
|
||||
- `date` - Accepts ISO format date strings (e.g., "2023-04-15")
|
||||
- `timedelta` - Accepts integer seconds or timedelta objects
|
||||
|
||||
### Collection Types
|
||||
|
||||
FastMCP supports all standard Python collection types:
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def analyze_data(
|
||||
values: list[float], # List of numbers
|
||||
properties: dict[str, str], # Dictionary with string keys and values
|
||||
unique_ids: set[int], # Set of unique integers
|
||||
coordinates: tuple[float, float], # Tuple with fixed structure
|
||||
mixed_data: dict[str, list[int]] # Nested collections
|
||||
):
|
||||
"""Analyze collections of data."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
All collection types can be used as parameter annotations:
|
||||
- `list[T]` - Ordered sequence of items
|
||||
- `dict[K, V]` - Key-value mapping
|
||||
- `set[T]` - Unordered collection of unique items
|
||||
- `tuple[T1, T2, ...]` - Fixed-length sequence with potentially different types
|
||||
|
||||
Collection types can be nested and combined to represent complex data structures. JSON strings that match the expected structure will be automatically parsed and converted to the appropriate Python collection type.
|
||||
|
||||
### Union and Optional Types
|
||||
|
||||
For parameters that can accept multiple types or may be omitted:
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def flexible_search(
|
||||
query: str | int, # Can be either string or integer
|
||||
filters: dict[str, str] | None = None, # Optional dictionary
|
||||
sort_field: str | None = None # Optional string
|
||||
):
|
||||
"""Search with flexible parameter types."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
Modern Python syntax (`str | int`) is preferred over older `Union[str, int]` forms. Similarly, `str | None` is preferred over `Optional[str]`.
|
||||
|
||||
### Constrained Types
|
||||
|
||||
When a parameter must be one of a predefined set of values, you can use either Literal types or Enums:
|
||||
|
||||
#### Literals
|
||||
|
||||
Literals constrain parameters to a specific set of values:
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
|
||||
@mcp.tool()
|
||||
def sort_data(
|
||||
data: list[float],
|
||||
order: Literal["ascending", "descending"] = "ascending",
|
||||
algorithm: Literal["quicksort", "mergesort", "heapsort"] = "quicksort"
|
||||
):
|
||||
"""Sort data using specific options."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
Literal types:
|
||||
- Specify exact allowable values directly in the type annotation
|
||||
- Help LLMs understand exactly which values are acceptable
|
||||
- Provide input validation (errors for invalid values)
|
||||
- Create clear schemas for clients
|
||||
|
||||
#### Enums
|
||||
|
||||
For more structured sets of constrained values, use Python's Enum class:
|
||||
|
||||
```python
|
||||
from enum import Enum
|
||||
|
||||
class Color(Enum):
|
||||
RED = "red"
|
||||
GREEN = "green"
|
||||
BLUE = "blue"
|
||||
|
||||
@mcp.tool()
|
||||
def process_image(
|
||||
image_path: str,
|
||||
color_filter: Color = Color.RED
|
||||
):
|
||||
"""Process an image with a color filter."""
|
||||
# Implementation...
|
||||
# color_filter will be a Color enum member
|
||||
```
|
||||
|
||||
When using Enum types:
|
||||
- Clients should provide the enum's value (e.g., "red"), not the enum member name (e.g., "RED")
|
||||
- FastMCP automatically coerces the string value into the appropriate Enum object
|
||||
- Your function receives the actual Enum member (e.g., `Color.RED`)
|
||||
- Validation errors are raised for values not in the enum
|
||||
|
||||
### Binary Data
|
||||
|
||||
There are two approaches to handling binary data in tool parameters:
|
||||
|
||||
#### Bytes
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def process_binary(data: bytes):
|
||||
"""Process binary data directly.
|
||||
|
||||
The client can send a binary string, which will be
|
||||
converted directly to bytes.
|
||||
"""
|
||||
# Implementation using binary data
|
||||
data_length = len(data)
|
||||
# ...
|
||||
```
|
||||
|
||||
When you annotate a parameter as `bytes`, FastMCP will:
|
||||
- Convert raw strings directly to bytes
|
||||
- Validate that the input can be properly represented as bytes
|
||||
|
||||
FastMCP does not automatically decode base64-encoded strings for bytes parameters. If you need to accept base64-encoded data, you should handle the decoding manually as shown below.
|
||||
|
||||
#### Base64-encoded strings
|
||||
|
||||
```python
|
||||
from typing import Annotated
|
||||
from pydantic import Field
|
||||
|
||||
@mcp.tool()
|
||||
def process_image_data(
|
||||
image_data: Annotated[str, Field(description="Base64-encoded image data")]
|
||||
):
|
||||
"""Process an image from base64-encoded string.
|
||||
|
||||
The client is expected to provide base64-encoded data as a string.
|
||||
You'll need to decode it manually.
|
||||
"""
|
||||
# Manual base64 decoding
|
||||
import base64
|
||||
binary_data = base64.b64decode(image_data)
|
||||
# Process binary_data...
|
||||
```
|
||||
|
||||
This approach is recommended when you expect to receive base64-encoded binary data from clients.
|
||||
|
||||
### Paths
|
||||
|
||||
The `Path` type from the `pathlib` module can be used for file system paths:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
|
||||
@mcp.tool()
|
||||
def process_file(path: Path) -> str:
|
||||
"""Process a file at the given path."""
|
||||
assert isinstance(path, Path) # Path is properly converted
|
||||
return f"Processing file at {path}"
|
||||
```
|
||||
|
||||
When a client sends a string path, FastMCP automatically converts it to a `Path` object.
|
||||
|
||||
### UUIDs
|
||||
|
||||
The `UUID` type from the `uuid` module can be used for unique identifiers:
|
||||
|
||||
```python
|
||||
import uuid
|
||||
|
||||
@mcp.tool()
|
||||
def process_item(
|
||||
item_id: uuid.UUID # String UUID or UUID object
|
||||
) -> str:
|
||||
"""Process an item with the given UUID."""
|
||||
assert isinstance(item_id, uuid.UUID) # Properly converted to UUID
|
||||
return f"Processing item {item_id}"
|
||||
```
|
||||
|
||||
When a client sends a string UUID (e.g., "123e4567-e89b-12d3-a456-426614174000"), FastMCP automatically converts it to a `UUID` object.
|
||||
|
||||
### Pydantic Models
|
||||
|
||||
For complex, structured data with nested fields and validation, use Pydantic models:
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
email: str = Field(description="User's email address")
|
||||
age: int | None = None
|
||||
is_active: bool = True
|
||||
|
||||
@mcp.tool()
|
||||
def create_user(user: User):
|
||||
"""Create a new user in the system."""
|
||||
# The input is automatically validated against the User model
|
||||
# Even if provided as a JSON string or dict
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
Using Pydantic models provides:
|
||||
- Clear, self-documenting structure for complex inputs
|
||||
- Built-in data validation
|
||||
- Automatic generation of detailed JSON schemas for the LLM
|
||||
- Automatic conversion from dict/JSON input
|
||||
|
||||
Clients can provide data for Pydantic model parameters as either:
|
||||
- A JSON object (string)
|
||||
- A dictionary with the appropriate structure
|
||||
- Nested parameters in the appropriate format
|
||||
|
||||
### Pydantic Fields
|
||||
|
||||
FastMCP supports robust parameter validation through Pydantic's `Field` class. This is especially useful to ensure that input values meet specific requirements beyond just their type.
|
||||
|
||||
Note that fields can be used *outside* Pydantic models to provide metadata and validation constraints. The preferred approach is using `Annotated` with `Field`:
|
||||
|
||||
```python
|
||||
from typing import Annotated
|
||||
from pydantic import Field
|
||||
|
||||
@mcp.tool()
|
||||
def analyze_metrics(
|
||||
# Numbers with range constraints
|
||||
count: Annotated[int, Field(ge=0, le=100)], # 0 <= count <= 100
|
||||
ratio: Annotated[float, Field(gt=0, lt=1.0)], # 0 < ratio < 1.0
|
||||
|
||||
# String with pattern and length constraints
|
||||
user_id: Annotated[str, Field(
|
||||
pattern=r"^[A-Z]{2}\d{4}$", # Must match regex pattern
|
||||
description="User ID in format XX0000"
|
||||
)],
|
||||
|
||||
# String with length constraints
|
||||
comment: Annotated[str, Field(min_length=3, max_length=500)] = "",
|
||||
|
||||
# Numeric constraints
|
||||
factor: Annotated[int, Field(multiple_of=5)] = 10, # Must be multiple of 5
|
||||
):
|
||||
"""Analyze metrics with validated parameters."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
You can also use `Field` as a default value, though the `Annotated` approach is preferred:
|
||||
|
||||
```python
|
||||
@mcp.tool()
|
||||
def validate_data(
|
||||
# Value constraints
|
||||
age: int = Field(ge=0, lt=120), # 0 <= age < 120
|
||||
|
||||
# String constraints
|
||||
email: str = Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$"), # Email pattern
|
||||
|
||||
# Collection constraints
|
||||
tags: list[str] = Field(min_length=1, max_length=10) # 1-10 tags
|
||||
):
|
||||
"""Process data with field validations."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
Common validation options include:
|
||||
|
||||
| Validation | Type | Description |
|
||||
| :--------- | :--- | :---------- |
|
||||
| `ge`, `gt` | Number | Greater than (or equal) constraint |
|
||||
| `le`, `lt` | Number | Less than (or equal) constraint |
|
||||
| `multiple_of` | Number | Value must be a multiple of this number |
|
||||
| `min_length`, `max_length` | String, List, etc. | Length constraints |
|
||||
| `pattern` | String | Regular expression pattern constraint |
|
||||
| `description` | Any | Human-readable description (appears in schema) |
|
||||
|
||||
When a client sends invalid data, FastMCP will return a validation error explaining why the parameter failed validation.
|
||||
|
||||
## Server Behavior
|
||||
|
||||
### Duplicate Tools
|
||||
|
||||
<VersionBadge version="2.1.0" />
|
||||
|
||||
You can control how the FastMCP server behaves if you try to register multiple tools with the same name. This is configured using the `on_duplicate_tools` argument when creating the `FastMCP` instance.
|
||||
|
||||
```python
|
||||
|
|
@ -331,4 +663,4 @@ The duplicate behavior options are:
|
|||
- `"warn"` (default): Logs a warning and the new tool replaces the old one.
|
||||
- `"error"`: Raises a `ValueError`, preventing the duplicate registration.
|
||||
- `"replace"`: Silently replaces the existing tool with the new one.
|
||||
- `"ignore"`: Keeps the original tool and ignores the new registration attempt.
|
||||
- `"ignore"`: Keeps the original tool and ignores the new registration attempt.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
export const VersionBadge = ({ version }) => {
|
||||
return (
|
||||
<span className="version-badge">
|
||||
<span className="badge-emoji" aria-hidden="true" style={{ marginRight: '0.3em', verticalAlign: 'middle' }}>✨</span>
|
||||
New in version {version}
|
||||
</span>
|
||||
<code className="version-badge-container">
|
||||
<div className="version-badge">
|
||||
<span className="version-badge-label">New in version:</span>
|
||||
<span className="version-badge-version">{version}</span>
|
||||
</div>
|
||||
</code>
|
||||
|
||||
|
||||
|
||||
);
|
||||
};
|
||||
|
|
@ -14,16 +14,18 @@ h6 code:not(pre code) {
|
|||
|
||||
/* Version badge -- display a badge with the current version of the documentation */
|
||||
.version-badge {
|
||||
display: inline-flex;
|
||||
display: inline-block;
|
||||
align-items: center;
|
||||
gap: 0.3em;
|
||||
padding: 0.32em 1em;
|
||||
font-size: 0.92em;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: #7417e5;
|
||||
background: #f3e8ff;
|
||||
border: 1.5px solid #c084fc;
|
||||
padding: 0.2em 0.8em;
|
||||
font-size: 1.1em;
|
||||
font-weight: 400;
|
||||
|
||||
font-family: "Inter", sans-serif;
|
||||
letter-spacing: 0.025em;
|
||||
color: #ff5400;
|
||||
background: #ffeee6;
|
||||
border: 1px solid rgb(255, 84, 0, 0.5);
|
||||
border-radius: 6px;
|
||||
box-shadow: none;
|
||||
vertical-align: middle;
|
||||
|
|
@ -31,6 +33,11 @@ h6 code:not(pre code) {
|
|||
transition: box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
|
||||
.version-badge-container {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.version-badge:hover {
|
||||
box-shadow: 0 2px 8px 0 rgba(160, 132, 252, 0.1);
|
||||
transform: translateY(-1px) scale(1.03);
|
||||
|
|
@ -41,13 +48,3 @@ h6 code:not(pre code) {
|
|||
background: #312e81;
|
||||
border: 1.5px solid #a78bfa;
|
||||
}
|
||||
|
||||
.badge-emoji {
|
||||
font-size: 1.15em;
|
||||
line-height: 1;
|
||||
text-shadow: 0 1px 2px #fff, 0 0px 2px #c084fc;
|
||||
}
|
||||
|
||||
.dark .badge-emoji {
|
||||
text-shadow: 0 1px 2px #312e81, 0 0px 2px #a78bfa;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -223,6 +223,27 @@ def dev(
|
|||
help="Additional packages to install",
|
||||
),
|
||||
] = [],
|
||||
inspector_version: Annotated[
|
||||
str | None,
|
||||
typer.Option(
|
||||
"--inspector-version",
|
||||
help="Version of the MCP Inspector to use",
|
||||
),
|
||||
] = None,
|
||||
ui_port: Annotated[
|
||||
int | None,
|
||||
typer.Option(
|
||||
"--ui-port",
|
||||
help="Port for the MCP Inspector UI",
|
||||
),
|
||||
] = None,
|
||||
server_port: Annotated[
|
||||
int | None,
|
||||
typer.Option(
|
||||
"--server-port",
|
||||
help="Port for the MCP Inspector Proxy server",
|
||||
),
|
||||
] = None,
|
||||
) -> None:
|
||||
"""Run a MCP server with the MCP Inspector."""
|
||||
file, server_object = _parse_file_path(file_spec)
|
||||
|
|
@ -234,6 +255,8 @@ def dev(
|
|||
"server_object": server_object,
|
||||
"with_editable": str(with_editable) if with_editable else None,
|
||||
"with_packages": with_packages,
|
||||
"ui_port": ui_port,
|
||||
"server_port": server_port,
|
||||
},
|
||||
)
|
||||
|
||||
|
|
@ -243,7 +266,11 @@ def dev(
|
|||
if hasattr(server, "dependencies"):
|
||||
with_packages = list(set(with_packages + server.dependencies))
|
||||
|
||||
uv_cmd = _build_uv_command(file_spec, with_editable, with_packages)
|
||||
env_vars = {}
|
||||
if ui_port:
|
||||
env_vars["CLIENT_PORT"] = str(ui_port)
|
||||
if server_port:
|
||||
env_vars["SERVER_PORT"] = str(server_port)
|
||||
|
||||
# Get the correct npx command
|
||||
npx_cmd = _get_npx_command()
|
||||
|
|
@ -254,13 +281,19 @@ def dev(
|
|||
)
|
||||
sys.exit(1)
|
||||
|
||||
inspector_cmd = "@modelcontextprotocol/inspector"
|
||||
if inspector_version:
|
||||
inspector_cmd += f"@{inspector_version}"
|
||||
|
||||
uv_cmd = _build_uv_command(file_spec, with_editable, with_packages)
|
||||
|
||||
# Run the MCP Inspector command with shell=True on Windows
|
||||
shell = sys.platform == "win32"
|
||||
process = subprocess.run(
|
||||
[npx_cmd, "@modelcontextprotocol/inspector"] + uv_cmd,
|
||||
[npx_cmd, inspector_cmd] + uv_cmd,
|
||||
check=True,
|
||||
shell=shell,
|
||||
env=dict(os.environ.items()), # Convert to list of tuples for env update
|
||||
env=dict(os.environ.items()) | env_vars,
|
||||
)
|
||||
sys.exit(process.returncode)
|
||||
except subprocess.CalledProcessError as e:
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
"""Base classes for FastMCP prompts."""
|
||||
|
||||
from __future__ import annotations as _annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from typing import Annotated, Any, Literal
|
||||
from typing import TYPE_CHECKING, Annotated, Any, Literal
|
||||
|
||||
import pydantic_core
|
||||
from mcp.types import EmbeddedResource, ImageContent, TextContent
|
||||
|
|
@ -13,6 +15,12 @@ from pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_ca
|
|||
|
||||
from fastmcp.utilities.types import _convert_set_defaults
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
CONTENT_TYPES = TextContent | ImageContent | EmbeddedResource
|
||||
|
||||
|
||||
|
|
@ -72,6 +80,9 @@ class Prompt(BaseModel):
|
|||
None, description="Arguments that can be passed to the prompt"
|
||||
)
|
||||
fn: Callable[..., PromptResult | Awaitable[PromptResult]]
|
||||
context_kwarg: str | None = Field(
|
||||
None, description="Name of the kwarg that should receive context"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_function(
|
||||
|
|
@ -80,7 +91,8 @@ class Prompt(BaseModel):
|
|||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
tags: set[str] | None = None,
|
||||
) -> "Prompt":
|
||||
context_kwarg: str | None = None,
|
||||
) -> Prompt:
|
||||
"""Create a Prompt from a function.
|
||||
|
||||
The function can return:
|
||||
|
|
@ -89,11 +101,24 @@ class Prompt(BaseModel):
|
|||
- A dict (converted to a message)
|
||||
- A sequence of any of the above
|
||||
"""
|
||||
from fastmcp import Context
|
||||
|
||||
func_name = name or fn.__name__
|
||||
|
||||
if func_name == "<lambda>":
|
||||
raise ValueError("You must provide a name for lambda functions")
|
||||
|
||||
# Auto-detect context parameter if not provided
|
||||
if context_kwarg is None:
|
||||
if inspect.ismethod(fn) and hasattr(fn, "__func__"):
|
||||
sig = inspect.signature(fn.__func__)
|
||||
else:
|
||||
sig = inspect.signature(fn)
|
||||
for param_name, param in sig.parameters.items():
|
||||
if param.annotation is Context:
|
||||
context_kwarg = param_name
|
||||
break
|
||||
|
||||
# Get schema from TypeAdapter - will fail if function isn't properly typed
|
||||
parameters = TypeAdapter(fn).json_schema()
|
||||
|
||||
|
|
@ -101,6 +126,10 @@ class Prompt(BaseModel):
|
|||
arguments: list[PromptArgument] = []
|
||||
if "properties" in parameters:
|
||||
for param_name, param in parameters["properties"].items():
|
||||
# Skip context parameter
|
||||
if param_name == context_kwarg:
|
||||
continue
|
||||
|
||||
required = param_name in parameters.get("required", [])
|
||||
arguments.append(
|
||||
PromptArgument(
|
||||
|
|
@ -119,9 +148,14 @@ class Prompt(BaseModel):
|
|||
arguments=arguments,
|
||||
fn=fn,
|
||||
tags=tags or set(),
|
||||
context_kwarg=context_kwarg,
|
||||
)
|
||||
|
||||
async def render(self, arguments: dict[str, Any] | None = None) -> list[Message]:
|
||||
async def render(
|
||||
self,
|
||||
arguments: dict[str, Any] | None = None,
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> list[Message]:
|
||||
"""Render the prompt with arguments."""
|
||||
# Validate required arguments
|
||||
if self.arguments:
|
||||
|
|
@ -132,8 +166,13 @@ class Prompt(BaseModel):
|
|||
raise ValueError(f"Missing required arguments: {missing}")
|
||||
|
||||
try:
|
||||
# Prepare arguments with context
|
||||
kwargs = arguments.copy() if arguments else {}
|
||||
if self.context_kwarg is not None and context is not None:
|
||||
kwargs[self.context_kwarg] = context
|
||||
|
||||
# Call function and check if result is a coroutine
|
||||
result = self.fn(**(arguments or {}))
|
||||
result = self.fn(**kwargs)
|
||||
if inspect.iscoroutine(result):
|
||||
result = await result
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,21 @@
|
|||
"""Prompt management functionality."""
|
||||
|
||||
from __future__ import annotations as _annotations
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from fastmcp.exceptions import NotFoundError
|
||||
from fastmcp.prompts.prompt import Message, Prompt, PromptResult
|
||||
from fastmcp.settings import DuplicateBehavior
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
|
|
@ -69,14 +77,17 @@ class PromptManager:
|
|||
return prompt
|
||||
|
||||
async def render_prompt(
|
||||
self, name: str, arguments: dict[str, Any] | None = None
|
||||
self,
|
||||
name: str,
|
||||
arguments: dict[str, Any] | None = None,
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> list[Message]:
|
||||
"""Render a prompt by name with arguments."""
|
||||
prompt = self.get_prompt(name)
|
||||
if not prompt:
|
||||
raise NotFoundError(f"Unknown prompt: {name}")
|
||||
|
||||
return await prompt.render(arguments)
|
||||
return await prompt.render(arguments, context=context)
|
||||
|
||||
def has_prompt(self, key: str) -> bool:
|
||||
"""Check if a prompt exists."""
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
"""Base classes and interfaces for FastMCP resources."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
from typing import Annotated, Any
|
||||
from typing import TYPE_CHECKING, Annotated, Any
|
||||
|
||||
from mcp.types import Resource as MCPResource
|
||||
from pydantic import (
|
||||
|
|
@ -17,6 +19,12 @@ from pydantic import (
|
|||
|
||||
from fastmcp.utilities.types import _convert_set_defaults
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
|
||||
class Resource(BaseModel, abc.ABC):
|
||||
"""Base class for all resources."""
|
||||
|
|
@ -58,7 +66,9 @@ class Resource(BaseModel, abc.ABC):
|
|||
raise ValueError("Either name or uri must be provided")
|
||||
|
||||
@abc.abstractmethod
|
||||
async def read(self) -> str | bytes:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str | bytes:
|
||||
"""Read the resource content."""
|
||||
pass
|
||||
|
||||
|
|
|
|||
|
|
@ -61,9 +61,16 @@ class ResourceManager:
|
|||
The added resource or template. If a resource or template with the same URI already exists,
|
||||
returns the existing resource or template.
|
||||
"""
|
||||
from fastmcp.server.context import Context
|
||||
|
||||
# Check if this should be a template
|
||||
has_uri_params = "{" in uri and "}" in uri
|
||||
has_func_params = bool(inspect.signature(fn).parameters)
|
||||
# check if the function has any parameters (other than injected context)
|
||||
has_func_params = any(
|
||||
p
|
||||
for p in inspect.signature(fn).parameters.values()
|
||||
if p.annotation is not Context
|
||||
)
|
||||
|
||||
if has_uri_params or has_func_params:
|
||||
return self.add_template_from_fn(
|
||||
|
|
@ -102,12 +109,12 @@ class ResourceManager:
|
|||
The added resource. If a resource with the same URI already exists,
|
||||
returns the existing resource.
|
||||
"""
|
||||
resource = FunctionResource(
|
||||
resource = FunctionResource.from_function(
|
||||
fn=fn,
|
||||
uri=AnyUrl(uri),
|
||||
name=name,
|
||||
description=description,
|
||||
mime_type=mime_type or "text/plain",
|
||||
fn=fn,
|
||||
tags=tags or set(),
|
||||
)
|
||||
return self.add_resource(resource)
|
||||
|
|
@ -212,9 +219,13 @@ class ResourceManager:
|
|||
return True
|
||||
return False
|
||||
|
||||
async def get_resource(self, uri: AnyUrl | str) -> Resource:
|
||||
async def get_resource(self, uri: AnyUrl | str, context=None) -> Resource:
|
||||
"""Get resource by URI, checking concrete resources first, then templates.
|
||||
|
||||
Args:
|
||||
uri: The URI of the resource to get
|
||||
context: Optional context object to pass to template resources
|
||||
|
||||
Raises:
|
||||
NotFoundError: If no resource or template matching the URI is found.
|
||||
"""
|
||||
|
|
@ -230,7 +241,11 @@ class ResourceManager:
|
|||
# Try to match against the storage key (which might be a custom key)
|
||||
if params := match_uri_template(uri_str, storage_key):
|
||||
try:
|
||||
return await template.create_resource(uri_str, params)
|
||||
return await template.create_resource(
|
||||
uri_str,
|
||||
params=params,
|
||||
context=context,
|
||||
)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Error creating resource from template: {e}")
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||
import inspect
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, Any
|
||||
from typing import TYPE_CHECKING, Annotated, Any
|
||||
from urllib.parse import unquote
|
||||
|
||||
from mcp.types import ResourceTemplate as MCPResourceTemplate
|
||||
|
|
@ -22,15 +22,24 @@ from pydantic import (
|
|||
from fastmcp.resources.types import FunctionResource, Resource
|
||||
from fastmcp.utilities.types import _convert_set_defaults
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
|
||||
def build_regex(template: str) -> re.Pattern:
|
||||
# Escape all non-brace characters, then restore {var} placeholders
|
||||
parts = re.split(r"(\{[^}]+\})", template)
|
||||
pattern = ""
|
||||
for part in parts:
|
||||
if part.startswith("{") and part.endswith("}"):
|
||||
name = part[1:-1]
|
||||
pattern += f"(?P<{name}>[^/]+)"
|
||||
if name.endswith("*"):
|
||||
name = name[:-1]
|
||||
pattern += f"(?P<{name}>.+)"
|
||||
else:
|
||||
pattern += f"(?P<{name}>[^/]+)"
|
||||
else:
|
||||
pattern += re.escape(part)
|
||||
return re.compile(f"^{pattern}$")
|
||||
|
|
@ -67,6 +76,9 @@ class ResourceTemplate(BaseModel):
|
|||
parameters: dict[str, Any] = Field(
|
||||
description="JSON schema for function parameters"
|
||||
)
|
||||
context_kwarg: str | None = Field(
|
||||
None, description="Name of the kwarg that should receive context"
|
||||
)
|
||||
|
||||
@field_validator("mime_type", mode="before")
|
||||
@classmethod
|
||||
|
|
@ -85,18 +97,34 @@ class ResourceTemplate(BaseModel):
|
|||
description: str | None = None,
|
||||
mime_type: str | None = None,
|
||||
tags: set[str] | None = None,
|
||||
context_kwarg: str | None = None,
|
||||
) -> ResourceTemplate:
|
||||
"""Create a template from a function."""
|
||||
from fastmcp import Context
|
||||
|
||||
func_name = name or fn.__name__
|
||||
if func_name == "<lambda>":
|
||||
raise ValueError("You must provide a name for lambda functions")
|
||||
|
||||
# Auto-detect context parameter if not provided
|
||||
if context_kwarg is None:
|
||||
if inspect.ismethod(fn) and hasattr(fn, "__func__"):
|
||||
sig = inspect.signature(fn.__func__)
|
||||
else:
|
||||
sig = inspect.signature(fn)
|
||||
for param_name, param in sig.parameters.items():
|
||||
if param.annotation is Context:
|
||||
context_kwarg = param_name
|
||||
break
|
||||
|
||||
# Validate that URI params match function params
|
||||
uri_params = set(re.findall(r"{(\w+)}", uri_template))
|
||||
uri_params = set(re.findall(r"{(\w+)(?:\*)?}", uri_template))
|
||||
if not uri_params:
|
||||
raise ValueError("URI template must contain at least one parameter")
|
||||
|
||||
func_params = set(inspect.signature(fn).parameters.keys())
|
||||
if context_kwarg:
|
||||
func_params.discard(context_kwarg)
|
||||
|
||||
# get the parameters that are required
|
||||
required_params = {
|
||||
|
|
@ -104,6 +132,8 @@ class ResourceTemplate(BaseModel):
|
|||
for p in func_params
|
||||
if inspect.signature(fn).parameters[p].default is inspect.Parameter.empty
|
||||
}
|
||||
if context_kwarg and context_kwarg in required_params:
|
||||
required_params.discard(context_kwarg)
|
||||
|
||||
if not required_params.issubset(uri_params):
|
||||
raise ValueError(
|
||||
|
|
@ -129,17 +159,28 @@ class ResourceTemplate(BaseModel):
|
|||
fn=fn,
|
||||
parameters=parameters,
|
||||
tags=tags or set(),
|
||||
context_kwarg=context_kwarg,
|
||||
)
|
||||
|
||||
def matches(self, uri: str) -> dict[str, Any] | None:
|
||||
"""Check if URI matches template and extract parameters."""
|
||||
return match_uri_template(uri, self.uri_template)
|
||||
|
||||
async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:
|
||||
async def create_resource(
|
||||
self,
|
||||
uri: str,
|
||||
params: dict[str, Any],
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> Resource:
|
||||
"""Create a resource from the template with the given parameters."""
|
||||
try:
|
||||
# Add context to parameters if needed
|
||||
kwargs = params.copy()
|
||||
if self.context_kwarg is not None and context is not None:
|
||||
kwargs[self.context_kwarg] = context
|
||||
|
||||
# Call function and check if result is a coroutine
|
||||
result = self.fn(**params)
|
||||
result = self.fn(**kwargs)
|
||||
if inspect.iscoroutine(result):
|
||||
result = await result
|
||||
|
||||
|
|
@ -148,8 +189,9 @@ class ResourceTemplate(BaseModel):
|
|||
name=self.name,
|
||||
description=self.description,
|
||||
mime_type=self.mime_type,
|
||||
fn=lambda: result, # Capture result in closure
|
||||
fn=lambda **kwargs: result, # Capture result in closure
|
||||
tags=self.tags,
|
||||
context_kwarg=self.context_kwarg,
|
||||
)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Error creating resource from template: {e}")
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
"""Concrete resource implementations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import anyio
|
||||
import anyio.to_thread
|
||||
|
|
@ -13,15 +15,24 @@ import pydantic.json
|
|||
import pydantic_core
|
||||
from pydantic import Field, ValidationInfo
|
||||
|
||||
import fastmcp
|
||||
from fastmcp.resources.resource import Resource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
|
||||
class TextResource(Resource):
|
||||
"""A resource that reads from a string."""
|
||||
|
||||
text: str = Field(description="Text content of the resource")
|
||||
|
||||
async def read(self) -> str:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str:
|
||||
"""Read the text content."""
|
||||
return self.text
|
||||
|
||||
|
|
@ -31,7 +42,9 @@ class BinaryResource(Resource):
|
|||
|
||||
data: bytes = Field(description="Binary content of the resource")
|
||||
|
||||
async def read(self) -> bytes:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> bytes:
|
||||
"""Read the binary content."""
|
||||
return self.data
|
||||
|
||||
|
|
@ -50,15 +63,40 @@ class FunctionResource(Resource):
|
|||
"""
|
||||
|
||||
fn: Callable[[], Any]
|
||||
context_kwarg: str | None = Field(
|
||||
default=None, description="Name of the kwarg that should receive context"
|
||||
)
|
||||
|
||||
async def read(self) -> str | bytes:
|
||||
@classmethod
|
||||
def from_function(
|
||||
cls, fn: Callable[[], Any], context_kwarg: str | None = None, **kwargs
|
||||
) -> FunctionResource:
|
||||
if context_kwarg is None:
|
||||
parameters = inspect.signature(fn).parameters
|
||||
context_param = next(
|
||||
(p for p in parameters.values() if p.annotation is fastmcp.Context),
|
||||
None,
|
||||
)
|
||||
if context_param is not None:
|
||||
context_kwarg = context_param.name
|
||||
return cls(fn=fn, context_kwarg=context_kwarg, **kwargs)
|
||||
|
||||
async def read(
|
||||
self,
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> str | bytes:
|
||||
"""Read the resource by calling the wrapped function."""
|
||||
try:
|
||||
result = (
|
||||
await self.fn() if inspect.iscoroutinefunction(self.fn) else self.fn()
|
||||
)
|
||||
kwargs = {}
|
||||
if self.context_kwarg is not None:
|
||||
kwargs[self.context_kwarg] = context
|
||||
|
||||
result = self.fn(**kwargs)
|
||||
if inspect.iscoroutinefunction(self.fn):
|
||||
result = await result
|
||||
|
||||
if isinstance(result, Resource):
|
||||
return await result.read()
|
||||
return await result.read(context=context)
|
||||
if isinstance(result, bytes):
|
||||
return result
|
||||
if isinstance(result, str):
|
||||
|
|
@ -105,7 +143,9 @@ class FileResource(Resource):
|
|||
mime_type = info.data.get("mime_type", "text/plain")
|
||||
return not mime_type.startswith("text/")
|
||||
|
||||
async def read(self) -> str | bytes:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str | bytes:
|
||||
"""Read the file content."""
|
||||
try:
|
||||
if self.is_binary:
|
||||
|
|
@ -123,7 +163,9 @@ class HttpResource(Resource):
|
|||
default="application/json", description="MIME type of the resource content"
|
||||
)
|
||||
|
||||
async def read(self) -> str | bytes:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str | bytes:
|
||||
"""Read the HTTP content."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(self.url)
|
||||
|
|
@ -175,7 +217,9 @@ class DirectoryResource(Resource):
|
|||
except Exception as e:
|
||||
raise ValueError(f"Error listing directory {self.path}: {e}")
|
||||
|
||||
async def read(self) -> str: # Always returns JSON string
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str: # Always returns JSON string
|
||||
"""Read the directory listing."""
|
||||
try:
|
||||
files = await anyio.to_thread.run_sync(self.list_files)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
"""FastMCP server implementation for OpenAPI integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from re import Pattern
|
||||
from typing import Any, Literal
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
import httpx
|
||||
from mcp.types import TextContent
|
||||
|
|
@ -22,6 +24,12 @@ from fastmcp.utilities.openapi import (
|
|||
format_description_with_responses,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
HttpMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
|
||||
|
|
@ -257,7 +265,9 @@ class OpenAPIResource(Resource):
|
|||
self._client = client
|
||||
self._route = route
|
||||
|
||||
async def read(self) -> str:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str | bytes:
|
||||
"""Fetch the resource data by making an HTTP request."""
|
||||
try:
|
||||
# Extract path parameters from the URI if present
|
||||
|
|
@ -297,15 +307,16 @@ class OpenAPIResource(Resource):
|
|||
# Raise for 4xx/5xx responses
|
||||
response.raise_for_status()
|
||||
|
||||
# Return response content based on mime type
|
||||
if self.mime_type == "application/json":
|
||||
try:
|
||||
return response.json()
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
# Fallback to returning the text
|
||||
return response.text
|
||||
else:
|
||||
# Determine content type and return appropriate format
|
||||
content_type = response.headers.get("content-type", "").lower()
|
||||
|
||||
if "application/json" in content_type:
|
||||
result = response.json()
|
||||
return json.dumps(result)
|
||||
elif any(ct in content_type for ct in ["text/", "application/xml"]):
|
||||
return response.text
|
||||
else:
|
||||
return response.content
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
# Handle HTTP errors (4xx, 5xx)
|
||||
|
|
@ -343,60 +354,20 @@ class OpenAPIResourceTemplate(ResourceTemplate):
|
|||
uri_template=uri_template,
|
||||
name=name,
|
||||
description=description,
|
||||
fn=self._create_resource_fn,
|
||||
fn=lambda **kwargs: None,
|
||||
parameters=parameters,
|
||||
tags=tags,
|
||||
context_kwarg=None,
|
||||
)
|
||||
self._client = client
|
||||
self._route = route
|
||||
|
||||
async def _create_resource_fn(self, **kwargs):
|
||||
"""Create a resource with parameters."""
|
||||
# Prepare the path with parameters
|
||||
path = self._route.path
|
||||
for param_name, param_value in kwargs.items():
|
||||
path = path.replace(f"{{{param_name}}}", str(param_value))
|
||||
|
||||
try:
|
||||
response = await self._client.request(
|
||||
method=self._route.method,
|
||||
url=path,
|
||||
timeout=30.0, # Default timeout
|
||||
)
|
||||
|
||||
# Raise for 4xx/5xx responses
|
||||
response.raise_for_status()
|
||||
|
||||
# Determine the mime type from the response
|
||||
content_type = response.headers.get("content-type", "application/json")
|
||||
mime_type = content_type.split(";")[0].strip()
|
||||
|
||||
# Return the appropriate data
|
||||
if mime_type == "application/json":
|
||||
try:
|
||||
return response.json()
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return response.text
|
||||
else:
|
||||
return response.text
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
error_message = (
|
||||
f"HTTP error {e.response.status_code}: {e.response.reason_phrase}"
|
||||
)
|
||||
try:
|
||||
error_data = e.response.json()
|
||||
error_message += f" - {error_data}"
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
if e.response.text:
|
||||
error_message += f" - {e.response.text}"
|
||||
|
||||
raise ValueError(error_message)
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise ValueError(f"Request error: {str(e)}")
|
||||
|
||||
async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:
|
||||
async def create_resource(
|
||||
self,
|
||||
uri: str,
|
||||
params: dict[str, Any],
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> Resource:
|
||||
"""Create a resource with the given parameters."""
|
||||
# Generate a URI for this resource instance
|
||||
uri_parts = []
|
||||
|
|
@ -409,9 +380,8 @@ class OpenAPIResourceTemplate(ResourceTemplate):
|
|||
route=self._route,
|
||||
uri=uri,
|
||||
name=f"{self.name}-{'-'.join(uri_parts)}",
|
||||
description=self.description
|
||||
or f"Resource for {self._route.path}", # Provide default if None
|
||||
mime_type="application/json", # Default, will be updated when read
|
||||
description=self.description or f"Resource for {self._route.path}",
|
||||
mime_type="application/json",
|
||||
tags=set(self._route.tags or []),
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
from typing import Any, cast
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from urllib.parse import quote
|
||||
|
||||
import mcp.types
|
||||
|
|
@ -25,6 +27,12 @@ from fastmcp.tools.tool import Tool
|
|||
from fastmcp.utilities.func_metadata import func_metadata
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mcp.server.session import ServerSessionT
|
||||
from mcp.shared.context import LifespanContextT
|
||||
|
||||
from fastmcp.server import Context
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
|
|
@ -33,12 +41,12 @@ def _proxy_passthrough():
|
|||
|
||||
|
||||
class ProxyTool(Tool):
|
||||
def __init__(self, client: "Client", **kwargs):
|
||||
def __init__(self, client: Client, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._client = client
|
||||
|
||||
@classmethod
|
||||
async def from_client(cls, client: "Client", tool: mcp.types.Tool) -> "ProxyTool":
|
||||
async def from_client(cls, client: Client, tool: mcp.types.Tool) -> ProxyTool:
|
||||
return cls(
|
||||
client=client,
|
||||
name=tool.name,
|
||||
|
|
@ -50,7 +58,9 @@ class ProxyTool(Tool):
|
|||
)
|
||||
|
||||
async def run(
|
||||
self, arguments: dict[str, Any], context: Context | None = None
|
||||
self,
|
||||
arguments: dict[str, Any],
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> Any:
|
||||
# the client context manager will swallow any exceptions inside a TaskGroup
|
||||
# so we return the raw result and raise an exception ourselves
|
||||
|
|
@ -64,17 +74,15 @@ class ProxyTool(Tool):
|
|||
|
||||
|
||||
class ProxyResource(Resource):
|
||||
def __init__(
|
||||
self, client: "Client", *, _value: str | bytes | None = None, **kwargs
|
||||
):
|
||||
def __init__(self, client: Client, *, _value: str | bytes | None = None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._client = client
|
||||
self._value = _value
|
||||
|
||||
@classmethod
|
||||
async def from_client(
|
||||
cls, client: "Client", resource: mcp.types.Resource
|
||||
) -> "ProxyResource":
|
||||
cls, client: Client, resource: mcp.types.Resource
|
||||
) -> ProxyResource:
|
||||
return cls(
|
||||
client=client,
|
||||
uri=resource.uri,
|
||||
|
|
@ -83,7 +91,9 @@ class ProxyResource(Resource):
|
|||
mime_type=resource.mimeType,
|
||||
)
|
||||
|
||||
async def read(self) -> str | bytes:
|
||||
async def read(
|
||||
self, context: Context[ServerSessionT, LifespanContextT] | None = None
|
||||
) -> str | bytes:
|
||||
if self._value is not None:
|
||||
return self._value
|
||||
|
||||
|
|
@ -98,14 +108,14 @@ class ProxyResource(Resource):
|
|||
|
||||
|
||||
class ProxyTemplate(ResourceTemplate):
|
||||
def __init__(self, client: "Client", **kwargs):
|
||||
def __init__(self, client: Client, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._client = client
|
||||
|
||||
@classmethod
|
||||
async def from_client(
|
||||
cls, client: "Client", template: mcp.types.ResourceTemplate
|
||||
) -> "ProxyTemplate":
|
||||
cls, client: Client, template: mcp.types.ResourceTemplate
|
||||
) -> ProxyTemplate:
|
||||
return cls(
|
||||
client=client,
|
||||
uri_template=template.uriTemplate,
|
||||
|
|
@ -115,7 +125,12 @@ class ProxyTemplate(ResourceTemplate):
|
|||
parameters={},
|
||||
)
|
||||
|
||||
async def create_resource(self, uri: str, params: dict[str, Any]) -> ProxyResource:
|
||||
async def create_resource(
|
||||
self,
|
||||
uri: str,
|
||||
params: dict[str, Any],
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> ProxyResource:
|
||||
# dont use the provided uri, because it may not be the same as the
|
||||
# uri_template on the remote server.
|
||||
# quote params to ensure they are valid for the uri_template
|
||||
|
|
@ -144,14 +159,12 @@ class ProxyTemplate(ResourceTemplate):
|
|||
|
||||
|
||||
class ProxyPrompt(Prompt):
|
||||
def __init__(self, client: "Client", **kwargs):
|
||||
def __init__(self, client: Client, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._client = client
|
||||
|
||||
@classmethod
|
||||
async def from_client(
|
||||
cls, client: "Client", prompt: mcp.types.Prompt
|
||||
) -> "ProxyPrompt":
|
||||
async def from_client(cls, client: Client, prompt: mcp.types.Prompt) -> ProxyPrompt:
|
||||
return cls(
|
||||
client=client,
|
||||
name=prompt.name,
|
||||
|
|
@ -160,14 +173,18 @@ class ProxyPrompt(Prompt):
|
|||
fn=_proxy_passthrough,
|
||||
)
|
||||
|
||||
async def render(self, arguments: dict[str, Any]) -> list[Message]:
|
||||
async def render(
|
||||
self,
|
||||
arguments: dict[str, Any],
|
||||
context: Context[ServerSessionT, LifespanContextT] | None = None,
|
||||
) -> list[Message]:
|
||||
async with self._client:
|
||||
result = await self._client.get_prompt(self.name, arguments)
|
||||
return [Message(role=m.role, content=m.content) for m in result]
|
||||
|
||||
|
||||
class FastMCPProxy(FastMCP):
|
||||
def __init__(self, client: "Client", **kwargs):
|
||||
def __init__(self, client: Client, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.client = client
|
||||
|
||||
|
|
|
|||
|
|
@ -402,9 +402,10 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
server.
|
||||
"""
|
||||
if self._resource_manager.has_resource(uri):
|
||||
resource = await self._resource_manager.get_resource(uri)
|
||||
context = self.get_context()
|
||||
resource = await self._resource_manager.get_resource(uri, context=context)
|
||||
try:
|
||||
content = await resource.read()
|
||||
content = await resource.read(context=context)
|
||||
return [
|
||||
ReadResourceContents(content=content, mime_type=resource.mime_type)
|
||||
]
|
||||
|
|
@ -428,7 +429,10 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
|
||||
"""
|
||||
if self._prompt_manager.has_prompt(name):
|
||||
messages = await self._prompt_manager.render_prompt(name, arguments)
|
||||
context = self.get_context()
|
||||
messages = await self._prompt_manager.render_prompt(
|
||||
name, arguments=arguments or {}, context=context
|
||||
)
|
||||
return GetPromptResult(messages=pydantic_core.to_jsonable_python(messages))
|
||||
else:
|
||||
for server in self._mounted_servers.values():
|
||||
|
|
@ -566,6 +570,10 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
- bytes for binary content
|
||||
- other types will be converted to JSON
|
||||
|
||||
Resources can optionally request a Context object by adding a parameter with the
|
||||
Context type annotation. The context provides access to MCP capabilities like
|
||||
logging, progress reporting, and session information.
|
||||
|
||||
If the URI contains parameters (e.g. "resource://{param}") or the function
|
||||
has parameters, it will be registered as a template resource.
|
||||
|
||||
|
|
@ -590,6 +598,11 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
def get_weather(city: str) -> str:
|
||||
return f"Weather for {city}"
|
||||
|
||||
@server.resource("resource://{city}/weather")
|
||||
def get_weather_with_context(city: str, ctx: Context) -> str:
|
||||
ctx.info(f"Fetching weather for {city}")
|
||||
return f"Weather for {city}"
|
||||
|
||||
@server.resource("resource://{city}/weather")
|
||||
async def get_weather(city: str) -> str:
|
||||
data = await fetch_weather(city)
|
||||
|
|
@ -643,6 +656,10 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
) -> Callable[[AnyFunction], AnyFunction]:
|
||||
"""Decorator to register a prompt.
|
||||
|
||||
Prompts can optionally request a Context object by adding a parameter with the
|
||||
Context type annotation. The context provides access to MCP capabilities like
|
||||
logging, progress reporting, and session information.
|
||||
|
||||
Args:
|
||||
name: Optional name for the prompt (defaults to function name)
|
||||
description: Optional description of what the prompt does
|
||||
|
|
@ -659,6 +676,17 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
}
|
||||
]
|
||||
|
||||
@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)
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": f"Analyze this schema:\n{schema}"
|
||||
}
|
||||
]
|
||||
|
||||
@server.prompt()
|
||||
async def analyze_file(path: str) -> list[Message]:
|
||||
content = await read_file(path)
|
||||
|
|
|
|||
|
|
@ -76,7 +76,12 @@ class Tool(BaseModel):
|
|||
fn_callable,
|
||||
skip_names=[context_kwarg] if context_kwarg is not None else [],
|
||||
)
|
||||
parameters = func_arg_metadata.arg_model.model_json_schema()
|
||||
try:
|
||||
parameters = func_arg_metadata.arg_model.model_json_schema()
|
||||
except Exception as e:
|
||||
raise TypeError(
|
||||
f'Unable to parse parameters for function "{fn.__name__}": {e}'
|
||||
) from e
|
||||
|
||||
return cls(
|
||||
fn=fn_callable,
|
||||
|
|
@ -96,13 +101,16 @@ class Tool(BaseModel):
|
|||
) -> list[TextContent | ImageContent | EmbeddedResource]:
|
||||
"""Run the tool with arguments."""
|
||||
try:
|
||||
result = await self.fn_metadata.call_fn_with_arg_validation(
|
||||
self.fn,
|
||||
self.is_async,
|
||||
arguments,
|
||||
pass_args = (
|
||||
{self.context_kwarg: context}
|
||||
if self.context_kwarg is not None
|
||||
else None,
|
||||
else None
|
||||
)
|
||||
result = await self.fn_metadata.call_fn_with_arg_validation(
|
||||
fn=self.fn,
|
||||
fn_is_async=self.is_async,
|
||||
arguments_to_validate=arguments,
|
||||
arguments_to_pass_directly=pass_args,
|
||||
)
|
||||
return _convert_to_content(result)
|
||||
except Exception as e:
|
||||
|
|
@ -158,9 +166,22 @@ def _convert_to_content(
|
|||
|
||||
return other_content + mcp_types
|
||||
|
||||
# if the result is a bytes object, convert it to a text content object
|
||||
if not isinstance(result, str):
|
||||
try:
|
||||
result = json.dumps(pydantic_core.to_jsonable_python(result))
|
||||
jsonable_result = pydantic_core.to_jsonable_python(result)
|
||||
if jsonable_result is None:
|
||||
return [TextContent(type="text", text="null")]
|
||||
elif isinstance(jsonable_result, bool):
|
||||
return [
|
||||
TextContent(
|
||||
type="text", text="true" if jsonable_result else "false"
|
||||
)
|
||||
]
|
||||
elif isinstance(jsonable_result, str | int | float):
|
||||
return [TextContent(type="text", text=str(jsonable_result))]
|
||||
else:
|
||||
return [TextContent(type="text", text=json.dumps(jsonable_result))]
|
||||
except Exception:
|
||||
result = str(result)
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,15 @@ from typing import (
|
|||
ForwardRef,
|
||||
)
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, create_model
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
TypeAdapter,
|
||||
ValidationError,
|
||||
WithJsonSchema,
|
||||
create_model,
|
||||
)
|
||||
from pydantic._internal._typing_extra import eval_type_backport
|
||||
from pydantic.fields import FieldInfo
|
||||
from pydantic_core import PydanticUndefined
|
||||
|
|
@ -80,14 +88,18 @@ class FuncMetadata(BaseModel):
|
|||
dicts (JSON objects) as JSON strings, which can be pre-parsed here.
|
||||
"""
|
||||
new_data = data.copy() # Shallow copy
|
||||
for field_name, _field_info in self.arg_model.model_fields.items():
|
||||
for field_name, field_info in self.arg_model.model_fields.items():
|
||||
if field_name not in data.keys():
|
||||
continue
|
||||
if isinstance(data[field_name], str):
|
||||
try:
|
||||
pre_parsed = json.loads(data[field_name])
|
||||
except json.JSONDecodeError:
|
||||
continue # Not JSON - skip
|
||||
|
||||
# Check if the pre_parsed value is valid for the field
|
||||
validator = TypeAdapter(field_info.annotation)
|
||||
validator.validate_python(pre_parsed)
|
||||
except (json.JSONDecodeError, ValidationError):
|
||||
continue # Not JSON or invalid for the field
|
||||
if isinstance(pre_parsed, str | int | float):
|
||||
# This is likely that the raw value is e.g. `"hello"` which we
|
||||
# Should really be parsed as '"hello"' in Python - but if we parse
|
||||
|
|
|
|||
|
|
@ -297,10 +297,87 @@ class TestResourceTemplate:
|
|||
content = await resource.read()
|
||||
assert content == "hello"
|
||||
|
||||
async def test_wildcard_param_can_create_resource(self):
|
||||
"""Test that wildcard parameters are valid."""
|
||||
|
||||
def identity(path: str) -> str:
|
||||
return path
|
||||
|
||||
template = ResourceTemplate.from_function(
|
||||
fn=identity,
|
||||
uri_template="test://{path*}.py",
|
||||
name="test",
|
||||
)
|
||||
|
||||
assert await template.create_resource(
|
||||
"test://path/to/test.py",
|
||||
{"path": "path/to/test.py"},
|
||||
)
|
||||
|
||||
async def test_wildcard_param_matches(self):
|
||||
def identify(path: str) -> str:
|
||||
return path
|
||||
|
||||
template = ResourceTemplate.from_function(
|
||||
fn=identify,
|
||||
uri_template="test://src/{path*}.py",
|
||||
name="test",
|
||||
)
|
||||
# Valid match
|
||||
params = template.matches("test://src/path/to/test.py")
|
||||
assert params == {"path": "path/to/test"}
|
||||
|
||||
async def test_multiple_wildcard_params(self):
|
||||
"""Test that multiple wildcard parameters are valid."""
|
||||
|
||||
def identity(path: str, path2: str) -> str:
|
||||
return f"{path}/{path2}"
|
||||
|
||||
template = ResourceTemplate.from_function(
|
||||
fn=identity,
|
||||
uri_template="test://{path*}/xyz/{path2*}",
|
||||
name="test",
|
||||
)
|
||||
|
||||
params = template.matches("test://path/to/xyz/abc")
|
||||
assert params == {"path": "path/to", "path2": "abc"}
|
||||
|
||||
async def test_wildcard_param_with_regular_param(self):
|
||||
"""Test that a wildcard parameter can be used with a regular parameter."""
|
||||
|
||||
def identity(prefix: str, path: str) -> str:
|
||||
return f"{prefix}/{path}"
|
||||
|
||||
template = ResourceTemplate.from_function(
|
||||
fn=identity,
|
||||
uri_template="test://{prefix}/{path*}",
|
||||
name="test",
|
||||
)
|
||||
|
||||
params = template.matches("test://src/path/to/test.py")
|
||||
assert params == {"prefix": "src", "path": "path/to/test.py"}
|
||||
|
||||
|
||||
class TestMatchUriTemplate:
|
||||
"""Test match_uri_template function."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri, expected_params",
|
||||
[
|
||||
("test://a/b", None),
|
||||
("test://a/b/c", None),
|
||||
("test://a/x/b", {"x": "x"}),
|
||||
("test://a/x/y/b", None),
|
||||
],
|
||||
)
|
||||
def test_match_uri_template_single_param(
|
||||
self, uri: str, expected_params: dict[str, str]
|
||||
):
|
||||
"""Test that match_uri_template uses the slash delimiter."""
|
||||
uri_template = "test://a/{x}/b"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == expected_params
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri, expected_params",
|
||||
[
|
||||
|
|
@ -361,7 +438,7 @@ class TestMatchUriTemplate:
|
|||
("other+prefix+test://foo/test/123", None),
|
||||
],
|
||||
)
|
||||
def test_match_prefixed_uri_template(
|
||||
def test_match_uri_template_with_prefix(
|
||||
self, uri: str, expected_params: dict[str, str] | None
|
||||
):
|
||||
"""Test matching URIs against a template with a prefix."""
|
||||
|
|
@ -369,10 +446,77 @@ class TestMatchUriTemplate:
|
|||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == expected_params
|
||||
|
||||
def test_quoted_params(self):
|
||||
def test_match_uri_template_quoted_params(self):
|
||||
uri_template = "user://{name}/{email}"
|
||||
quoted_name = quote("John Doe", safe="")
|
||||
quoted_email = quote("john@example.com", safe="")
|
||||
uri = f"user://{quoted_name}/{quoted_email}"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == {"name": "John Doe", "email": "john@example.com"}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri, expected_params",
|
||||
[
|
||||
("test://a/b", None),
|
||||
("test://a/b/c", None),
|
||||
("test://a/x/b", {"x": "x"}),
|
||||
("test://a/x/y/b", {"x": "x/y"}),
|
||||
("bad-prefix://a/x/y/b", None),
|
||||
("test://a/x/y/z", None),
|
||||
],
|
||||
)
|
||||
def test_match_uri_template_wildcard_param(
|
||||
self, uri: str, expected_params: dict[str, str]
|
||||
):
|
||||
"""Test that match_uri_template uses the slash delimiter."""
|
||||
uri_template = "test://a/{x*}/b"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == expected_params
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri, expected_params",
|
||||
[
|
||||
("test://a/x/y/b/c/d", {"x": "x/y", "y": "c/d"}),
|
||||
("bad-prefix://a/x/y/b/c/d", None),
|
||||
("test://a/x/y/c/d", None),
|
||||
("test://a/x/b/y", {"x": "x", "y": "y"}),
|
||||
],
|
||||
)
|
||||
def test_match_uri_template_multiple_wildcard_params(
|
||||
self, uri: str, expected_params: dict[str, str]
|
||||
):
|
||||
"""Test that match_uri_template uses the slash delimiter."""
|
||||
uri_template = "test://a/{x*}/b/{y*}"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == expected_params
|
||||
|
||||
def test_match_uri_template_wildcard_and_literal_param(self):
|
||||
"""Test that match_uri_template uses the slash delimiter."""
|
||||
uri = "test://a/x/y/b"
|
||||
uri_template = "test://a/{x*}/{y}"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == {"x": "x/y", "y": "b"}
|
||||
|
||||
def test_match_consecutive_params(self):
|
||||
"""Test that consecutive parameters without a / are not matched."""
|
||||
uri = "test://a/x/y"
|
||||
uri_template = "test://a/{x}{y}"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri, expected_params",
|
||||
[
|
||||
("file://abc/xyz.py", {"path": "xyz"}),
|
||||
("file://abc/x/y/z.py", {"path": "x/y/z"}),
|
||||
("file://abc/x/y/z/.py", {"path": "x/y/z/"}),
|
||||
("file://abc/x/y/z.md", None),
|
||||
("file://x/y/z.txt", None),
|
||||
],
|
||||
)
|
||||
def test_match_uri_template_with_non_slash_suffix(
|
||||
self, uri: str, expected_params: dict[str, str]
|
||||
):
|
||||
uri_template = "file://abc/{path*}.py"
|
||||
result = match_uri_template(uri=uri, uri_template=uri_template)
|
||||
assert result == expected_params
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import base64
|
||||
import json
|
||||
import re
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from dirty_equals import IsStr
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi import FastAPI, HTTPException, Response
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from mcp.types import TextContent
|
||||
from mcp.types import BlobResourceContents, TextContent, TextResourceContents
|
||||
from pydantic import BaseModel, TypeAdapter
|
||||
from pydantic.networks import AnyUrl
|
||||
|
||||
|
|
@ -66,6 +68,17 @@ def fastapi_app(users_db: dict[int, User]) -> FastAPI:
|
|||
user.name = name
|
||||
return user
|
||||
|
||||
@app.get("/ping", response_class=PlainTextResponse)
|
||||
async def ping() -> str:
|
||||
"""Ping the server."""
|
||||
return "pong"
|
||||
|
||||
@app.get("/ping-bytes")
|
||||
async def ping_bytes() -> Response:
|
||||
"""Ping the server and get a bytes response."""
|
||||
|
||||
return Response(content=b"pong")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
|
|
@ -120,7 +133,8 @@ class TestTools:
|
|||
"""
|
||||
By default, tools exclude GET methods
|
||||
"""
|
||||
tools = await fastmcp_openapi_server._mcp_list_tools()
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 2
|
||||
|
||||
assert tools[0].model_dump() == dict(
|
||||
|
|
@ -156,9 +170,10 @@ class TestTools:
|
|||
"""
|
||||
The tool created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
tool_response = await fastmcp_openapi_server._mcp_call_tool(
|
||||
"create_user_users_post", {"name": "David", "active": False}
|
||||
)
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
tool_response = await client.call_tool(
|
||||
"create_user_users_post", {"name": "David", "active": False}
|
||||
)
|
||||
|
||||
# Convert TextContent to dict for comparison
|
||||
assert isinstance(tool_response, list) and len(tool_response) == 1
|
||||
|
|
@ -173,10 +188,13 @@ class TestTools:
|
|||
assert len(response.json()) == 4
|
||||
|
||||
# Check that the user was created via MCP
|
||||
user_response = await fastmcp_openapi_server._mcp_read_resource(
|
||||
"resource://openapi/get_user_users__user_id__get/4"
|
||||
)
|
||||
user = user_response[0].content
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
user_response = await client.read_resource(
|
||||
"resource://openapi/get_user_users__user_id__get/4"
|
||||
)
|
||||
assert isinstance(user_response[0], TextResourceContents)
|
||||
response_text = user_response[0].text
|
||||
user = json.loads(response_text)
|
||||
assert user == expected_user
|
||||
|
||||
async def test_call_update_user_name_tool(
|
||||
|
|
@ -185,9 +203,11 @@ class TestTools:
|
|||
"""
|
||||
The tool created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
tool_response = await fastmcp_openapi_server._mcp_call_tool(
|
||||
"update_user_name_users__user_id__name_patch", {"user_id": 1, "name": "XYZ"}
|
||||
)
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
tool_response = await client.call_tool(
|
||||
"update_user_name_users__user_id__name_patch",
|
||||
{"user_id": 1, "name": "XYZ"},
|
||||
)
|
||||
|
||||
# Convert TextContent to dict for comparison
|
||||
assert isinstance(tool_response, list) and len(tool_response) == 1
|
||||
|
|
@ -202,10 +222,13 @@ class TestTools:
|
|||
assert expected_data in response.json()
|
||||
|
||||
# Check that the user was updated via MCP
|
||||
user_response = await fastmcp_openapi_server._mcp_read_resource(
|
||||
"resource://openapi/get_user_users__user_id__get/1"
|
||||
)
|
||||
user = user_response[0].content
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
user_response = await client.read_resource(
|
||||
"resource://openapi/get_user_users__user_id__get/1"
|
||||
)
|
||||
assert isinstance(user_response[0], TextResourceContents)
|
||||
response_text = user_response[0].text
|
||||
user = json.loads(response_text)
|
||||
assert user == expected_data
|
||||
|
||||
|
||||
|
|
@ -214,8 +237,9 @@ class TestResources:
|
|||
"""
|
||||
By default, resources exclude GET methods without parameters
|
||||
"""
|
||||
resources = await fastmcp_openapi_server._mcp_list_resources()
|
||||
assert len(resources) == 1
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 3
|
||||
assert resources[0].uri == AnyUrl("resource://openapi/get_users_users_get")
|
||||
assert resources[0].name == "get_users_users_get"
|
||||
|
||||
|
|
@ -228,17 +252,47 @@ class TestResources:
|
|||
"""
|
||||
The resource created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
|
||||
json_users = TypeAdapter(list[User]).dump_python(
|
||||
sorted(users_db.values(), key=lambda x: x.id)
|
||||
)
|
||||
resource_response = await fastmcp_openapi_server._mcp_read_resource(
|
||||
"resource://openapi/get_users_users_get"
|
||||
)
|
||||
resource = resource_response[0].content
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/get_users_users_get"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
resource = json.loads(response_text)
|
||||
assert resource == json_users
|
||||
response = await api_client.get("/users")
|
||||
assert response.json() == json_users
|
||||
|
||||
async def test_get_bytes_resource(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""Test reading a resource that returns bytes."""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/ping_bytes_ping_bytes_get"
|
||||
)
|
||||
assert isinstance(resource_response[0], BlobResourceContents)
|
||||
assert base64.b64decode(resource_response[0].blob) == b"pong"
|
||||
|
||||
async def test_get_str_resource(
|
||||
self,
|
||||
fastmcp_openapi_server: FastMCPOpenAPI,
|
||||
api_client,
|
||||
):
|
||||
"""Test reading a resource that returns a string."""
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/ping_ping_get"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
assert resource_response[0].text == "pong"
|
||||
|
||||
|
||||
class TestResourceTemplates:
|
||||
async def test_list_resource_templates(
|
||||
|
|
@ -247,7 +301,8 @@ class TestResourceTemplates:
|
|||
"""
|
||||
By default, resource templates exclude GET methods without parameters
|
||||
"""
|
||||
resource_templates = await fastmcp_openapi_server._mcp_list_resource_templates()
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resource_templates = await client.list_resource_templates()
|
||||
assert len(resource_templates) == 1
|
||||
assert resource_templates[0].name == "get_user_users__user_id__get"
|
||||
assert (
|
||||
|
|
@ -265,11 +320,14 @@ class TestResourceTemplates:
|
|||
The resource template created by the OpenAPI server should be the same as the original
|
||||
"""
|
||||
user_id = 2
|
||||
resource_response = await fastmcp_openapi_server._mcp_read_resource(
|
||||
f"resource://openapi/get_user_users__user_id__get/{user_id}"
|
||||
)
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
f"resource://openapi/get_user_users__user_id__get/{user_id}"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
resource = json.loads(response_text)
|
||||
|
||||
resource = resource_response[0].content
|
||||
assert resource == users_db[user_id].model_dump()
|
||||
response = await api_client.get(f"/users/{user_id}")
|
||||
assert resource == response.json()
|
||||
|
|
@ -280,7 +338,8 @@ class TestPrompts:
|
|||
"""
|
||||
By default, there are no prompts.
|
||||
"""
|
||||
prompts = await fastmcp_openapi_server._mcp_list_prompts()
|
||||
async with Client(fastmcp_openapi_server) as client:
|
||||
prompts = await client.list_prompts()
|
||||
assert len(prompts) == 0
|
||||
|
||||
|
||||
|
|
@ -494,20 +553,23 @@ class TestOpenAPI30Compatibility:
|
|||
|
||||
async def test_resource_discovery(self, openapi_30_server):
|
||||
"""Test that resources are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
resources = await openapi_30_server._mcp_list_resources()
|
||||
async with Client(openapi_30_server) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 1
|
||||
assert resources[0].uri == AnyUrl("resource://openapi/listProducts")
|
||||
|
||||
async def test_resource_template_discovery(self, openapi_30_server):
|
||||
"""Test that resource templates are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
templates = await openapi_30_server._mcp_list_resource_templates()
|
||||
async with Client(openapi_30_server) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "getProduct"
|
||||
assert templates[0].uriTemplate == r"resource://openapi/getProduct/{product_id}"
|
||||
|
||||
async def test_tool_discovery(self, openapi_30_server):
|
||||
"""Test that tools are correctly discovered from an OpenAPI 3.0 spec."""
|
||||
tools = await openapi_30_server._mcp_list_tools()
|
||||
async with Client(openapi_30_server) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 1
|
||||
assert tools[0].name == "createProduct"
|
||||
assert "name" in tools[0].inputSchema["properties"]
|
||||
|
|
@ -515,20 +577,26 @@ class TestOpenAPI30Compatibility:
|
|||
|
||||
async def test_resource_access(self, openapi_30_server):
|
||||
"""Test reading a resource from an OpenAPI 3.0 server."""
|
||||
resource_response = await openapi_30_server._mcp_read_resource(
|
||||
"resource://openapi/listProducts"
|
||||
)
|
||||
content = resource_response[0].content
|
||||
async with Client(openapi_30_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/listProducts"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
content = json.loads(response_text)
|
||||
assert len(content) == 2
|
||||
assert content[0]["name"] == "Product 1"
|
||||
assert content[1]["name"] == "Product 2"
|
||||
|
||||
async def test_resource_template_access(self, openapi_30_server):
|
||||
"""Test reading a resource from template from an OpenAPI 3.0 server."""
|
||||
resource_response = await openapi_30_server._mcp_read_resource(
|
||||
"resource://openapi/getProduct/p1"
|
||||
)
|
||||
content = resource_response[0].content
|
||||
async with Client(openapi_30_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/getProduct/p1"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
content = json.loads(response_text)
|
||||
assert content["id"] == "p1"
|
||||
assert content["name"] == "Product 1"
|
||||
assert content["price"] == 19.99
|
||||
|
|
@ -665,20 +733,23 @@ class TestOpenAPI31Compatibility:
|
|||
|
||||
async def test_resource_discovery(self, openapi_31_server):
|
||||
"""Test that resources are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
resources = await openapi_31_server._mcp_list_resources()
|
||||
async with Client(openapi_31_server) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 1
|
||||
assert resources[0].uri == AnyUrl("resource://openapi/listOrders")
|
||||
|
||||
async def test_resource_template_discovery(self, openapi_31_server):
|
||||
"""Test that resource templates are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
templates = await openapi_31_server._mcp_list_resource_templates()
|
||||
async with Client(openapi_31_server) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "getOrder"
|
||||
assert templates[0].uriTemplate == r"resource://openapi/getOrder/{order_id}"
|
||||
|
||||
async def test_tool_discovery(self, openapi_31_server):
|
||||
"""Test that tools are correctly discovered from an OpenAPI 3.1 spec."""
|
||||
tools = await openapi_31_server._mcp_list_tools()
|
||||
async with Client(openapi_31_server) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 1
|
||||
assert tools[0].name == "createOrder"
|
||||
assert "customer" in tools[0].inputSchema["properties"]
|
||||
|
|
@ -686,20 +757,26 @@ class TestOpenAPI31Compatibility:
|
|||
|
||||
async def test_resource_access(self, openapi_31_server):
|
||||
"""Test reading a resource from an OpenAPI 3.1 server."""
|
||||
resource_response = await openapi_31_server._mcp_read_resource(
|
||||
"resource://openapi/listOrders"
|
||||
)
|
||||
content = resource_response[0].content
|
||||
async with Client(openapi_31_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/listOrders"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
content = json.loads(response_text)
|
||||
assert len(content) == 2
|
||||
assert content[0]["customer"] == "Alice"
|
||||
assert content[1]["customer"] == "Bob"
|
||||
|
||||
async def test_resource_template_access(self, openapi_31_server):
|
||||
"""Test reading a resource from template from an OpenAPI 3.1 server."""
|
||||
resource_response = await openapi_31_server._mcp_read_resource(
|
||||
"resource://openapi/getOrder/o1"
|
||||
)
|
||||
content = resource_response[0].content
|
||||
async with Client(openapi_31_server) as client:
|
||||
resource_response = await client.read_resource(
|
||||
"resource://openapi/getOrder/o1"
|
||||
)
|
||||
assert isinstance(resource_response[0], TextResourceContents)
|
||||
response_text = resource_response[0].text
|
||||
content = json.loads(response_text)
|
||||
assert content["id"] == "o1"
|
||||
assert content["customer"] == "Alice"
|
||||
assert content["items"] == ["item1", "item2"]
|
||||
|
|
@ -729,8 +806,9 @@ class TestMountFastMCP:
|
|||
await mcp.import_server("fastapi", fastmcp_openapi_server)
|
||||
|
||||
# Check that resources are available with prefixed URIs
|
||||
resources = await mcp._mcp_list_resources()
|
||||
assert len(resources) == 1
|
||||
async with Client(mcp) as client:
|
||||
resources = await client.list_resources()
|
||||
assert len(resources) == 3
|
||||
# We're checking the key used by mcp to store the resource
|
||||
# The prefixed URI is used as the key, but the resource's original uri is preserved
|
||||
prefixed_uri = "fastapi+resource://openapi/get_users_users_get"
|
||||
|
|
@ -738,7 +816,8 @@ class TestMountFastMCP:
|
|||
assert resource is not None
|
||||
|
||||
# Check that templates are available with prefixed URIs
|
||||
templates = await mcp._mcp_list_resource_templates()
|
||||
async with Client(mcp) as client:
|
||||
templates = await client.list_resource_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "get_user_users__user_id__get"
|
||||
prefixed_template_uri = (
|
||||
|
|
@ -748,10 +827,12 @@ class TestMountFastMCP:
|
|||
assert template is not None
|
||||
|
||||
# Check that tools are available with prefixed names
|
||||
tools = await mcp._mcp_list_tools()
|
||||
async with Client(mcp) as client:
|
||||
tools = await client.list_tools()
|
||||
assert len(tools) == 2
|
||||
assert tools[0].name == "fastapi_create_user_users_post"
|
||||
assert tools[1].name == "fastapi_update_user_name_users__user_id__name_patch"
|
||||
|
||||
prompts = await mcp._mcp_list_prompts()
|
||||
async with Client(mcp) as client:
|
||||
prompts = await client.list_prompts()
|
||||
assert len(prompts) == 0
|
||||
|
|
|
|||
|
|
@ -1,25 +1,14 @@
|
|||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Annotated
|
||||
|
||||
import pytest
|
||||
from mcp.types import (
|
||||
BlobResourceContents,
|
||||
ImageContent,
|
||||
TextContent,
|
||||
TextResourceContents,
|
||||
)
|
||||
from pydantic import AnyUrl, Field
|
||||
from pydantic import Field
|
||||
|
||||
from fastmcp import Client, Context, FastMCP
|
||||
from fastmcp.exceptions import ClientError, NotFoundError, ToolError
|
||||
from fastmcp.prompts.prompt import EmbeddedResource, Message, UserMessage
|
||||
from fastmcp.resources import FileResource, FunctionResource
|
||||
from fastmcp.utilities.types import Image
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastmcp import Context
|
||||
from fastmcp import Client, FastMCP
|
||||
from fastmcp.exceptions import ClientError, NotFoundError
|
||||
|
||||
|
||||
class TestCreateServer:
|
||||
|
|
@ -253,6 +242,36 @@ class TestToolDecorator:
|
|||
# Original name should not be registered
|
||||
assert "multiply" not in tools
|
||||
|
||||
async def test_tool_with_annotated_arguments(self):
|
||||
"""Test that tools with annotated arguments work correctly."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.tool()
|
||||
def add(
|
||||
x: Annotated[int, Field(description="x is an int")],
|
||||
y: Annotated[str, Field(description="y is not an int")],
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
tool = (await mcp.get_tools())["add"]
|
||||
assert tool.parameters["properties"]["x"]["description"] == "x is an int"
|
||||
assert tool.parameters["properties"]["y"]["description"] == "y is not an int"
|
||||
|
||||
async def test_tool_with_field_defaults(self):
|
||||
"""Test that tools with annotated arguments work correctly."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.tool()
|
||||
def add(
|
||||
x: int = Field(description="x is an int"),
|
||||
y: str = Field(description="y is not an int"),
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
tool = (await mcp.get_tools())["add"]
|
||||
assert tool.parameters["properties"]["x"]["description"] == "x is an int"
|
||||
assert tool.parameters["properties"]["y"]["description"] == "y is not an int"
|
||||
|
||||
|
||||
class TestResourceDecorator:
|
||||
async def test_no_resources_before_decorator(self):
|
||||
|
|
@ -531,6 +550,18 @@ class TestTemplateDecorator:
|
|||
template = templates_dict["resource://{param}"]
|
||||
assert template.tags == {"template", "test-tag"}
|
||||
|
||||
async def test_template_decorator_wildcard_param(self):
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{param*}")
|
||||
def template_resource(param: str) -> str:
|
||||
return f"Template resource: {param}"
|
||||
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
template = templates_dict["resource://{param*}"]
|
||||
assert template.uri_template == "resource://{param*}"
|
||||
assert template.name == "template_resource"
|
||||
|
||||
|
||||
class TestPromptDecorator:
|
||||
async def test_prompt_decorator(self):
|
||||
|
|
@ -703,764 +734,3 @@ class TestPromptDecorator:
|
|||
assert len(prompts_dict) == 1
|
||||
prompt = prompts_dict["sample_prompt"]
|
||||
assert prompt.tags == {"example", "test-tag"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tool_server():
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.tool()
|
||||
def add(x: int, y: int) -> int:
|
||||
return x + y
|
||||
|
||||
@mcp.tool()
|
||||
def list_tool() -> list[str | int]:
|
||||
return ["x", 2]
|
||||
|
||||
@mcp.tool()
|
||||
def error_tool() -> None:
|
||||
raise ValueError("Test error")
|
||||
|
||||
@mcp.tool()
|
||||
def image_tool(path: str) -> Image:
|
||||
return Image(path)
|
||||
|
||||
@mcp.tool()
|
||||
def mixed_content_tool() -> list[TextContent | ImageContent]:
|
||||
return [
|
||||
TextContent(type="text", text="Hello"),
|
||||
ImageContent(type="image", data="abc", mimeType="image/png"),
|
||||
]
|
||||
|
||||
@mcp.tool()
|
||||
def mixed_list_fn(image_path: str) -> list:
|
||||
return [
|
||||
"text message",
|
||||
Image(image_path),
|
||||
{"key": "value"},
|
||||
TextContent(type="text", text="direct content"),
|
||||
]
|
||||
|
||||
return mcp
|
||||
|
||||
|
||||
class TestServerTools:
|
||||
async def test_add_tool_exists(self, tool_server: FastMCP):
|
||||
assert "add" in [t.name for t in await tool_server._mcp_list_tools()]
|
||||
|
||||
async def test_list_tools(self, tool_server: FastMCP):
|
||||
assert len(await tool_server._mcp_list_tools()) == 6
|
||||
|
||||
async def test_call_tool(self, tool_server: FastMCP):
|
||||
result = await tool_server._mcp_call_tool("add", {"x": 1, "y": 2})
|
||||
assert isinstance(result[0], TextContent)
|
||||
assert result[0].text == "3"
|
||||
|
||||
async def test_call_tool_as_client(self, tool_server: FastMCP):
|
||||
async with Client(tool_server) as client:
|
||||
result = await client.call_tool("add", {"x": 1, "y": 2})
|
||||
assert isinstance(result[0], TextContent)
|
||||
assert result[0].text == "3"
|
||||
|
||||
async def test_call_tool_error(self, tool_server: FastMCP):
|
||||
with pytest.raises(ToolError):
|
||||
await tool_server._mcp_call_tool("error_tool", {})
|
||||
|
||||
async def test_call_tool_error_as_client(self, tool_server: FastMCP):
|
||||
async with Client(tool_server) as client:
|
||||
with pytest.raises(Exception):
|
||||
await client.call_tool("error_tool", {})
|
||||
|
||||
async def test_call_tool_error_as_client_raw(self, tool_server: FastMCP):
|
||||
async with Client(tool_server) as client:
|
||||
result = await client.call_tool("error_tool", {}, _return_raw_result=True)
|
||||
assert result.isError
|
||||
assert isinstance(result.content[0], TextContent)
|
||||
assert "Test error" in result.content[0].text
|
||||
|
||||
async def test_tool_returns_list(self, tool_server: FastMCP):
|
||||
result = await tool_server._mcp_call_tool("list_tool", {})
|
||||
assert isinstance(result[0], TextContent)
|
||||
assert result[0].text == '["x", 2]'
|
||||
|
||||
async def test_tool_image_helper(self, tool_server: FastMCP, tmp_path: Path):
|
||||
# Create a test image
|
||||
image_path = tmp_path / "test.png"
|
||||
image_path.write_bytes(b"fake png data")
|
||||
|
||||
result = await tool_server._mcp_call_tool(
|
||||
"image_tool", {"path": str(image_path)}
|
||||
)
|
||||
content = result[0]
|
||||
assert isinstance(content, ImageContent)
|
||||
assert content.type == "image"
|
||||
assert content.mimeType == "image/png"
|
||||
# Verify base64 encoding
|
||||
decoded = base64.b64decode(content.data)
|
||||
assert decoded == b"fake png data"
|
||||
|
||||
async def test_tool_mixed_content(self, tool_server: FastMCP):
|
||||
result = await tool_server._mcp_call_tool("mixed_content_tool", {})
|
||||
assert len(result) == 2
|
||||
content1 = result[0]
|
||||
content2 = result[1]
|
||||
assert isinstance(content1, TextContent)
|
||||
assert content1.text == "Hello"
|
||||
assert isinstance(content2, ImageContent)
|
||||
assert content2.mimeType == "image/png"
|
||||
assert content2.data == "abc"
|
||||
|
||||
async def test_tool_mixed_list_with_image(
|
||||
self, tool_server: FastMCP, tmp_path: Path
|
||||
):
|
||||
"""Test that lists containing Image objects and other types are handled
|
||||
correctly. Note that the non-MCP content will be grouped together."""
|
||||
# Create a test image
|
||||
image_path = tmp_path / "test.png"
|
||||
image_path.write_bytes(b"test image data")
|
||||
|
||||
result = await tool_server._mcp_call_tool(
|
||||
"mixed_list_fn", {"image_path": str(image_path)}
|
||||
)
|
||||
assert len(result) == 3
|
||||
# Check text conversion
|
||||
content1 = result[0]
|
||||
assert isinstance(content1, TextContent)
|
||||
assert json.loads(content1.text) == ["text message", {"key": "value"}]
|
||||
# Check image conversion
|
||||
content2 = result[1]
|
||||
assert isinstance(content2, ImageContent)
|
||||
assert content2.mimeType == "image/png"
|
||||
assert base64.b64decode(content2.data) == b"test image data"
|
||||
# Check direct TextContent
|
||||
content3 = result[2]
|
||||
assert isinstance(content3, TextContent)
|
||||
assert content3.text == "direct content"
|
||||
|
||||
async def test_parameter_descriptions(self):
|
||||
mcp = FastMCP("Test Server")
|
||||
|
||||
@mcp.tool()
|
||||
def greet(
|
||||
name: str = Field(description="The name to greet"),
|
||||
title: str = Field(description="Optional title", default=""),
|
||||
) -> str:
|
||||
"""A greeting tool"""
|
||||
return f"Hello {title} {name}"
|
||||
|
||||
tools = await mcp._mcp_list_tools()
|
||||
assert len(tools) == 1
|
||||
tool = tools[0]
|
||||
|
||||
# Check that parameter descriptions are present in the schema
|
||||
properties = tool.inputSchema["properties"]
|
||||
assert "name" in properties
|
||||
assert properties["name"]["description"] == "The name to greet"
|
||||
assert "title" in properties
|
||||
assert properties["title"]["description"] == "Optional title"
|
||||
|
||||
|
||||
class TestServerResources:
|
||||
async def test_text_resource(self):
|
||||
mcp = FastMCP()
|
||||
|
||||
def get_text():
|
||||
return "Hello, world!"
|
||||
|
||||
resource = FunctionResource(
|
||||
uri=AnyUrl("resource://test"), name="test", fn=get_text
|
||||
)
|
||||
mcp.add_resource(resource)
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("resource://test"))
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "Hello, world!"
|
||||
|
||||
async def test_binary_resource(self):
|
||||
mcp = FastMCP()
|
||||
|
||||
def get_binary():
|
||||
return b"Binary data"
|
||||
|
||||
resource = FunctionResource(
|
||||
uri=AnyUrl("resource://binary"),
|
||||
name="binary",
|
||||
fn=get_binary,
|
||||
mime_type="application/octet-stream",
|
||||
)
|
||||
mcp.add_resource(resource)
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("resource://binary"))
|
||||
assert isinstance(result[0], BlobResourceContents)
|
||||
assert result[0].blob == base64.b64encode(b"Binary data").decode()
|
||||
|
||||
async def test_file_resource_text(self, tmp_path: Path):
|
||||
mcp = FastMCP()
|
||||
|
||||
# Create a text file
|
||||
text_file = tmp_path / "test.txt"
|
||||
text_file.write_text("Hello from file!")
|
||||
|
||||
resource = FileResource(
|
||||
uri=AnyUrl("file://test.txt"), name="test.txt", path=text_file
|
||||
)
|
||||
mcp.add_resource(resource)
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("file://test.txt"))
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "Hello from file!"
|
||||
|
||||
async def test_file_resource_binary(self, tmp_path: Path):
|
||||
mcp = FastMCP()
|
||||
|
||||
# Create a binary file
|
||||
binary_file = tmp_path / "test.bin"
|
||||
binary_file.write_bytes(b"Binary file data")
|
||||
|
||||
resource = FileResource(
|
||||
uri=AnyUrl("file://test.bin"),
|
||||
name="test.bin",
|
||||
path=binary_file,
|
||||
mime_type="application/octet-stream",
|
||||
)
|
||||
mcp.add_resource(resource)
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("file://test.bin"))
|
||||
assert isinstance(result[0], BlobResourceContents)
|
||||
assert result[0].blob == base64.b64encode(b"Binary file data").decode()
|
||||
|
||||
|
||||
class TestServerResourceTemplates:
|
||||
async def test_resource_with_params_not_in_uri(self):
|
||||
"""Test that a resource with function parameters raises an error if the URI
|
||||
parameters don't match"""
|
||||
mcp = FastMCP()
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="URI template must contain at least one parameter",
|
||||
):
|
||||
|
||||
@mcp.resource("resource://data")
|
||||
def get_data_fn(param: str) -> str:
|
||||
return f"Data: {param}"
|
||||
|
||||
async def test_resource_with_uri_params_without_args(self):
|
||||
"""Test that a resource with URI parameters is automatically a template"""
|
||||
mcp = FastMCP()
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="URI parameters .* must be a subset of the function arguments",
|
||||
):
|
||||
|
||||
@mcp.resource("resource://{param}")
|
||||
def get_data() -> str:
|
||||
return "Data"
|
||||
|
||||
async def test_resource_with_untyped_params(self):
|
||||
"""Test that a resource with untyped parameters raises an error"""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{param}")
|
||||
def get_data(param) -> str:
|
||||
return "Data"
|
||||
|
||||
async def test_resource_matching_params(self):
|
||||
"""Test that a resource with matching URI and function parameters works"""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{name}/data")
|
||||
def get_data(name: str) -> str:
|
||||
return f"Data for {name}"
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("resource://test/data"))
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "Data for test"
|
||||
|
||||
async def test_resource_mismatched_params(self):
|
||||
"""Test that mismatched parameters raise an error"""
|
||||
mcp = FastMCP()
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="URI parameters .* must be a subset of the required function arguments",
|
||||
):
|
||||
|
||||
@mcp.resource("resource://{name}/data")
|
||||
def get_data(user: str) -> str:
|
||||
return f"Data for {user}"
|
||||
|
||||
async def test_resource_multiple_params(self):
|
||||
"""Test that multiple parameters work correctly"""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{org}/{repo}/data")
|
||||
def get_data(org: str, repo: str) -> str:
|
||||
return f"Data for {org}/{repo}"
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(
|
||||
AnyUrl("resource://cursor/fastmcp/data")
|
||||
)
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "Data for cursor/fastmcp"
|
||||
|
||||
async def test_resource_multiple_mismatched_params(self):
|
||||
"""Test that mismatched parameters raise an error"""
|
||||
mcp = FastMCP()
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="URI parameters .* must be a subset of the required function arguments",
|
||||
):
|
||||
|
||||
@mcp.resource("resource://{org}/{repo}/data")
|
||||
def get_data_mismatched(org: str, repo_2: str) -> str:
|
||||
return f"Data for {org}"
|
||||
|
||||
"""Test that a resource with no parameters works as a regular resource"""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://static")
|
||||
def get_static_data() -> str:
|
||||
return "Static data"
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("resource://static"))
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "Static data"
|
||||
|
||||
async def test_template_with_default_params(self):
|
||||
"""Test that a template can have default parameters."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("math://add/{x}")
|
||||
def add(x: int, y: int = 10) -> int:
|
||||
return x + y
|
||||
|
||||
# Verify it's registered as a template
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
templates = list(templates_dict.values())
|
||||
assert len(templates) == 1
|
||||
assert templates[0].uri_template == "math://add/{x}"
|
||||
|
||||
# Call the template and verify it uses the default value
|
||||
async with Client(mcp) as client:
|
||||
result = await client.read_resource(AnyUrl("math://add/5"))
|
||||
assert isinstance(result[0], TextResourceContents)
|
||||
assert result[0].text == "15" # 5 + default 10
|
||||
|
||||
# Can also call with explicit params
|
||||
resource = await mcp._resource_manager.get_resource("math://add/7")
|
||||
assert isinstance(resource, FunctionResource)
|
||||
result = await resource.read()
|
||||
assert result == "17" # 7 + default 10
|
||||
|
||||
async def test_template_to_resource_conversion(self):
|
||||
"""Test that a template can be converted to a resource."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{name}/data")
|
||||
def get_data(name: str) -> str:
|
||||
return f"Data for {name}"
|
||||
|
||||
# Verify it's registered as a template
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
templates = list(templates_dict.values())
|
||||
assert len(templates) == 1
|
||||
assert templates[0].uri_template == "resource://{name}/data"
|
||||
|
||||
# When accessed, should create a concrete resource
|
||||
resource = await mcp._resource_manager.get_resource("resource://test/data")
|
||||
assert isinstance(resource, FunctionResource)
|
||||
result = await resource.read()
|
||||
assert result == "Data for test"
|
||||
|
||||
async def test_stacked_resource_template_decorators(self):
|
||||
"""Test that resource template decorators can be stacked."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("users://email/{email}")
|
||||
@mcp.resource("users://name/{name}")
|
||||
def lookup_user(name: str | None = None, email: str | None = None) -> dict:
|
||||
if name:
|
||||
return {
|
||||
"id": "123",
|
||||
"name": name,
|
||||
"email": "dummy@example.com",
|
||||
"lookup": "name",
|
||||
}
|
||||
elif email:
|
||||
return {
|
||||
"id": "123",
|
||||
"name": "Test User",
|
||||
"email": email,
|
||||
"lookup": "email",
|
||||
}
|
||||
else:
|
||||
raise ValueError("Either name or email must be provided")
|
||||
|
||||
# Verify both templates are registered
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
templates = list(templates_dict.values())
|
||||
assert len(templates) == 2
|
||||
template_uris = {t.uri_template for t in templates}
|
||||
assert "users://email/{email}" in template_uris
|
||||
assert "users://name/{name}" in template_uris
|
||||
|
||||
# Test lookup by email
|
||||
async with Client(mcp) as client:
|
||||
email_result = await client.read_resource(
|
||||
AnyUrl("users://email/user@example.com")
|
||||
)
|
||||
assert isinstance(email_result[0], TextResourceContents)
|
||||
email_data = json.loads(email_result[0].text)
|
||||
assert email_data["lookup"] == "email"
|
||||
assert email_data["email"] == "user@example.com"
|
||||
|
||||
# Test lookup by name
|
||||
name_result = await client.read_resource(AnyUrl("users://name/John"))
|
||||
assert isinstance(name_result[0], TextResourceContents)
|
||||
name_data = json.loads(name_result[0].text)
|
||||
assert name_data["lookup"] == "name"
|
||||
assert name_data["name"] == "John"
|
||||
assert name_data["email"] == "dummy@example.com"
|
||||
|
||||
async def test_template_decorator_with_tags(self):
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{param}", tags={"template", "test-tag"})
|
||||
def template_resource(param: str) -> str:
|
||||
return f"Template resource: {param}"
|
||||
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
template = templates_dict["resource://{param}"]
|
||||
assert template.tags == {"template", "test-tag"}
|
||||
|
||||
|
||||
class TestContextInjection:
|
||||
"""Test context injection in tools."""
|
||||
|
||||
async def test_context_detection(self):
|
||||
"""Test that context parameters are properly detected."""
|
||||
mcp = FastMCP()
|
||||
|
||||
def tool_with_context(x: int, ctx: Context) -> str:
|
||||
return f"Request {ctx.request_id}: {x}"
|
||||
|
||||
tool = mcp._tool_manager.add_tool_from_fn(tool_with_context)
|
||||
assert tool.context_kwarg == "ctx"
|
||||
|
||||
async def test_context_injection(self):
|
||||
"""Test that context is properly injected into tool calls."""
|
||||
mcp = FastMCP()
|
||||
|
||||
def tool_with_context(x: int, ctx: Context) -> str:
|
||||
assert ctx.request_id is not None
|
||||
return f"Request {ctx.request_id}: {x}"
|
||||
|
||||
mcp.add_tool(tool_with_context)
|
||||
async with Client(mcp) as client:
|
||||
result = await client.call_tool("tool_with_context", {"x": 42})
|
||||
assert len(result) == 1
|
||||
content = result[0]
|
||||
assert isinstance(content, TextContent)
|
||||
assert "Request" in content.text
|
||||
assert "42" in content.text
|
||||
|
||||
async def test_async_context(self):
|
||||
"""Test that context works in async functions."""
|
||||
mcp = FastMCP()
|
||||
|
||||
async def async_tool(x: int, ctx: Context) -> str:
|
||||
assert ctx.request_id is not None
|
||||
return f"Async request {ctx.request_id}: {x}"
|
||||
|
||||
mcp.add_tool(async_tool)
|
||||
async with Client(mcp) as client:
|
||||
result = await client.call_tool("async_tool", {"x": 42})
|
||||
assert len(result) == 1
|
||||
content = result[0]
|
||||
assert isinstance(content, TextContent)
|
||||
assert "Async request" in content.text
|
||||
assert "42" in content.text
|
||||
|
||||
async def test_context_logging(self):
|
||||
from unittest.mock import patch
|
||||
|
||||
import mcp.server.session
|
||||
|
||||
"""Test that context logging methods work."""
|
||||
mcp = FastMCP()
|
||||
|
||||
async def logging_tool(msg: str, ctx: Context) -> str:
|
||||
await ctx.debug("Debug message")
|
||||
await ctx.info("Info message")
|
||||
await ctx.warning("Warning message")
|
||||
await ctx.error("Error message")
|
||||
return f"Logged messages for {msg}"
|
||||
|
||||
mcp.add_tool(logging_tool)
|
||||
|
||||
with patch("mcp.server.session.ServerSession.send_log_message") as mock_log:
|
||||
async with Client(mcp) as client:
|
||||
result = await client.call_tool("logging_tool", {"msg": "test"})
|
||||
assert len(result) == 1
|
||||
content = result[0]
|
||||
assert isinstance(content, TextContent)
|
||||
assert "Logged messages for test" in content.text
|
||||
|
||||
assert mock_log.call_count == 4
|
||||
mock_log.assert_any_call(
|
||||
level="debug", data="Debug message", logger=None
|
||||
)
|
||||
mock_log.assert_any_call(level="info", data="Info message", logger=None)
|
||||
mock_log.assert_any_call(
|
||||
level="warning", data="Warning message", logger=None
|
||||
)
|
||||
mock_log.assert_any_call(
|
||||
level="error", data="Error message", logger=None
|
||||
)
|
||||
|
||||
async def test_optional_context(self):
|
||||
"""Test that context is optional."""
|
||||
mcp = FastMCP()
|
||||
|
||||
def no_context(x: int) -> int:
|
||||
return x * 2
|
||||
|
||||
mcp.add_tool(no_context)
|
||||
async with Client(mcp) as client:
|
||||
result = await client.call_tool("no_context", {"x": 21})
|
||||
assert len(result) == 1
|
||||
content = result[0]
|
||||
assert isinstance(content, TextContent)
|
||||
assert content.text == "42"
|
||||
|
||||
async def test_context_resource_access(self):
|
||||
"""Test that context can access resources."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("test://data")
|
||||
def test_resource() -> str:
|
||||
return "resource data"
|
||||
|
||||
@mcp.tool()
|
||||
async def tool_with_resource(ctx: Context) -> str:
|
||||
r_iter = await ctx.read_resource("test://data")
|
||||
r_list = list(r_iter)
|
||||
assert len(r_list) == 1
|
||||
r = r_list[0]
|
||||
return f"Read resource: {r.content} with mime type {r.mime_type}"
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.call_tool("tool_with_resource", {})
|
||||
assert len(result) == 1
|
||||
content = result[0]
|
||||
assert isinstance(content, TextContent)
|
||||
assert "Read resource: resource data" in content.text
|
||||
|
||||
|
||||
class TestServerPrompts:
|
||||
"""Test prompt functionality in FastMCP server."""
|
||||
|
||||
async def test_prompt_decorator(self):
|
||||
"""Test that the prompt decorator registers prompts correctly."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt()
|
||||
def fn() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
prompts_dict = await mcp.get_prompts()
|
||||
assert len(prompts_dict) == 1
|
||||
prompt = prompts_dict["fn"]
|
||||
assert prompt.name == "fn"
|
||||
# Don't compare functions directly since validate_call wraps them
|
||||
content = await prompt.render()
|
||||
assert isinstance(content[0].content, TextContent)
|
||||
assert content[0].content.text == "Hello, world!"
|
||||
|
||||
async def test_prompt_decorator_with_name(self):
|
||||
"""Test prompt decorator with custom name."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt(name="custom_name")
|
||||
def fn() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
prompts_dict = await mcp.get_prompts()
|
||||
assert len(prompts_dict) == 1
|
||||
prompt = prompts_dict["custom_name"]
|
||||
assert prompt.name == "custom_name"
|
||||
content = await prompt.render()
|
||||
assert isinstance(content[0].content, TextContent)
|
||||
assert content[0].content.text == "Hello, world!"
|
||||
|
||||
async def test_prompt_decorator_with_description(self):
|
||||
"""Test prompt decorator with custom description."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt(description="A custom description")
|
||||
def fn() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
prompts_dict = await mcp.get_prompts()
|
||||
assert len(prompts_dict) == 1
|
||||
prompt = prompts_dict["fn"]
|
||||
assert prompt.description == "A custom description"
|
||||
content = await prompt.render()
|
||||
assert isinstance(content[0].content, TextContent)
|
||||
assert content[0].content.text == "Hello, world!"
|
||||
|
||||
def test_prompt_decorator_error(self):
|
||||
"""Test error when decorator is used incorrectly."""
|
||||
mcp = FastMCP()
|
||||
with pytest.raises(TypeError, match="decorator was used incorrectly"):
|
||||
|
||||
@mcp.prompt # type: ignore
|
||||
def fn() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
async def test_list_prompts(self):
|
||||
"""Test listing prompts through MCP protocol."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt()
|
||||
def fn(name: str, optional: str = "default") -> str:
|
||||
return f"Hello, {name}! {optional}"
|
||||
|
||||
prompts_dict = await mcp.get_prompts()
|
||||
assert len(prompts_dict) == 1
|
||||
|
||||
async with Client(mcp) as client:
|
||||
prompts = await client.list_prompts()
|
||||
assert len(prompts) == 1
|
||||
assert prompts[0].name == "fn"
|
||||
assert prompts[0].description is None
|
||||
assert prompts[0].arguments is not None
|
||||
assert len(prompts[0].arguments) == 2
|
||||
assert prompts[0].arguments[0].name == "name"
|
||||
assert prompts[0].arguments[0].required is True
|
||||
assert prompts[0].arguments[1].name == "optional"
|
||||
assert prompts[0].arguments[1].required is False
|
||||
|
||||
async def test_get_prompt(self):
|
||||
"""Test getting a prompt through MCP protocol."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt()
|
||||
def fn(name: str) -> str:
|
||||
return f"Hello, {name}!"
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.get_prompt("fn", {"name": "World"})
|
||||
assert len(result) == 1
|
||||
message = result[0]
|
||||
assert message.role == "user"
|
||||
content = message.content
|
||||
assert isinstance(content, TextContent)
|
||||
assert content.text == "Hello, World!"
|
||||
|
||||
async def test_get_prompt_with_resource(self):
|
||||
"""Test getting a prompt that returns resource content."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt()
|
||||
def fn() -> Message:
|
||||
return UserMessage(
|
||||
content=EmbeddedResource(
|
||||
type="resource",
|
||||
resource=TextResourceContents(
|
||||
uri=AnyUrl("file://file.txt"),
|
||||
text="File contents",
|
||||
mimeType="text/plain",
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
async with Client(mcp) as client:
|
||||
result = await client.get_prompt("fn")
|
||||
assert result[0].role == "user"
|
||||
content = result[0].content
|
||||
assert isinstance(content, EmbeddedResource)
|
||||
resource = content.resource
|
||||
assert isinstance(resource, TextResourceContents)
|
||||
assert resource.text == "File contents"
|
||||
assert resource.mimeType == "text/plain"
|
||||
|
||||
async def test_get_unknown_prompt(self):
|
||||
"""Test error when getting unknown prompt."""
|
||||
mcp = FastMCP()
|
||||
with pytest.raises(ClientError, match="Unknown prompt"):
|
||||
async with Client(mcp) as client:
|
||||
await client.get_prompt("unknown")
|
||||
|
||||
async def test_get_prompt_missing_args(self):
|
||||
"""Test error when required arguments are missing."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt()
|
||||
def prompt_fn(name: str) -> str:
|
||||
return f"Hello, {name}!"
|
||||
|
||||
with pytest.raises(ClientError, match="Missing required arguments"):
|
||||
async with Client(mcp) as client:
|
||||
await client.get_prompt("prompt_fn")
|
||||
|
||||
async def test_tool_decorator_with_tags(self):
|
||||
"""Test that the tool decorator properly sets tags."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.tool(tags={"example", "test-tag"})
|
||||
def sample_tool(x: int) -> int:
|
||||
return x * 2
|
||||
|
||||
# Verify the tags were set correctly
|
||||
tools = mcp._tool_manager.list_tools()
|
||||
assert len(tools) == 1
|
||||
assert tools[0].tags == {"example", "test-tag"}
|
||||
|
||||
async def test_resource_decorator_with_tags(self):
|
||||
"""Test that the resource decorator supports tags."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://data", tags={"example", "test-tag"})
|
||||
def get_data() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
resources_dict = await mcp.get_resources()
|
||||
resources = list(resources_dict.values())
|
||||
assert len(resources) == 1
|
||||
assert resources[0].tags == {"example", "test-tag"}
|
||||
|
||||
async def test_template_decorator_with_tags(self):
|
||||
"""Test that the template decorator properly sets tags."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.resource("resource://{param}", tags={"template", "test-tag"})
|
||||
def template_resource(param: str) -> str:
|
||||
return f"Template resource: {param}"
|
||||
|
||||
templates_dict = await mcp.get_resource_templates()
|
||||
template = templates_dict["resource://{param}"]
|
||||
assert template.tags == {"template", "test-tag"}
|
||||
|
||||
async def test_prompt_decorator_with_tags(self):
|
||||
"""Test that the prompt decorator properly sets tags."""
|
||||
mcp = FastMCP()
|
||||
|
||||
@mcp.prompt(tags={"example", "test-tag"})
|
||||
def sample_prompt() -> str:
|
||||
return "Hello, world!"
|
||||
|
||||
prompts_dict = await mcp.get_prompts()
|
||||
assert len(prompts_dict) == 1
|
||||
prompt = prompts_dict["sample_prompt"]
|
||||
assert prompt.tags == {"example", "test-tag"}
|
||||
|
|
|
|||
1398
tests/server/test_server_interactions.py
Normal file
1398
tests/server/test_server_interactions.py
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -2,8 +2,10 @@ import json
|
|||
import logging
|
||||
|
||||
import pytest
|
||||
from mcp.types import ImageContent, TextContent
|
||||
from pydantic import BaseModel
|
||||
|
||||
from fastmcp import Context, FastMCP, Image
|
||||
from fastmcp.exceptions import NotFoundError, ToolError
|
||||
from fastmcp.tools import ToolManager
|
||||
from fastmcp.tools.tool import Tool
|
||||
|
|
@ -68,6 +70,18 @@ class TestAddTools:
|
|||
assert "age" in tool.parameters["$defs"]["UserInput"]["properties"]
|
||||
assert "flag" in tool.parameters["properties"]
|
||||
|
||||
async def test_tool_with_image_return(self):
|
||||
def image_tool(data: bytes) -> Image:
|
||||
return Image(data=data)
|
||||
|
||||
manager = ToolManager()
|
||||
manager.add_tool_from_fn(image_tool)
|
||||
|
||||
tool = manager.get_tool("image_tool")
|
||||
result = await tool.run({"data": "test.png"})
|
||||
assert tool.parameters["properties"]["data"]["type"] == "string"
|
||||
assert isinstance(result[0], ImageContent)
|
||||
|
||||
def test_add_invalid_tool(self):
|
||||
manager = ToolManager()
|
||||
with pytest.raises(AttributeError):
|
||||
|
|
@ -263,7 +277,6 @@ class TestCallTools:
|
|||
result = await manager.call_tool("double", {"n": 5})
|
||||
assert isinstance(result, list)
|
||||
assert len(result) == 1
|
||||
from mcp.types import TextContent
|
||||
|
||||
assert isinstance(result[0], TextContent)
|
||||
assert result[0].text == "10"
|
||||
|
|
@ -279,7 +292,6 @@ class TestCallTools:
|
|||
result = await manager.call_tool("add", {"a": 1})
|
||||
assert isinstance(result, list)
|
||||
assert len(result) == 1
|
||||
from mcp.types import TextContent
|
||||
|
||||
assert isinstance(result[0], TextContent)
|
||||
assert result[0].text == "2"
|
||||
|
|
@ -307,7 +319,6 @@ class TestCallTools:
|
|||
manager = ToolManager()
|
||||
manager.add_tool_from_fn(sum_vals)
|
||||
# Try both with plain list and with JSON list
|
||||
from mcp.types import TextContent
|
||||
|
||||
result = await manager.call_tool("sum_vals", {"vals": "[1, 2, 3]"})
|
||||
assert isinstance(result, list)
|
||||
|
|
@ -329,7 +340,6 @@ class TestCallTools:
|
|||
|
||||
manager = ToolManager()
|
||||
manager.add_tool_from_fn(concat_strs)
|
||||
from mcp.types import TextContent
|
||||
|
||||
# Try both with plain python object and with JSON list
|
||||
result = await manager.call_tool("concat_strs", {"vals": ["a", "b", "c"]})
|
||||
|
|
@ -357,10 +367,6 @@ class TestCallTools:
|
|||
assert result[0].text == '"a"'
|
||||
|
||||
async def test_call_tool_with_complex_model(self):
|
||||
from mcp.types import TextContent
|
||||
|
||||
from fastmcp import Context
|
||||
|
||||
class MyShrimpTank(BaseModel):
|
||||
class Shrimp(BaseModel):
|
||||
name: str
|
||||
|
|
@ -397,8 +403,6 @@ class TestCallTools:
|
|||
|
||||
class TestToolSchema:
|
||||
async def test_context_arg_excluded_from_schema(self):
|
||||
from fastmcp import Context
|
||||
|
||||
def something(a: int, ctx: Context) -> int:
|
||||
return a
|
||||
|
||||
|
|
@ -415,7 +419,6 @@ class TestContextHandling:
|
|||
def test_context_parameter_detection(self):
|
||||
"""Test that context parameters are properly detected in
|
||||
Tool.from_function()."""
|
||||
from fastmcp import Context
|
||||
|
||||
def tool_with_context(x: int, ctx: Context) -> str:
|
||||
return str(x)
|
||||
|
|
@ -432,9 +435,6 @@ class TestContextHandling:
|
|||
|
||||
async def test_context_injection(self):
|
||||
"""Test that context is properly injected during tool execution."""
|
||||
from mcp.types import TextContent
|
||||
|
||||
from fastmcp import Context, FastMCP
|
||||
|
||||
def tool_with_context(x: int, ctx: Context) -> str:
|
||||
assert isinstance(ctx, Context)
|
||||
|
|
@ -453,9 +453,6 @@ class TestContextHandling:
|
|||
|
||||
async def test_context_injection_async(self):
|
||||
"""Test that context is properly injected in async tools."""
|
||||
from mcp.types import TextContent
|
||||
|
||||
from fastmcp import Context, FastMCP
|
||||
|
||||
async def async_tool(x: int, ctx: Context) -> str:
|
||||
assert isinstance(ctx, Context)
|
||||
|
|
@ -476,8 +473,6 @@ class TestContextHandling:
|
|||
"""Test that context is optional when calling tools."""
|
||||
from mcp.types import TextContent
|
||||
|
||||
from fastmcp import Context
|
||||
|
||||
def tool_with_context(x: int, ctx: Context | None = None) -> str:
|
||||
return str(x)
|
||||
|
||||
|
|
@ -492,7 +487,6 @@ class TestContextHandling:
|
|||
|
||||
async def test_context_error_handling(self):
|
||||
"""Test error handling when context injection fails."""
|
||||
from fastmcp import Context, FastMCP
|
||||
|
||||
def tool_with_context(x: int, ctx: Context) -> str:
|
||||
raise ValueError("Test error")
|
||||
|
|
|
|||
|
|
@ -174,6 +174,74 @@ def test_str_vs_list_str():
|
|||
assert result["str_or_list"] == ["hello", "world"]
|
||||
|
||||
|
||||
def test_keep_str_as_str():
|
||||
"""Test that string arguments are kept as strings"""
|
||||
|
||||
def func_with_str_types(string: str):
|
||||
return string
|
||||
|
||||
meta = func_metadata(func_with_str_types)
|
||||
result = meta.pre_parse_json(
|
||||
{"string": "{'nice to meet you': 'hello', 'goodbye': 5}"}
|
||||
)
|
||||
assert result["string"] == "{'nice to meet you': 'hello', 'goodbye': 5}"
|
||||
|
||||
|
||||
def test_missing_annotation():
|
||||
"""Test that missing annotations don't cause errors"""
|
||||
|
||||
def fn(x, y):
|
||||
return x + y
|
||||
|
||||
meta = func_metadata(fn)
|
||||
result = meta.pre_parse_json({"x": "1", "y": "2"})
|
||||
assert result["x"] == "1"
|
||||
assert result["y"] == "2"
|
||||
|
||||
|
||||
def test_keep_str_union_as_str():
|
||||
"""Test that string arguments are kept as strings"""
|
||||
|
||||
def func_with_str_types(string: str | dict[int, str] | None):
|
||||
return string
|
||||
|
||||
meta = func_metadata(func_with_str_types)
|
||||
result = meta.pre_parse_json(
|
||||
{"string": "{'nice to meet you': 'hello', 'goodbye': 5}"}
|
||||
)
|
||||
assert result["string"] == "{'nice to meet you': 'hello', 'goodbye': 5}"
|
||||
|
||||
|
||||
def test_keep_str_complex_type_as_str():
|
||||
"""Test that string arguments are kept as strings because it's invalid for the field"""
|
||||
|
||||
class SomeModel(BaseModel):
|
||||
x: int
|
||||
y: dict[int, str]
|
||||
|
||||
def func_with_str_types(string: str | SomeModel | None):
|
||||
return string
|
||||
|
||||
meta = func_metadata(func_with_str_types)
|
||||
result = meta.pre_parse_json({"string": '{"x": 1, "y": {"invalid": "hello"}}'})
|
||||
assert result["string"] == '{"x": 1, "y": {"invalid": "hello"}}'
|
||||
|
||||
|
||||
def test_convert_str_to_complex_type():
|
||||
"""Test that string arguments are converted to the complex type because it's valid for the field"""
|
||||
|
||||
class SomeModel(BaseModel):
|
||||
x: int
|
||||
y: dict[int, str]
|
||||
|
||||
def func_with_str_types(string: str | SomeModel | None):
|
||||
return string
|
||||
|
||||
meta = func_metadata(func_with_str_types)
|
||||
result = meta.pre_parse_json({"string": '{"x": 1, "y": {"1": "hello"}}'})
|
||||
assert result["string"] == {"x": 1, "y": {"1": "hello"}}
|
||||
|
||||
|
||||
def test_skip_names():
|
||||
"""Test that skipped parameters are not included in the model"""
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue