From b81d1a11ec8f901db02c5ccd07be4d608aab476c Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 12:11:00 -0400 Subject: [PATCH 01/32] Indicate that Image class is for returns --- README.md | 36 +++++++++++++++----------------- docs/servers/tools.mdx | 11 +++++++--- tests/tools/test_tool_manager.py | 34 +++++++++++++----------------- 3 files changed, 39 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 03748d3f8..cad1d02e6 100644 --- a/README.md +++ b/README.md @@ -332,32 +332,30 @@ 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. + + +The below code requires the `pillow` library to be installed. + ```python -from fastmcp import FastMCP, Image -from PIL import Image as PILImage -import io +from mcp.server.fastmcp import FastMCP, Image +try: + from PIL import Image as PILImage +except ImportError: + raise ImportError("Please install the `pillow` library to run this example.") + +mcp = FastMCP("My App") -mcp = FastMCP("Image Demo") @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 +def create_thumbnail(image_path: str) -> Image: + """Create a thumbnail from an image""" + img = PILImage.open(image_path) img.thumbnail((100, 100)) - buffer = io.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) + return Image(data=img.tobytes(), format="png") ``` -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 diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index df8e21bd6..7839efa89 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -209,13 +209,18 @@ 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). ```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: diff --git a/tests/tools/test_tool_manager.py b/tests/tools/test_tool_manager.py index 8206fd645..c58406c6d 100644 --- a/tests/tools/test_tool_manager.py +++ b/tests/tools/test_tool_manager.py @@ -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") From 1fa2e67403310ff504ac5fefa0c59eace81a27ab Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 12:11:12 -0400 Subject: [PATCH 02/32] Improve error message when parsing params --- src/fastmcp/tools/tool.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py index cfdef7692..e4af4749a 100644 --- a/src/fastmcp/tools/tool.py +++ b/src/fastmcp/tools/tool.py @@ -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, From fa3e327cac08b8a821b3d42af3a689f8774bacb0 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 12:13:28 -0400 Subject: [PATCH 03/32] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index cad1d02e6..d0b83eb75 100644 --- a/README.md +++ b/README.md @@ -340,6 +340,7 @@ The below code requires the `pillow` library to be installed. ```python from mcp.server.fastmcp import FastMCP, Image +from io import BytesIO try: from PIL import Image as PILImage except ImportError: @@ -347,13 +348,14 @@ except ImportError: mcp = FastMCP("My App") - @mcp.tool() def create_thumbnail(image_path: str) -> Image: """Create a thumbnail from an image""" img = PILImage.open(image_path) - img.thumbnail((100, 100)) - return Image(data=img.tobytes(), format="png") + img.thumbnail((100, 100)) + buffer = BytesIO() + img.save(buffer, format="PNG") + return Image(data=buffer.getvalue(), format="png") ``` 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. From f704624c6d9cda3555bc32d9c563ffb71a979ace Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 12:15:57 -0400 Subject: [PATCH 04/32] Update mermaid diagram --- docs/patterns/proxy.mdx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/patterns/proxy.mdx b/docs/patterns/proxy.mdx index 412cbfd6e..553f792f5 100644 --- a/docs/patterns/proxy.mdx +++ b/docs/patterns/proxy.mdx @@ -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). From 4e076c7c8fa3826a4dffc393aa45504080f0f039 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 15:01:36 -0400 Subject: [PATCH 05/32] Add wildcard params --- docs/servers/resources.mdx | 66 +++++++++++++++++++++-- src/fastmcp/resources/template.py | 7 ++- tests/resources/test_resource_template.py | 64 +++++++++++++++++++++- 3 files changed, 130 insertions(+), 7 deletions(-) diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 078e47385..9e13b98bd 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -5,6 +5,8 @@ description: Expose data sources and dynamic content generators to your MCP clie 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. @@ -183,6 +185,8 @@ Use these when the content is static or sourced directly from a file/URL, bypass #### Custom Resource Keys + + When adding resources directly with `mcp.add_resource()`, you can optionally provide a custom storage key: ```python @@ -201,6 +205,10 @@ Note that this parameter is only available when using `add_resource()` directly 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 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 +241,61 @@ 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 + + + +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 +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:// + 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 + + When creating resource templates, FastMCP enforces two rules for the relationship between URI template parameters and function parameters: @@ -315,6 +373,8 @@ Templates provide a powerful way to expose parameterized data access points foll ### Custom Template Keys + + Similar to resources, you can provide custom keys when directly adding templates: ```python diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py index bba1c4467..d174365f3 100644 --- a/src/fastmcp/resources/template.py +++ b/src/fastmcp/resources/template.py @@ -24,13 +24,16 @@ from fastmcp.utilities.types import _convert_set_defaults 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}$") diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py index a8b01c11c..7dba257e4 100644 --- a/tests/resources/test_resource_template.py +++ b/tests/resources/test_resource_template.py @@ -301,6 +301,23 @@ class TestResourceTemplate: 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 +378,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 +386,53 @@ 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"} From f2c5f0d708e68032d4382d3a01cdd0d45e516c28 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 15:07:06 -0400 Subject: [PATCH 06/32] Update test_resource_template.py --- tests/resources/test_resource_template.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py index 7dba257e4..38b2f45f9 100644 --- a/tests/resources/test_resource_template.py +++ b/tests/resources/test_resource_template.py @@ -436,3 +436,10 @@ class TestMatchUriTemplate: 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 From 9b20e8a6b04a98e6a6592b39a4fc66adaa0bd47b Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Thu, 24 Apr 2025 20:27:27 -0400 Subject: [PATCH 07/32] update version badges --- docs/clients/transports.mdx | 4 ++++ docs/patterns/contrib.mdx | 3 +++ docs/servers/fastmcp.mdx | 6 ++++++ docs/servers/prompts.mdx | 4 ++++ docs/servers/resources.mdx | 2 ++ docs/servers/tools.mdx | 2 ++ docs/snippets/version-badge.mdx | 13 +++++++++---- docs/style.css | 33 +++++++++++++++------------------ 8 files changed, 45 insertions(+), 22 deletions(-) diff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdx index a64fb0c25..67a70b5b2 100644 --- a/docs/clients/transports.mdx +++ b/docs/clients/transports.mdx @@ -5,6 +5,10 @@ description: Understand the different ways FastMCP Clients can connect to server icon: link --- +import { VersionBadge } from "/snippets/version-badge.mdx" + + + 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. diff --git a/docs/patterns/contrib.mdx b/docs/patterns/contrib.mdx index 920b248bf..aead6affd 100644 --- a/docs/patterns/contrib.mdx +++ b/docs/patterns/contrib.mdx @@ -4,6 +4,9 @@ description: "Community-contributed modules extending FastMCP" icon: "cubes" --- +import { VersionBadge } from "/snippets/version-badge.mdx" + + 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. diff --git a/docs/servers/fastmcp.mdx b/docs/servers/fastmcp.mdx index 745d56bdf..9294ddb2a 100644 --- a/docs/servers/fastmcp.mdx +++ b/docs/servers/fastmcp.mdx @@ -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 + + 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 + + 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. diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdx index 2f71cb74c..b9a6b520c 100644 --- a/docs/servers/prompts.mdx +++ b/docs/servers/prompts.mdx @@ -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? @@ -201,6 +203,8 @@ Refer to the [Context documentation](/servers/context) for more details on these ### Duplicate Prompts + + 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 diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 9e13b98bd..4db09f209 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -397,6 +397,8 @@ This allows accessing the same template implementation through different URI pat ### Duplicate Resources + + 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 diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 7839efa89..7d4fdbf50 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -311,6 +311,8 @@ For full documentation on the Context object and all its capabilities, see the [ ### Duplicate Tools + + 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 diff --git a/docs/snippets/version-badge.mdx b/docs/snippets/version-badge.mdx index a5021de94..d8ef3dd95 100644 --- a/docs/snippets/version-badge.mdx +++ b/docs/snippets/version-badge.mdx @@ -1,8 +1,13 @@ export const VersionBadge = ({ version }) => { return ( - - - New in version {version} - + +
+ New in version:  + {version} +
+
+ + + ); }; \ No newline at end of file diff --git a/docs/style.css b/docs/style.css index f6bb832bc..be64b3edd 100644 --- a/docs/style.css +++ b/docs/style.css @@ -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; -} From 1e3378373fce50fe2ee3aa761bf4fa32c6de0d5a Mon Sep 17 00:00:00 2001 From: TechWIthTy <37724661+TechWithTy@users.noreply.github.com> Date: Thu, 24 Apr 2025 20:07:32 -0600 Subject: [PATCH 08/32] Update README.md Grammar error --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0b83eb75..31275b4c1 100644 --- a/README.md +++ b/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 From c8dface36ae6b006f16049fb09f5510eb8d31a28 Mon Sep 17 00:00:00 2001 From: cutekibry Date: Fri, 25 Apr 2025 15:24:12 +0800 Subject: [PATCH 09/32] fix: unintended type convert The function tries to convert `str`` into `dict` without validate if it is suitable for the type annotation. This will cause unintended type converting. Refs: #251 --- src/fastmcp/utilities/func_metadata.py | 20 +++++++-- tests/utilities/test_func_metadata.py | 56 ++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/src/fastmcp/utilities/func_metadata.py b/src/fastmcp/utilities/func_metadata.py index 777e7d744..138cb4389 100644 --- a/src/fastmcp/utilities/func_metadata.py +++ b/src/fastmcp/utilities/func_metadata.py @@ -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 diff --git a/tests/utilities/test_func_metadata.py b/tests/utilities/test_func_metadata.py index 96d8c6f3b..cc4b013b1 100644 --- a/tests/utilities/test_func_metadata.py +++ b/tests/utilities/test_func_metadata.py @@ -174,6 +174,62 @@ 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_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""" From b6ef8d234605885c29141e6e1e59fee98a3219c9 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 10:27:26 -0400 Subject: [PATCH 10/32] Add test for missing annotation --- tests/utilities/test_func_metadata.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/utilities/test_func_metadata.py b/tests/utilities/test_func_metadata.py index cc4b013b1..9beb27e6c 100644 --- a/tests/utilities/test_func_metadata.py +++ b/tests/utilities/test_func_metadata.py @@ -187,6 +187,18 @@ def test_keep_str_as_str(): 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""" From 048671b088336dd10f95d65306198993559ede18 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 11:19:42 -0400 Subject: [PATCH 11/32] Allow customization of inspector proxy port, ui port, and version --- src/fastmcp/cli/cli.py | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/fastmcp/cli/cli.py b/src/fastmcp/cli/cli.py index 379059d7e..cb4c112ab 100644 --- a/src/fastmcp/cli/cli.py +++ b/src/fastmcp/cli/cli.py @@ -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: From 63d8b1b7239eb13850094375c183d7da4dd48faa Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 12:22:30 -0400 Subject: [PATCH 12/32] Ensure openapi resources return valid responses --- src/fastmcp/server/openapi.py | 35 +++---- tests/server/test_openapi.py | 192 ++++++++++++++++++++++++---------- 2 files changed, 152 insertions(+), 75 deletions(-) diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.py index bc65c2ff7..82cde553c 100644 --- a/src/fastmcp/server/openapi.py +++ b/src/fastmcp/server/openapi.py @@ -257,7 +257,7 @@ class OpenAPIResource(Resource): self._client = client self._route = route - async def read(self) -> str: + async def read(self) -> str | bytes: """Fetch the resource data by making an HTTP request.""" try: # Extract path parameters from the URI if present @@ -297,15 +297,15 @@ 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: + return str(response.json()) + 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) @@ -367,18 +367,15 @@ class OpenAPIResourceTemplate(ResourceTemplate): # 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() + # Determine content type and return appropriate format + content_type = response.headers.get("content-type", "").lower() - # Return the appropriate data - if mime_type == "application/json": - try: - return response.json() - except (json.JSONDecodeError, ValueError): - return response.text - else: + if "application/json" in content_type: + return str(response.json()) + elif any(ct in content_type for ct in ["text/", "application/xml"]): return response.text + else: + return response.content except httpx.HTTPStatusError as e: error_message = ( diff --git a/tests/server/test_openapi.py b/tests/server/test_openapi.py index afad3b669..c7839920c 100644 --- a/tests/server/test_openapi.py +++ b/tests/server/test_openapi.py @@ -1,12 +1,13 @@ +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 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 +67,17 @@ def fastapi_app(users_db: dict[int, User]) -> FastAPI: user.name = name return user + @app.get("/ping") + 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 +132,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 +169,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 +187,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 +202,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 +221,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 +236,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 +251,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 +300,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 +319,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 +337,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 +552,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 +576,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 +732,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 +756,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 +805,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 +815,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 +826,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 From 57cb110338f7d3101bf0dfa924d05681c13c2ab1 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 12:35:07 -0400 Subject: [PATCH 13/32] Fix issues with simple str response --- src/fastmcp/server/openapi.py | 53 ++++------------------------------- tests/server/test_openapi.py | 3 +- 2 files changed, 7 insertions(+), 49 deletions(-) diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.py index 82cde553c..0911cae8a 100644 --- a/src/fastmcp/server/openapi.py +++ b/src/fastmcp/server/openapi.py @@ -301,7 +301,8 @@ class OpenAPIResource(Resource): content_type = response.headers.get("content-type", "").lower() if "application/json" in content_type: - return str(response.json()) + result = response.json() + return json.dumps(result) elif any(ct in content_type for ct in ["text/", "application/xml"]): return response.text else: @@ -343,56 +344,13 @@ class OpenAPIResourceTemplate(ResourceTemplate): uri_template=uri_template, name=name, description=description, - fn=self._create_resource_fn, + fn=lambda **kwargs: None, parameters=parameters, tags=tags, ) 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 content type and return appropriate format - content_type = response.headers.get("content-type", "").lower() - - if "application/json" in content_type: - return str(response.json()) - elif any(ct in content_type for ct in ["text/", "application/xml"]): - return response.text - else: - return response.content - - 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: """Create a resource with the given parameters.""" # Generate a URI for this resource instance @@ -406,9 +364,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 []), ) diff --git a/tests/server/test_openapi.py b/tests/server/test_openapi.py index c7839920c..8b6e828d7 100644 --- a/tests/server/test_openapi.py +++ b/tests/server/test_openapi.py @@ -6,6 +6,7 @@ import httpx import pytest from dirty_equals import IsStr from fastapi import FastAPI, HTTPException, Response +from fastapi.responses import PlainTextResponse from httpx import ASGITransport, AsyncClient from mcp.types import BlobResourceContents, TextContent, TextResourceContents from pydantic import BaseModel, TypeAdapter @@ -67,7 +68,7 @@ def fastapi_app(users_db: dict[int, User]) -> FastAPI: user.name = name return user - @app.get("/ping") + @app.get("/ping", response_class=PlainTextResponse) async def ping() -> str: """Ping the server.""" return "pong" From d73e87b0534d0928e7be62e56e74d8923031c8c8 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 12:55:32 -0400 Subject: [PATCH 14/32] Add resource template tests --- tests/resources/test_resource_template.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py index 38b2f45f9..33db36cd4 100644 --- a/tests/resources/test_resource_template.py +++ b/tests/resources/test_resource_template.py @@ -443,3 +443,20 @@ class TestMatchUriTemplate: 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 From 713864aa9a8cdb39295262bce73db0acd2b79447 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 14:25:17 -0400 Subject: [PATCH 15/32] Ensure servers expose template wildcards --- src/fastmcp/resources/template.py | 2 +- tests/resources/test_resource_template.py | 60 +++++++++++++++++++ tests/server/test_server.py | 73 +++++++++++++++++++++++ 3 files changed, 134 insertions(+), 1 deletion(-) diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py index d174365f3..0d804f3da 100644 --- a/src/fastmcp/resources/template.py +++ b/src/fastmcp/resources/template.py @@ -95,7 +95,7 @@ class ResourceTemplate(BaseModel): raise ValueError("You must provide a name for lambda functions") # 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") diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py index 33db36cd4..86fd24df4 100644 --- a/tests/resources/test_resource_template.py +++ b/tests/resources/test_resource_template.py @@ -297,6 +297,66 @@ 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.""" diff --git a/tests/server/test_server.py b/tests/server/test_server.py index 42a47ae65..f27e0c042 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -531,6 +531,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): @@ -1143,6 +1155,67 @@ class TestServerResourceTemplates: 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}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://test/data")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource: test/data" + + async def test_templates_match_in_order_of_definition(self): + """ + If a wildcard template is defined first, it will take priority over another + matching template. + + """ + mcp = FastMCP() + + @mcp.resource("resource://{param*}") + def template_resource(param: str) -> str: + return f"Template resource 1: {param}" + + @mcp.resource("resource://{x}/{y}") + def template_resource_with_params(x: str, y: str) -> str: + return f"Template resource 2: {x}/{y}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://a/b/c")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b/c" + + result = await client.read_resource(AnyUrl("resource://a/b")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b" + + async def test_templates_shadow_each_other_reorder(self): + """ + If a wildcard template is defined second, it will *not* take priority over + another matching template. + """ + mcp = FastMCP() + + @mcp.resource("resource://{x}/{y}") + def template_resource_with_params(x: str, y: str) -> str: + return f"Template resource 1: {x}/{y}" + + @mcp.resource("resource://{param*}") + def template_resource(param: str) -> str: + return f"Template resource 2: {param}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://a/b/c")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 2: a/b/c" + + result = await client.read_resource(AnyUrl("resource://a/b")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b" + class TestContextInjection: """Test context injection in tools.""" From 4e650dedf569d4fc248805eed7e95763f78e370c Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 14:34:56 -0400 Subject: [PATCH 16/32] Update resources.mdx --- docs/servers/resources.mdx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 4db09f209..573379593 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -251,13 +251,18 @@ With these two templates defined, clients can request a variety of resources: + +Please note: the Model Context Protocol URI standard follows RFC 6570, which does not include support for wildcard parameters. FastMCP extends the template syntax to support wildcards (`{param*}`), and because template matching happens entirely in the FastMCP server, it is not expected that these wildcards will cause compatibility issues with other MCP implementations. However, this can not be guaranteed. + + 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 +```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: @@ -265,6 +270,7 @@ def get_file(filename: str) -> str: # Will only match files:// return f"File content for: {filename}" + # Wildcard parameter can match multiple segments @mcp.resource("path://{filepath*}") def get_path_content(filepath: str) -> str: @@ -272,6 +278,7 @@ def get_path_content(filepath: str) -> str: # 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: From d71ae13a2d32550577081f5e8ba15b0bd4ef2548 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 15:52:23 -0400 Subject: [PATCH 17/32] Update wildcards to 2.2.4 --- docs/servers/resources.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 573379593..d5ef7e050 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -249,7 +249,7 @@ With these two templates defined, clients can request a variety of resources: ### Wildcard Parameters - + Please note: the Model Context Protocol URI standard follows RFC 6570, which does not include support for wildcard parameters. FastMCP extends the template syntax to support wildcards (`{param*}`), and because template matching happens entirely in the FastMCP server, it is not expected that these wildcards will cause compatibility issues with other MCP implementations. However, this can not be guaranteed. From 466c1a42f7dda8ac77d0702e79b06fd00f1f3f08 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 16:12:23 -0400 Subject: [PATCH 18/32] Update note --- docs/servers/resources.mdx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index d5ef7e050..447e854f5 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -251,9 +251,10 @@ With these two templates defined, clients can request a variety of resources: - -Please note: the Model Context Protocol URI standard follows RFC 6570, which does not include support for wildcard parameters. FastMCP extends the template syntax to support wildcards (`{param*}`), and because template matching happens entirely in the FastMCP server, it is not expected that these wildcards will cause compatibility issues with other MCP implementations. However, this can not be guaranteed. - + +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. + + 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. From 09cf6550b5dab7208bf334d4637dbefac9fc879f Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 17:49:42 -0400 Subject: [PATCH 19/32] Split server interaction tests into new file --- tests/server/test_server.py | 840 +--------------------- tests/server/test_server_interactions.py | 851 +++++++++++++++++++++++ 2 files changed, 853 insertions(+), 838 deletions(-) create mode 100644 tests/server/test_server_interactions.py diff --git a/tests/server/test_server.py b/tests/server/test_server.py index f27e0c042..7c4782eba 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -1,25 +1,11 @@ -import base64 -import json -from pathlib import Path -from typing import TYPE_CHECKING - import pytest from mcp.types import ( - BlobResourceContents, - ImageContent, TextContent, TextResourceContents, ) -from pydantic import AnyUrl, 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: @@ -715,825 +701,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"} - - 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}" - - async with Client(mcp) as client: - result = await client.read_resource(AnyUrl("resource://test/data")) - assert isinstance(result[0], TextResourceContents) - assert result[0].text == "Template resource: test/data" - - async def test_templates_match_in_order_of_definition(self): - """ - If a wildcard template is defined first, it will take priority over another - matching template. - - """ - mcp = FastMCP() - - @mcp.resource("resource://{param*}") - def template_resource(param: str) -> str: - return f"Template resource 1: {param}" - - @mcp.resource("resource://{x}/{y}") - def template_resource_with_params(x: str, y: str) -> str: - return f"Template resource 2: {x}/{y}" - - async with Client(mcp) as client: - result = await client.read_resource(AnyUrl("resource://a/b/c")) - assert isinstance(result[0], TextResourceContents) - assert result[0].text == "Template resource 1: a/b/c" - - result = await client.read_resource(AnyUrl("resource://a/b")) - assert isinstance(result[0], TextResourceContents) - assert result[0].text == "Template resource 1: a/b" - - async def test_templates_shadow_each_other_reorder(self): - """ - If a wildcard template is defined second, it will *not* take priority over - another matching template. - """ - mcp = FastMCP() - - @mcp.resource("resource://{x}/{y}") - def template_resource_with_params(x: str, y: str) -> str: - return f"Template resource 1: {x}/{y}" - - @mcp.resource("resource://{param*}") - def template_resource(param: str) -> str: - return f"Template resource 2: {param}" - - async with Client(mcp) as client: - result = await client.read_resource(AnyUrl("resource://a/b/c")) - assert isinstance(result[0], TextResourceContents) - assert result[0].text == "Template resource 2: a/b/c" - - result = await client.read_resource(AnyUrl("resource://a/b")) - assert isinstance(result[0], TextResourceContents) - assert result[0].text == "Template resource 1: a/b" - - -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"} diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py new file mode 100644 index 000000000..6ac501787 --- /dev/null +++ b/tests/server/test_server_interactions.py @@ -0,0 +1,851 @@ +import base64 +import json +from pathlib import Path + +import pytest +from mcp.types import ( + BlobResourceContents, + ImageContent, + TextContent, + TextResourceContents, +) +from pydantic import AnyUrl, Field + +from fastmcp import Client, Context, FastMCP +from fastmcp.exceptions import ClientError +from fastmcp.prompts.prompt import EmbeddedResource, Message, UserMessage +from fastmcp.resources import FileResource, FunctionResource +from fastmcp.utilities.types import Image + + +@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 TestTools: + async def test_add_tool_exists(self, tool_server: FastMCP): + async with Client(tool_server) as client: + tools = await client.list_tools() + assert "add" in [t.name for t in tools] + + async def test_list_tools(self, tool_server: FastMCP): + async with Client(tool_server) as client: + assert len(await client.list_tools()) == 6 + + async def test_call_tool(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_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): + 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(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): + async with Client(tool_server) as client: + result = await client.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") + + async with Client(tool_server) as client: + result = await client.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): + async with Client(tool_server) as client: + result = await client.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") + + async with Client(tool_server) as client: + result = await client.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}" + + async with Client(mcp) as client: + tools = await client.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 TestResources: + 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 TestResourceTemplates: + 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 + result2 = await client.read_resource(AnyUrl("math://add/7")) + assert isinstance(result2[0], TextResourceContents) + assert result2[0].text == "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 + 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_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"} + + 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}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://test/data")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource: test/data" + + async def test_templates_match_in_order_of_definition(self): + """ + If a wildcard template is defined first, it will take priority over another + matching template. + + """ + mcp = FastMCP() + + @mcp.resource("resource://{param*}") + def template_resource(param: str) -> str: + return f"Template resource 1: {param}" + + @mcp.resource("resource://{x}/{y}") + def template_resource_with_params(x: str, y: str) -> str: + return f"Template resource 2: {x}/{y}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://a/b/c")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b/c" + + result = await client.read_resource(AnyUrl("resource://a/b")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b" + + async def test_templates_shadow_each_other_reorder(self): + """ + If a wildcard template is defined second, it will *not* take priority over + another matching template. + """ + mcp = FastMCP() + + @mcp.resource("resource://{x}/{y}") + def template_resource_with_params(x: str, y: str) -> str: + return f"Template resource 1: {x}/{y}" + + @mcp.resource("resource://{param*}") + def template_resource(param: str) -> str: + return f"Template resource 2: {param}" + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://a/b/c")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 2: a/b/c" + + result = await client.read_resource(AnyUrl("resource://a/b")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Template resource 1: a/b" + + +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}" + + mcp.add_tool(tool_with_context) + async with Client(mcp) as client: + tools = await client.list_tools() + assert len(tools) == 1 + assert tools[0].name == "tool_with_context" + + 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 + + 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 tool exists + async with Client(mcp) as client: + tools = await client.list_tools() + assert len(tools) == 1 + # Note: MCPTool from the client API doesn't expose tags + + +class TestPrompts: + """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_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"} From 3f793d541cdba5c31f6aed6537c9a0bc6d4d6e74 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 18:32:24 -0400 Subject: [PATCH 20/32] minor docs updates --- docs/servers/context.mdx | 2 +- docs/servers/prompts.mdx | 2 +- docs/servers/resources.mdx | 6 +++--- docs/servers/tools.mdx | 2 +- tests/server/test_server_interactions.py | 15 +++++++++++++++ 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx index e6ce5a56f..685b833b0 100644 --- a/docs/servers/context.mdx +++ b/docs/servers/context.mdx @@ -19,7 +19,7 @@ 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. diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdx index b9a6b520c..5668846f4 100644 --- a/docs/servers/prompts.mdx +++ b/docs/servers/prompts.mdx @@ -20,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 diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 447e854f5..6b1fe6bd2 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -1,6 +1,6 @@ --- title: Resources & Templates -sidebarTitle: Resources & Templates +sidebarTitle: Resources description: Expose data sources and dynamic content generators to your MCP client. icon: database --- @@ -21,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 @@ -201,7 +201,7 @@ 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. diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 7d4fdbf50..6eded291f 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -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 diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index 6ac501787..a02afd533 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -180,6 +180,21 @@ class TestTools: assert "title" in properties assert properties["title"]["description"] == "Optional title" + async def test_tool_with_bytes_input(self): + mcp = FastMCP() + + @mcp.tool() + def process_image(image: bytes) -> Image: + return Image(data=image) + + async with Client(mcp) as client: + result = await client.call_tool( + "process_image", {"image": b"fake png data"} + ) + assert isinstance(result[0], ImageContent) + assert result[0].mimeType == "image/png" + assert result[0].data == base64.b64encode(b"fake png data").decode() + class TestResources: async def test_text_resource(self): From 8a4aa707a3c6861af8e03adf444be823d232219e Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 18:41:14 -0400 Subject: [PATCH 21/32] Update tools.mdx --- docs/servers/tools.mdx | 105 ++++++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 39 deletions(-) diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 6eded291f..44c2eafde 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -44,44 +44,31 @@ 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:** +#### Supported Types + +FastMCP supports a wide range of type annotations: | Type Annotation | Example | Description | | :---------------------- | :---------------------------- | :---------------------------------- | @@ -90,30 +77,70 @@ def process_data( | 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) | +| Pydantic models | `UserData` | Complex structured data (see Structured Inputs) | **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. -### Required vs. Optional Parameters +#### Parameter Metadata -Parameters in your function signature are considered **required** unless they have a default value. +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 + +#### Optional Arguments + +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. +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. ### Structured Inputs From 5f1e1dea5b63c1836793494606a279d746978824 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 19:05:20 -0400 Subject: [PATCH 22/32] update tool docs --- docs/servers/tools.mdx | 230 +++++++++++++++++------ tests/server/test_server_interactions.py | 14 ++ 2 files changed, 187 insertions(+), 57 deletions(-) diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 44c2eafde..888593f33 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -66,23 +66,6 @@ def analyze_text( # Implementation... ``` -#### Supported Types - -FastMCP supports a wide range of type annotations: - -| 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 Structured Inputs) | - - -**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. - - #### 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: @@ -124,6 +107,20 @@ Field provides several validation and documentation features: - `pattern`: Regex pattern for string validation - `default`: Default value if parameter is omitted +#### Supported Types + +FastMCP supports a wide range of type annotations: + +| Type Annotation | Example | Description | +| :---------------------- | :---------------------------- | :---------------------------------- | +| Basic types | `int`, `float`, `str`, `bool` | Simple scalar values - see [Built-in Types](#built-in-types) | +| Binary data | `bytes` | Binary content - see [Binary Data Handling](#binary-data-handling) | +| 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) | +| Literal types | `Literal["A", "B"]` | Parameters with specific allowed values - see [Literal Types](#literal-types) | +| Pydantic models | `UserData` | Complex structured data - see [Pydantic Models](#pydantic-models) | + #### Optional Arguments FastMCP follows Python's standard function parameter conventions. Parameters without default values are required, while those with default values are optional. @@ -142,44 +139,6 @@ def search_products( 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. -### 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. - ### Metadata While FastMCP infers the name and description from your function, you can override these and add tags using arguments to the `@mcp.tool` decorator: @@ -293,7 +252,7 @@ FastMCP automatically catches exceptions raised within your tool function: Using informative exceptions helps the LLM understand failures and react appropriately. -### Using Context in Tools +### Accessing 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`. @@ -365,4 +324,161 @@ 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. \ No newline at end of file +- `"ignore"`: Keeps the original tool and ignores the new registration attempt. + +## Parameter Types + +FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools. When clients send parameters, FastMCP will attempt to coerce values into the appropriate type when possible (for example, parsing JSON strings into structured types). + +### 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`. + +### Collection Types + +For structured data collections, FastMCP supports standard Python collection types: + +```python +@mcp.tool() +def analyze_data( + values: list[float], # List of numbers + labels: list[str], # List of strings + properties: dict[str, str], # Dictionary with string keys and values + mixed_data: dict[str, list[int]] # Nested collections +): + """Analyze collections of data.""" + # Implementation... +``` + +Collection types can be nested and combined to represent complex data structures. If a client sends a JSON string like `"[1.5, 2.5, 3.5]"` for a `list[float]` parameter, FastMCP will automatically parse and convert it. + +### 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]`. + +### Literal Types + +When a parameter must be one of a predefined 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 specified order and algorithm.""" + # Implementation... +``` + +Literal types help LLMs understand exactly which values are acceptable and provide validation for incoming parameters. + +### Binary Data Handling + +There are two approaches to handling binary data in tool parameters: + +#### Using bytes type + +```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. + +#### Using 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. + +### 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 \ No newline at end of file diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index a02afd533..ac7fffde6 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -195,6 +195,20 @@ class TestTools: assert result[0].mimeType == "image/png" assert result[0].data == base64.b64encode(b"fake png data").decode() + async def test_tool_with_invalid_input(self): + mcp = FastMCP() + + @mcp.tool() + def my_tool(x: int) -> int: + return x + 1 + + async with Client(mcp) as client: + with pytest.raises( + ClientError, + match="Input should be a valid integer, unable to parse string as an integer", + ): + await client.call_tool("my_tool", {"x": "not an int"}) + class TestResources: async def test_text_resource(self): From cd97b1c20133db64424e815f5a6b92ac2edcf66d Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 19:30:43 -0400 Subject: [PATCH 23/32] Document and test input types --- docs/servers/tools.mdx | 141 +++++++++++-- tests/server/test_server.py | 33 +++ tests/server/test_server_interactions.py | 254 ++++++++++++++++++++++- 3 files changed, 414 insertions(+), 14 deletions(-) diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 888593f33..2d75b9688 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -118,9 +118,11 @@ FastMCP supports a wide range of type annotations: | 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) | -| Literal types | `Literal["A", "B"]` | Parameters with specific allowed values - see [Literal Types](#literal-types) | +| Constrained types | `Literal["A", "B"]`, `Enum` | Parameters with specific allowed values - see [Constrained Types](#constrained-types) | | Pydantic models | `UserData` | Complex structured data - see [Pydantic Models](#pydantic-models) | +For additional type annotations not listed here, see the [Parameter Types](#parameter-types) section below for more detailed information and examples. + #### Optional Arguments FastMCP follows Python's standard function parameter conventions. Parameters without default values are required, while those with default values are optional. @@ -198,6 +200,8 @@ FastMCP automatically converts the value returned by your function into the appr - **`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. + ```python from fastmcp import FastMCP, Image import io @@ -328,7 +332,12 @@ The duplicate behavior options are: ## Parameter Types -FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools. When clients send parameters, FastMCP will attempt to coerce values into the appropriate type when possible (for example, parsing JSON strings into structured types). +FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools. + + + +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 @@ -350,21 +359,28 @@ These types provide clear expectations to the LLM about what values are acceptab ### Collection Types -For structured data collections, FastMCP supports standard Python collection types: +FastMCP supports all standard Python collection types: ```python @mcp.tool() def analyze_data( values: list[float], # List of numbers - labels: list[str], # List of strings 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... ``` -Collection types can be nested and combined to represent complex data structures. If a client sends a JSON string like `"[1.5, 2.5, 3.5]"` for a `list[float]` parameter, FastMCP will automatically parse and convert it. +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 @@ -383,9 +399,13 @@ def flexible_search( Modern Python syntax (`str | int`) is preferred over older `Union[str, int]` forms. Similarly, `str | None` is preferred over `Optional[str]`. -### Literal Types +### Constrained Types -When a parameter must be one of a predefined set of values: +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 @@ -396,17 +416,49 @@ def sort_data( order: Literal["ascending", "descending"] = "ascending", algorithm: Literal["quicksort", "mergesort", "heapsort"] = "quicksort" ): - """Sort data using specified order and algorithm.""" + """Sort data using specific options.""" # Implementation... ``` -Literal types help LLMs understand exactly which values are acceptable and provide validation for incoming parameters. +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 -### Binary Data Handling +#### 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: -#### Using bytes type +#### Bytes ```python @mcp.tool() @@ -427,7 +479,7 @@ When you annotate a parameter as `bytes`, FastMCP will: 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. -#### Using base64-encoded strings +#### Base64-encoded strings ```python from typing import Annotated @@ -481,4 +533,67 @@ Using Pydantic models provides: 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 \ No newline at end of file +- 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. diff --git a/tests/server/test_server.py b/tests/server/test_server.py index 7c4782eba..6a80c03ab 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -1,8 +1,11 @@ +from typing import Annotated + import pytest from mcp.types import ( TextContent, TextResourceContents, ) +from pydantic import Field from fastmcp import Client, FastMCP from fastmcp.exceptions import ClientError, NotFoundError @@ -239,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): diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index ac7fffde6..cd56a0b09 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -1,6 +1,8 @@ import base64 import json +from enum import Enum from pathlib import Path +from typing import Annotated, Literal import pytest from mcp.types import ( @@ -157,7 +159,32 @@ class TestTools: assert isinstance(content3, TextContent) assert content3.text == "direct content" - async def test_parameter_descriptions(self): + async def test_parameter_descriptions_with_field_annotations(self): + mcp = FastMCP("Test Server") + + @mcp.tool() + def greet( + name: Annotated[str, Field(description="The name to greet")], + title: Annotated[str, Field(description="Optional title", default="")], + ) -> str: + """A greeting tool""" + return f"Hello {title} {name}" + + async with Client(mcp) as client: + tools = await client.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" + assert properties["title"]["default"] == "" + assert tool.inputSchema["required"] == ["name"] + + async def test_parameter_descriptions_with_field_defaults(self): mcp = FastMCP("Test Server") @mcp.tool() @@ -179,6 +206,8 @@ class TestTools: assert properties["name"]["description"] == "The name to greet" assert "title" in properties assert properties["title"]["description"] == "Optional title" + assert properties["title"]["default"] == "" + assert tool.inputSchema["required"] == ["name"] async def test_tool_with_bytes_input(self): mcp = FastMCP() @@ -209,6 +238,229 @@ class TestTools: ): await client.call_tool("my_tool", {"x": "not an int"}) + async def test_tool_int_coercion(self): + """Test string-to-int type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def add_one(x: int) -> int: + return x + 1 + + async with Client(mcp) as client: + # String with integer value should be coerced to int + result = await client.call_tool("add_one", {"x": "42"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "43" + + async def test_tool_bool_coercion(self): + """Test string-to-bool type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def toggle(flag: bool) -> bool: + return not flag + + async with Client(mcp) as client: + # String with boolean value should be coerced to bool + result = await client.call_tool("toggle", {"flag": "true"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "false" + + result = await client.call_tool("toggle", {"flag": "false"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "true" + + async def test_tool_list_coercion(self): + """Test JSON string to collection type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def process_list(items: list[int]) -> int: + return sum(items) + + async with Client(mcp) as client: + # JSON array string should be coerced to list + result = await client.call_tool( + "process_list", {"items": "[1, 2, 3, 4, 5]"} + ) + assert isinstance(result[0], TextContent) + assert result[0].text == "15" + + async def test_tool_list_coercion_error(self): + """Test that a list coercion error is raised if the input is not a valid list.""" + mcp = FastMCP() + + @mcp.tool() + def process_list(items: list[int]) -> int: + return sum(items) + + async with Client(mcp) as client: + with pytest.raises( + ClientError, + match="Input should be a valid list", + ): + await client.call_tool("process_list", {"items": "['a', 'b', 3]"}) + + async def test_tool_dict_coercion(self): + """Test JSON string to dict type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def process_dict(data: dict[str, int]) -> int: + return sum(data.values()) + + async with Client(mcp) as client: + # JSON object string should be coerced to dict + result = await client.call_tool( + "process_dict", {"data": '{"a": 1, "b": "2", "c": 3}'} + ) + assert isinstance(result[0], TextContent) + assert result[0].text == "6" + + async def test_tool_set_coercion(self): + """Test JSON string to set type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def process_set(items: set[int]) -> int: + assert isinstance(items, set) + return sum(items) + + async with Client(mcp) as client: + result = await client.call_tool("process_set", {"items": "[1, 2, 3, 4, 5]"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "15" + + async def test_tool_tuple_coercion(self): + """Test JSON string to tuple type coercion.""" + mcp = FastMCP() + + @mcp.tool() + def process_tuple(items: tuple[int, str]) -> int: + assert isinstance(items, tuple) + return items[0] + len(items[1]) + + async with Client(mcp) as client: + result = await client.call_tool("process_tuple", {"items": '["1", "two"]'}) + assert isinstance(result[0], TextContent) + assert result[0].text == "4" + + async def test_annotated_field_validation(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: Annotated[int, Field(ge=1)]) -> None: + pass + + async with Client(mcp) as client: + with pytest.raises( + ClientError, + match="Input should be greater than or equal to 1", + ): + await client.call_tool("analyze", {"x": 0}) + + async def test_default_field_validation(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: int = Field(ge=1)) -> None: + pass + + async with Client(mcp) as client: + with pytest.raises( + ClientError, + match="Input should be greater than or equal to 1", + ): + await client.call_tool("analyze", {"x": 0}) + + async def test_default_field_is_still_required_if_no_default_specified(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: int = Field()) -> None: + pass + + async with Client(mcp) as client: + with pytest.raises(ClientError, match="Field required"): + await client.call_tool("analyze", {}) + + async def test_literal_type_validation_error(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: Literal["a", "b"]) -> None: + pass + + async with Client(mcp) as client: + with pytest.raises(ClientError, match="Input should be 'a' or 'b'"): + await client.call_tool("analyze", {"x": "c"}) + + async def test_literal_type_validation_success(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: Literal["a", "b"]) -> str: + return x + + async with Client(mcp) as client: + result = await client.call_tool("analyze", {"x": "a"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "a" + + async def test_enum_type_validation_error(self): + mcp = FastMCP() + + class MyEnum(Enum): + RED = "red" + GREEN = "green" + BLUE = "blue" + + @mcp.tool() + def analyze(x: MyEnum) -> str: + return x.value + + async with Client(mcp) as client: + with pytest.raises( + ClientError, match="Input should be 'red', 'green' or 'blue'" + ): + await client.call_tool("analyze", {"x": "some-color"}) + + async def test_enum_type_validation_success(self): + mcp = FastMCP() + + class MyEnum(Enum): + RED = "red" + GREEN = "green" + BLUE = "blue" + + @mcp.tool() + def analyze(x: MyEnum) -> str: + return x.value + + async with Client(mcp) as client: + result = await client.call_tool("analyze", {"x": "red"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "red" + + async def test_union_type_validation(self): + mcp = FastMCP() + + @mcp.tool() + def analyze(x: int | float) -> str: + return str(x) + + async with Client(mcp) as client: + result = await client.call_tool("analyze", {"x": 1}) + assert isinstance(result[0], TextContent) + assert result[0].text == "1" + + result = await client.call_tool("analyze", {"x": 1.0}) + assert isinstance(result[0], TextContent) + assert result[0].text == "1.0" + + with pytest.raises(ClientError, match="2 validation errors for analyze"): + await client.call_tool("analyze", {"x": "not a number"}) + class TestResources: async def test_text_resource(self): From 882a10a5e3947ba797ef7a4f387c8066f01f21f6 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 19:48:23 -0400 Subject: [PATCH 24/32] Update docs and tests --- docs/servers/tools.mdx | 70 ++++++++++- tests/server/test_server_interactions.py | 143 +++++++++++++++++++++++ 2 files changed, 209 insertions(+), 4 deletions(-) diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 2d75b9688..71c24dfbe 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -109,16 +109,19 @@ Field provides several validation and documentation features: #### Supported Types -FastMCP supports a wide range of type annotations: +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 - see [Built-in Types](#built-in-types) | -| Binary data | `bytes` | Binary content - see [Binary Data Handling](#binary-data-handling) | +| 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) | For additional type annotations not listed here, see the [Parameter Types](#parameter-types) section below for more detailed information and examples. @@ -334,11 +337,10 @@ The duplicate behavior options are: 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: @@ -357,6 +359,32 @@ def process_values( 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: @@ -502,6 +530,40 @@ def process_image_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: diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index cd56a0b09..3144f710b 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -1,5 +1,7 @@ import base64 +import datetime import json +import uuid from enum import Enum from pathlib import Path from typing import Annotated, Literal @@ -159,6 +161,8 @@ class TestTools: assert isinstance(content3, TextContent) assert content3.text == "direct content" + +class TestToolParameters: async def test_parameter_descriptions_with_field_annotations(self): mcp = FastMCP("Test Server") @@ -461,6 +465,145 @@ class TestTools: with pytest.raises(ClientError, match="2 validation errors for analyze"): await client.call_tool("analyze", {"x": "not a number"}) + async def test_path_type(self): + mcp = FastMCP() + + @mcp.tool() + def send_path(path: Path) -> str: + assert isinstance(path, Path) + return str(path) + + async with Client(mcp) as client: + result = await client.call_tool("send_path", {"path": "/tmp/test.txt"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "/tmp/test.txt" + + async def test_path_type_error(self): + mcp = FastMCP() + + @mcp.tool() + def send_path(path: Path) -> str: + return str(path) + + async with Client(mcp) as client: + with pytest.raises(ClientError, match="Input is not a valid path"): + await client.call_tool("send_path", {"path": 1}) + + async def test_uuid_type(self): + mcp = FastMCP() + + @mcp.tool() + def send_uuid(x: uuid.UUID) -> str: + assert isinstance(x, uuid.UUID) + return str(x) + + test_uuid = uuid.uuid4() + + async with Client(mcp) as client: + result = await client.call_tool("send_uuid", {"x": test_uuid}) + assert isinstance(result[0], TextContent) + assert result[0].text == str(test_uuid) + + async def test_uuid_type_error(self): + mcp = FastMCP() + + @mcp.tool() + def send_uuid(x: uuid.UUID) -> str: + return str(x) + + async with Client(mcp) as client: + with pytest.raises(ClientError, match="Input should be a valid UUID"): + await client.call_tool("send_uuid", {"x": "not a uuid"}) + + async def test_datetime_type(self): + mcp = FastMCP() + + @mcp.tool() + def send_datetime(x: datetime.datetime) -> str: + return x.isoformat() + + async with Client(mcp) as client: + result = await client.call_tool( + "send_datetime", {"x": datetime.datetime.now()} + ) + assert isinstance(result[0], TextContent) + assert result[0].text == datetime.datetime.now().isoformat() + + async def test_datetime_type_parse_string(self): + mcp = FastMCP() + + @mcp.tool() + def send_datetime(x: datetime.datetime) -> str: + return x.isoformat() + + async with Client(mcp) as client: + result = await client.call_tool( + "send_datetime", {"x": "2021-01-01T00:00:00"} + ) + assert isinstance(result[0], TextContent) + assert result[0].text == "2021-01-01T00:00:00" + + async def test_datetime_type_error(self): + mcp = FastMCP() + + @mcp.tool() + def send_datetime(x: datetime.datetime) -> str: + return x.isoformat() + + async with Client(mcp) as client: + with pytest.raises(ClientError, match="Input should be a valid datetime"): + await client.call_tool("send_datetime", {"x": "not a datetime"}) + + async def test_date_type(self): + mcp = FastMCP() + + @mcp.tool() + def send_date(x: datetime.date) -> str: + return x.isoformat() + + async with Client(mcp) as client: + result = await client.call_tool("send_date", {"x": datetime.date.today()}) + assert isinstance(result[0], TextContent) + assert result[0].text == datetime.date.today().isoformat() + + async def test_date_type_parse_string(self): + mcp = FastMCP() + + @mcp.tool() + def send_date(x: datetime.date) -> str: + return x.isoformat() + + async with Client(mcp) as client: + result = await client.call_tool("send_date", {"x": "2021-01-01"}) + assert isinstance(result[0], TextContent) + assert result[0].text == "2021-01-01" + + async def test_timedelta_type(self): + mcp = FastMCP() + + @mcp.tool() + def send_timedelta(x: datetime.timedelta) -> str: + return str(x) + + async with Client(mcp) as client: + result = await client.call_tool( + "send_timedelta", {"x": datetime.timedelta(days=1)} + ) + assert isinstance(result[0], TextContent) + assert result[0].text == "1 day, 0:00:00" + + async def test_timedelta_type_parse_int(self): + mcp = FastMCP() + + @mcp.tool() + def send_timedelta(x: datetime.timedelta) -> str: + return str(x) + + async with Client(mcp) as client: + result = await client.call_tool("send_timedelta", {"x": 1000}) + assert isinstance(result[0], TextContent) + assert result[0].text == "0:16:40" + class TestResources: async def test_text_resource(self): From 8205e1eefb647c865296a8888fd31dd0ee8c911c Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 19:51:16 -0400 Subject: [PATCH 25/32] Improve datetime test to avoid now --- tests/server/test_server_interactions.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index 3144f710b..9f588a475 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -522,12 +522,12 @@ class TestToolParameters: def send_datetime(x: datetime.datetime) -> str: return x.isoformat() + dt = datetime.datetime(2025, 4, 25, 1, 2, 3) + async with Client(mcp) as client: - result = await client.call_tool( - "send_datetime", {"x": datetime.datetime.now()} - ) + result = await client.call_tool("send_datetime", {"x": dt}) assert isinstance(result[0], TextContent) - assert result[0].text == datetime.datetime.now().isoformat() + assert result[0].text == dt.isoformat() async def test_datetime_type_parse_string(self): mcp = FastMCP() From f87617e2280d11f79fb3c4efd5545137b1a3b17c Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:01:51 -0400 Subject: [PATCH 26/32] Fix issues with type conversion --- src/fastmcp/tools/tool.py | 15 ++++- tests/server/test_server_interactions.py | 78 +++++++++++++++++++++++- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py index e4af4749a..4b8ccee84 100644 --- a/src/fastmcp/tools/tool.py +++ b/src/fastmcp/tools/tool.py @@ -163,9 +163,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) diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index 9f588a475..153b58608 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -106,12 +106,86 @@ class TestTools: assert isinstance(result[0], TextContent) assert result[0].text == '["x", 2]' - async def test_tool_image_helper(self, tool_server: FastMCP, tmp_path: Path): + +class TestToolReturnTypes: + async def test_string(self): + mcp = FastMCP() + + @mcp.tool() + def string_tool() -> str: + return "Hello, world!" + + async with Client(mcp) as client: + result = await client.call_tool("string_tool", {}) + assert isinstance(result[0], TextContent) + assert result[0].text == "Hello, world!" + + async def test_bytes(self, tmp_path: Path): + mcp = FastMCP() + + @mcp.tool() + def bytes_tool() -> bytes: + return b"Hello, world!" + + async with Client(mcp) as client: + result = await client.call_tool("bytes_tool", {}) + assert isinstance(result[0], TextContent) + assert result[0].text == "Hello, world!" + + async def test_uuid(self): + mcp = FastMCP() + + test_uuid = uuid.uuid4() + + @mcp.tool() + def uuid_tool() -> uuid.UUID: + return test_uuid + + async with Client(mcp) as client: + result = await client.call_tool("uuid_tool", {}) + assert isinstance(result[0], TextContent) + assert result[0].text == str(test_uuid) + + async def test_path(self): + mcp = FastMCP() + + test_path = Path("/tmp/test.txt") + + @mcp.tool() + def path_tool() -> Path: + return test_path + + async with Client(mcp) as client: + result = await client.call_tool("path_tool", {}) + assert isinstance(result[0], TextContent) + assert result[0].text == str(test_path) + + async def test_datetime(self): + mcp = FastMCP() + + dt = datetime.datetime(2025, 4, 25, 1, 2, 3) + + @mcp.tool() + def datetime_tool() -> datetime.datetime: + return dt + + async with Client(mcp) as client: + result = await client.call_tool("datetime_tool", {}) + assert isinstance(result[0], TextContent) + assert result[0].text == dt.isoformat() + + async def test_image(self, tmp_path: Path): + mcp = FastMCP() + + @mcp.tool() + def image_tool(path: str) -> Image: + return Image(path) + # Create a test image image_path = tmp_path / "test.png" image_path.write_bytes(b"fake png data") - async with Client(tool_server) as client: + async with Client(mcp) as client: result = await client.call_tool("image_tool", {"path": str(image_path)}) content = result[0] assert isinstance(content, ImageContent) From b62f005307d7c022dddabd9c41755c73a84b118e Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:02:46 -0400 Subject: [PATCH 27/32] Update tools.mdx --- docs/servers/tools.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 71c24dfbe..2c4fb7370 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -205,6 +205,10 @@ FastMCP automatically converts the value returned by your function into the appr FastMCP will attempt to serialize other types to a string if possible. + +At this time, FastMCP responds only to your tool's return *value*, not its return *annotation*. + + ```python from fastmcp import FastMCP, Image import io From 702bc68a4c026736306026e2c41cb037171f45c3 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:05:04 -0400 Subject: [PATCH 28/32] platform independent path --- tests/server/test_server_interactions.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index 9f588a475..94f7ebdd0 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -473,10 +473,13 @@ class TestToolParameters: assert isinstance(path, Path) return str(path) + # Use a platform-independent path + test_path = Path("tmp") / "test.txt" + async with Client(mcp) as client: - result = await client.call_tool("send_path", {"path": "/tmp/test.txt"}) + result = await client.call_tool("send_path", {"path": str(test_path)}) assert isinstance(result[0], TextContent) - assert result[0].text == "/tmp/test.txt" + assert result[0].text == str(test_path) async def test_path_type_error(self): mcp = FastMCP() From 0889c07f2723b504aeb1b80c93ce877963825e8d Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:23:33 -0400 Subject: [PATCH 29/32] Clean up tool call --- src/fastmcp/tools/tool.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py index 4b8ccee84..6f67e20a6 100644 --- a/src/fastmcp/tools/tool.py +++ b/src/fastmcp/tools/tool.py @@ -101,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: From 1480c8771b225a9b96e3e85d13ebf45a8d2829ce Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:33:24 -0400 Subject: [PATCH 30/32] Add context support to all objects --- src/fastmcp/prompts/prompt.py | 47 +++++++++++++++++-- src/fastmcp/prompts/prompt_manager.py | 17 +++++-- src/fastmcp/resources/resource.py | 14 +++++- src/fastmcp/resources/resource_manager.py | 10 +++- src/fastmcp/resources/template.py | 45 ++++++++++++++++-- src/fastmcp/resources/types.py | 36 +++++++++++--- src/fastmcp/server/openapi.py | 18 ++++++- src/fastmcp/server/proxy.py | 57 +++++++++++++++-------- src/fastmcp/server/server.py | 32 ++++++++++++- 9 files changed, 231 insertions(+), 45 deletions(-) diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.py index c6bcefc62..0cf37403d 100644 --- a/src/fastmcp/prompts/prompt.py +++ b/src/fastmcp/prompts/prompt.py @@ -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 == "": 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 diff --git a/src/fastmcp/prompts/prompt_manager.py b/src/fastmcp/prompts/prompt_manager.py index a48ec91b9..db16d4398 100644 --- a/src/fastmcp/prompts/prompt_manager.py +++ b/src/fastmcp/prompts/prompt_manager.py @@ -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.""" diff --git a/src/fastmcp/resources/resource.py b/src/fastmcp/resources/resource.py index b79381bbd..e4d69638d 100644 --- a/src/fastmcp/resources/resource.py +++ b/src/fastmcp/resources/resource.py @@ -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 diff --git a/src/fastmcp/resources/resource_manager.py b/src/fastmcp/resources/resource_manager.py index 613cd728b..1cf42d839 100644 --- a/src/fastmcp/resources/resource_manager.py +++ b/src/fastmcp/resources/resource_manager.py @@ -212,9 +212,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 +234,9 @@ 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, context=context + ) except Exception as e: raise ValueError(f"Error creating resource from template: {e}") diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py index 0d804f3da..41516dd91 100644 --- a/src/fastmcp/resources/template.py +++ b/src/fastmcp/resources/template.py @@ -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,6 +22,12 @@ 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: parts = re.split(r"(\{[^}]+\})", template) @@ -70,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 @@ -88,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 == "": 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)) 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 = { @@ -107,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( @@ -132,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 @@ -153,6 +191,7 @@ class ResourceTemplate(BaseModel): mime_type=self.mime_type, fn=lambda: 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}") diff --git a/src/fastmcp/resources/types.py b/src/fastmcp/resources/types.py index 30d168bee..e86733e8a 100644 --- a/src/fastmcp/resources/types.py +++ b/src/fastmcp/resources/types.py @@ -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 @@ -15,13 +17,21 @@ from pydantic import Field, ValidationInfo 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 +41,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,13 +62,23 @@ 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: + 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() if isinstance(result, bytes): diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.py index 0911cae8a..ae2776af8 100644 --- a/src/fastmcp/server/openapi.py +++ b/src/fastmcp/server/openapi.py @@ -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"] @@ -347,11 +355,17 @@ class OpenAPIResourceTemplate(ResourceTemplate): fn=lambda **kwargs: None, parameters=parameters, tags=tags, + context_kwarg=None, ) self._client = client self._route = route - 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 = [] diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.py index b3d9d8dce..e7cd35d68 100644 --- a/src/fastmcp/server/proxy.py +++ b/src/fastmcp/server/proxy.py @@ -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 diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py index 6f2167410..1ca3b116a 100644 --- a/src/fastmcp/server/server.py +++ b/src/fastmcp/server/server.py @@ -398,7 +398,8 @@ 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() return [ @@ -424,7 +425,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, context=context + ) return GetPromptResult(messages=pydantic_core.to_jsonable_python(messages)) else: for server in self._mounted_servers.values(): @@ -562,6 +566,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. @@ -586,6 +594,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) @@ -639,6 +652,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 @@ -655,6 +672,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) From ef432ade0f240dc273d492a44be5c75e6abf5456 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 20:57:49 -0400 Subject: [PATCH 31/32] Add context injection to all objects --- src/fastmcp/resources/resource_manager.py | 17 +- src/fastmcp/resources/template.py | 2 +- src/fastmcp/resources/types.py | 32 ++- src/fastmcp/server/openapi.py | 4 +- src/fastmcp/server/server.py | 4 +- tests/server/test_server_interactions.py | 316 +++++++++++++--------- 6 files changed, 227 insertions(+), 148 deletions(-) diff --git a/src/fastmcp/resources/resource_manager.py b/src/fastmcp/resources/resource_manager.py index 1cf42d839..d27f6247d 100644 --- a/src/fastmcp/resources/resource_manager.py +++ b/src/fastmcp/resources/resource_manager.py @@ -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) @@ -235,7 +242,9 @@ class ResourceManager: if params := match_uri_template(uri_str, storage_key): try: return await template.create_resource( - uri_str, params, context=context + uri_str, + params=params, + context=context, ) except Exception as e: raise ValueError(f"Error creating resource from template: {e}") diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py index 41516dd91..d0ec24fbd 100644 --- a/src/fastmcp/resources/template.py +++ b/src/fastmcp/resources/template.py @@ -189,7 +189,7 @@ 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, ) diff --git a/src/fastmcp/resources/types.py b/src/fastmcp/resources/types.py index e86733e8a..f7384a85a 100644 --- a/src/fastmcp/resources/types.py +++ b/src/fastmcp/resources/types.py @@ -15,6 +15,7 @@ import pydantic.json import pydantic_core from pydantic import Field, ValidationInfo +import fastmcp from fastmcp.resources.resource import Resource if TYPE_CHECKING: @@ -66,8 +67,23 @@ class FunctionResource(Resource): default=None, description="Name of the kwarg that should receive context" ) + @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 + self, + context: Context[ServerSessionT, LifespanContextT] | None = None, ) -> str | bytes: """Read the resource by calling the wrapped function.""" try: @@ -80,7 +96,7 @@ class FunctionResource(Resource): 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): @@ -127,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: @@ -145,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) @@ -197,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) diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.py index ae2776af8..b3396b368 100644 --- a/src/fastmcp/server/openapi.py +++ b/src/fastmcp/server/openapi.py @@ -265,7 +265,9 @@ class OpenAPIResource(Resource): self._client = client self._route = route - async def read(self) -> str | bytes: + 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 diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py index 1ca3b116a..2983932a1 100644 --- a/src/fastmcp/server/server.py +++ b/src/fastmcp/server/server.py @@ -401,7 +401,7 @@ class FastMCP(Generic[LifespanResultT]): 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) ] @@ -427,7 +427,7 @@ class FastMCP(Generic[LifespanResultT]): if self._prompt_manager.has_prompt(name): context = self.get_context() messages = await self._prompt_manager.render_prompt( - name, arguments, context=context + name, arguments=arguments or {}, context=context ) return GetPromptResult(messages=pydantic_core.to_jsonable_python(messages)) else: diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index 506f1a65a..2653ea1a9 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -682,7 +682,147 @@ class TestToolParameters: assert result[0].text == "0:16:40" -class TestResources: +class TestToolContextInjection: + """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}" + + mcp.add_tool(tool_with_context) + async with Client(mcp) as client: + tools = await client.list_tools() + assert len(tools) == 1 + assert tools[0].name == "tool_with_context" + + async def test_context_injection(self): + """Test that context is properly injected into tool calls.""" + mcp = FastMCP() + + @mcp.tool() + def tool_with_context(x: int, ctx: Context) -> str: + assert isinstance(ctx, Context) + assert ctx.request_id is not None + return ctx.request_id + + 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 content.text == "1" + + 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 + + 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 tool exists + async with Client(mcp) as client: + tools = await client.list_tools() + assert len(tools) == 1 + # Note: MCPTool from the client API doesn't expose tags + + +class TestResource: async def test_text_resource(self): mcp = FastMCP() @@ -756,6 +896,21 @@ class TestResources: assert result[0].blob == base64.b64encode(b"Binary file data").decode() +class TestResourceContext: + async def test_resource_with_context_annotation_gets_context(self): + mcp = FastMCP() + + @mcp.resource("resource://test") + def resource_with_context(ctx: Context) -> str: + assert isinstance(ctx, Context) + return ctx.request_id + + async with Client(mcp) as client: + result = await client.read_resource(AnyUrl("resource://test")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "1" + + class TestResourceTemplates: async def test_resource_with_params_not_in_uri(self): """Test that a resource with function parameters raises an error if the URI @@ -1026,144 +1181,19 @@ class TestResourceTemplates: assert result[0].text == "Template resource 1: a/b" -class TestContextInjection: - """Test context injection in tools.""" - - async def test_context_detection(self): - """Test that context parameters are properly detected.""" +class TestResourceTemplateContext: + async def test_resource_template_context(self): mcp = FastMCP() - def tool_with_context(x: int, ctx: Context) -> str: - return f"Request {ctx.request_id}: {x}" - - mcp.add_tool(tool_with_context) - async with Client(mcp) as client: - tools = await client.list_tools() - assert len(tools) == 1 - assert tools[0].name == "tool_with_context" - - 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}" + @mcp.resource("resource://{param}") + def resource_template(param: str, ctx: Context) -> str: + assert isinstance(ctx, Context) + return f"Resource template: {param} {ctx.request_id}" 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 - - 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 tool exists - async with Client(mcp) as client: - tools = await client.list_tools() - assert len(tools) == 1 - # Note: MCPTool from the client API doesn't expose tags + result = await client.read_resource(AnyUrl("resource://test")) + assert isinstance(result[0], TextResourceContents) + assert result[0].text == "Resource template: test 1" class TestPrompts: @@ -1350,3 +1380,19 @@ class TestPrompts: assert len(prompts_dict) == 1 prompt = prompts_dict["sample_prompt"] assert prompt.tags == {"example", "test-tag"} + + +class TestPromptContext: + async def test_prompt_context(self): + mcp = FastMCP() + + @mcp.prompt() + def prompt_fn(name: str, ctx: Context) -> str: + assert isinstance(ctx, Context) + return f"Hello, {name}! {ctx.request_id}" + + async with Client(mcp) as client: + result = await client.get_prompt("prompt_fn", {"name": "World"}) + assert len(result) == 1 + message = result[0] + assert message.role == "user" From eefaadee3473eefdce15c4bbb09cfa2ff935603f Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 25 Apr 2025 21:11:14 -0400 Subject: [PATCH 32/32] Update docs for context --- docs/servers/context.mdx | 82 +++++++++++++++++++++++++++++++------- docs/servers/prompts.mdx | 31 +++++--------- docs/servers/resources.mdx | 54 +++++++++++++++---------- docs/servers/tools.mdx | 69 ++++++++++++++++---------------- 4 files changed, 146 insertions(+), 90 deletions(-) diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx index 685b833b0..203045184 100644 --- a/docs/servers/context.mdx +++ b/docs/servers/context.mdx @@ -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 @@ -21,7 +21,7 @@ The `Context` object provides a clean interface to access MCP features within yo ## 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 -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. -## 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. \ No newline at end of file +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} +""" +``` + + + +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. \ No newline at end of file diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdx index 5668846f4..9f276209a 100644 --- a/docs/servers/prompts.mdx +++ b/docs/servers/prompts.mdx @@ -171,33 +171,24 @@ 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. + -```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 diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx index 6b1fe6bd2..b3e1c1dee 100644 --- a/docs/servers/resources.mdx +++ b/docs/servers/resources.mdx @@ -95,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 + + + +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 @@ -205,6 +235,8 @@ Note that this parameter is only available when using `add_resource()` directly 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: @@ -379,28 +411,6 @@ 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 diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx index 2c4fb7370..34cb00601 100644 --- a/docs/servers/tools.mdx +++ b/docs/servers/tools.mdx @@ -263,7 +263,8 @@ FastMCP automatically catches exceptions raised within your tool function: Using informative exceptions helps the LLM understand failures and react appropriately. -### Accessing MCP Context +## 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`. @@ -304,39 +305,6 @@ The Context object provides access to: For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context). -## Server Behavior - -### Duplicate Tools - - - -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 -from fastmcp import FastMCP - -mcp = FastMCP( - name="StrictServer", - # Configure behavior for duplicate tool names - on_duplicate_tools="error" -) - -@mcp.tool() -def my_tool(): return "Version 1" - -# This will now raise a ValueError because 'my_tool' already exists -# and on_duplicate_tools is set to "error". -# @mcp.tool() -# def my_tool(): return "Version 2" -``` - -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. - ## Parameter Types FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools. @@ -663,3 +631,36 @@ Common validation options include: | `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 + + + +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 +from fastmcp import FastMCP + +mcp = FastMCP( + name="StrictServer", + # Configure behavior for duplicate tool names + on_duplicate_tools="error" +) + +@mcp.tool() +def my_tool(): return "Version 1" + +# This will now raise a ValueError because 'my_tool' already exists +# and on_duplicate_tools is set to "error". +# @mcp.tool() +# def my_tool(): return "Version 2" +``` + +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.