Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Merge branch 'main' into output-schema

Jeremiah Lowin1e29149d5feb
diff --cc src/fastmcp/server/server.py
index 6f14af60c,76b1373a6..ac3076b71
--- a/src/fastmcp/server/server.py
+++ b/src/fastmcp/server/server.py
@@@ -818,8 -839,7 +842,8 @@@ class FastMCP(Generic[LifespanResultT])
name: Optional name for the tool (keyword-only, alternative to name_or_fn)
description: Optional description of what the tool does
tags: Optional set of tags for categorizing the tool
+ output_schema: Optional JSON schema for the tool's output
- annotations: Optional annotations about the tool's behavior (e.g. {"is_async": True})
+ annotations: Optional annotations about the tool's behavior
exclude_args: Optional list of argument names to exclude from the tool schema
enabled: Optional boolean to enable or disable the tool
diff --cc src/fastmcp/tools/tool.py
index ad53590e6,49588df28..6579c3672
--- a/src/fastmcp/tools/tool.py
+++ b/src/fastmcp/tools/tool.py
@@@ -1,18 -1,15 +1,16 @@@
from __future__ import annotations
import inspect
- import json
from collections.abc import Callable
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Annotated, Any
+import mcp.types
import pydantic_core
from mcp.types import ContentBlock, TextContent, ToolAnnotations
from mcp.types import Tool as MCPTool
-from pydantic import Field
+from pydantic import Field, PydanticSchemaGenerationError
- import fastmcp
from fastmcp.server.dependencies import get_context
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.json_schema import compress_schema
@@@ -41,21 -35,30 +39,37 @@@ def default_serializer(data: Any) -> st
class Tool(FastMCPComponent):
"""Internal tool registration info."""
- parameters: dict[str, Any] = Field(description="JSON schema for tool parameters")
- annotations: ToolAnnotations | None = Field(
- default=None, description="Additional annotations about the tool"
- )
- serializer: Callable[[Any], str] | None = Field(
- default=None, description="Optional custom serializer for tool results"
- )
+ parameters: Annotated[
+ dict[str, Any], Field(description="JSON schema for tool parameters")
+ ]
+ output_schema: Annotated[
+ dict[str, Any] | None, Field(description="JSON schema for tool output")
+ ] = None
+ annotations: Annotated[
+ ToolAnnotations | None,
+ Field(description="Additional annotations about the tool"),
+ ] = None
+ serializer: Annotated[
+ Callable[[Any], str] | None,
+ Field(description="Optional custom serializer for tool results"),
+ ] = None
+ def enable(self) -> None:
+ super().enable()
+ try:
+ context = get_context()
+ context._queue_tool_list_changed() # type: ignore[private-use]
+ except RuntimeError:
+ pass # No context available
+
+ def disable(self) -> None:
+ super().disable()
+ try:
+ context = get_context()
+ context._queue_tool_list_changed() # type: ignore[private-use]
+ except RuntimeError:
+ pass # No context available
+
def to_mcp_tool(self, **overrides: Any) -> MCPTool:
kwargs = {
"name": self.name,
diff --cc src/fastmcp/tools/tool_transform.py
index 4104fcfe1,b2b871513..75fa2baaa
--- a/src/fastmcp/tools/tool_transform.py
+++ b/src/fastmcp/tools/tool_transform.py
@@@ -97,45 -100,65 +97,65 @@@ class ArgTransform
examples: Examples for the argument. Use ... for no change.
Examples:
- # Rename argument 'old_name' to 'new_name'
+ Rename argument 'old_name' to 'new_name'
+ ```python
ArgTransform(name="new_name")
+ ```
- # Change description only
+ Change description only
+ ```python
ArgTransform(description="Updated description")
+ ```
- # Add a default value (makes argument optional)
+ Add a default value (makes argument optional)
+ ```python
ArgTransform(default=42)
+ ```
- # Add a default factory (makes argument optional)
+ Add a default factory (makes argument optional)
+ ```python
ArgTransform(default_factory=lambda: time.time())
+ ```
- # Change the type
+ Change the type
+ ```python
ArgTransform(type=str)
+ ```
- # Hide the argument entirely from clients
+ Hide the argument entirely from clients
+ ```python
ArgTransform(hide=True)
+ ```
- # Hide argument but pass a constant value to parent
+ Hide argument but pass a constant value to parent
+ ```python
ArgTransform(hide=True, default="constant_value")
+ ```
- # Hide argument but pass a factory-generated value to parent
+ Hide argument but pass a factory-generated value to parent
+ ```python
ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex)
+ ```
- # Make an optional parameter required (removes any default)
+ Make an optional parameter required (removes any default)
+ ```python
ArgTransform(required=True)
+ ```
- # Combine multiple transformations
+ Combine multiple transformations
+ ```python
ArgTransform(name="new_name", description="New desc", default=None, type=int)
+ ```
"""
- name: str | EllipsisType = NotSet
- description: str | EllipsisType = NotSet
- default: Any | EllipsisType = NotSet
- default_factory: Callable[[], Any] | EllipsisType = NotSet
- type: Any | EllipsisType = NotSet
+ name: str | NotSetT = NotSet
+ description: str | NotSetT = NotSet
+ default: Any | NotSetT = NotSet
+ default_factory: Callable[[], Any] | NotSetT = NotSet
+ type: Any | NotSetT = NotSet
hide: bool = False
- required: Literal[True] | EllipsisType = NotSet
- examples: Any | EllipsisType = NotSet
+ required: Literal[True] | NotSetT = NotSet
+ examples: Any | NotSetT = NotSet
def __post_init__(self):
"""Validate that only one of default or default_factory is provided."""
diff --cc tests/server/test_server_interactions.py
index ae5287e51,36abc0c4b..042067bcb
--- a/tests/server/test_server_interactions.py
+++ b/tests/server/test_server_interactions.py
@@@ -822,26 -851,14 +851,30 @@@ class TestToolParameters
return str(x)
async with Client(mcp) as client:
- result = await client.call_tool("send_timedelta", {"x": 1000})
- assert result[0].text == "0:16:40" # type: ignore[attr-defined]
+ # Int input should raise validation error (no conversion)
+ with pytest.raises(
+ ToolError,
+ match="Input validation error: 1000 is not of type 'string'",
+ ):
+ await client.call_tool("send_timedelta", {"x": 1000})
+class TestToolOutputSchema:
+ @pytest.mark.parametrize("annotation", [str, int, float, bool, list, dict, AnyUrl])
+ async def test_output_schema(self, annotation):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def f() -> annotation: # type: ignore
+ return "hello"
+
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ assert len(tools) == 1
+ # this line will fail until MCP adds output schemas!!
+ assert tools[0].outputSchema == TypeAdapter(annotation).json_schema() # type: ignore
+
+
class TestToolContextInjection:
"""Test context injection in tools."""
diff --cc tests/tools/test_tool.py
index d60ec0a7d,d3da4c02a..1561323e2
--- a/tests/tools/test_tool.py
+++ b/tests/tools/test_tool.py
@@@ -10,13 -8,9 +10,9 @@@ from mcp.types import
TextContent,
TextResourceContents,
)
-from pydantic import AnyUrl, BaseModel
+from pydantic import AnyUrl, BaseModel, Field, TypeAdapter
- from fastmcp import FastMCP
- from fastmcp.client import Client
- from fastmcp.exceptions import ToolError
from fastmcp.tools.tool import Tool, _convert_to_content
- from fastmcp.utilities.tests import temporary_settings
from fastmcp.utilities.types import Audio, File, Image
@@@ -247,413 -240,6 +243,234 @@@ class TestToolFromFunction
assert result[0].text == "Custom serializer: 15"
+class TestToolFromFunctionOutputSchema:
+ async def test_no_return_annotation(self):
+ def func():
+ pass
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema is None
+
+ @pytest.mark.parametrize(
+ "annotation",
+ [
+ None,
+ int,
+ float,
+ bool,
+ str,
+ int | float,
+ list[int],
+ list[int | float],
+ dict[str, int | None],
+ tuple[int, str],
+ set[int],
+ list[tuple[int, str]],
+ ],
+ )
+ async def test_simple_return_annotation(self, annotation):
+ def func() -> annotation: # type: ignore
+ return 1
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(annotation).json_schema()
+
+ @pytest.mark.parametrize(
+ "annotation",
+ [
+ Any,
+ AnyUrl,
+ Annotated[int, Field(ge=1)],
+ Annotated[int, Field(ge=1)],
+ ],
+ )
+ async def test_complex_return_annotation(self, annotation):
+ def func() -> annotation: # type: ignore
+ return 1
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(annotation).json_schema()
+
+ @pytest.mark.parametrize(
+ "annotation, expected",
+ [
+ (Image, ImageContent),
+ (Audio, AudioContent),
+ (File, EmbeddedResource),
+ (Image | int, ImageContent | int),
+ (Image | Audio, ImageContent | AudioContent),
+ (list[Image | Audio], list[ImageContent | AudioContent]),
+ ],
+ )
+ async def test_converted_return_annotation(self, annotation, expected):
+ def func() -> annotation: # type: ignore
+ return 1
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(expected).json_schema()
+
+ async def test_dataclass_return_annotation(self):
+ @dataclass
+ class Person:
+ name: str
+ age: int
+
+ def func() -> Person:
+ return Person(name="John", age=30)
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(Person).json_schema()
+
+ async def test_base_model_return_annotation(self):
+ class Person(BaseModel):
+ name: str
+ age: int
+
+ def func() -> Person:
+ return Person(name="John", age=30)
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(Person).json_schema()
+
+ async def test_typeddict_return_annotation(self):
+ class Person(TypedDict):
+ name: str
+ age: int
+
+ def func() -> Person:
+ return Person(name="John", age=30)
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema == TypeAdapter(Person).json_schema()
+
+ async def test_unserializable_return_annotation(self):
+ class Unserializable:
+ def __init__(self, data: Any):
+ self.data = data
+
+ def func() -> Unserializable:
+ return Unserializable(data="test")
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema is None
+
+ async def test_mixed_unserializable_return_annotation(self):
+ class Unserializable:
+ def __init__(self, data: Any):
+ self.data = data
+
+ def func() -> Unserializable | int:
+ return Unserializable(data="test")
+
+ tool = Tool.from_function(func)
+ assert tool.output_schema is None
+
+ async def test_provided_output_schema_takes_precedence_over_json_compatible_annotation(
+ self,
+ ):
+ """Test that provided output_schema takes precedence over inferred schema from JSON-compatible annotation."""
+
+ def func() -> dict[str, int]:
+ return {"a": 1, "b": 2}
+
+ # Provide a custom output schema that differs from the inferred one
+ custom_schema = {"type": "string", "description": "Custom schema"}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_complex_annotation(
+ self,
+ ):
+ """Test that provided output_schema takes precedence over inferred schema from complex annotation."""
+
+ def func() -> list[dict[str, int | float]]:
+ return [{"a": 1, "b": 2.5}]
+
+ # Provide a custom output schema that differs from the inferred one
+ custom_schema = {"type": "object", "properties": {"custom": {"type": "string"}}}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_unserializable_annotation(
+ self,
+ ):
+ """Test that provided output_schema takes precedence over None schema from unserializable annotation."""
+
+ class Unserializable:
+ def __init__(self, data: Any):
+ self.data = data
+
+ def func() -> Unserializable:
+ return Unserializable(data="test")
+
+ # Provide a custom output schema even though the annotation is unserializable
+ custom_schema = {"type": "array", "items": {"type": "string"}}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_no_annotation(self):
+ """Test that provided output_schema takes precedence over None schema from no annotation."""
+
+ def func():
+ return "hello"
+
+ # Provide a custom output schema even though there's no return annotation
+ custom_schema = {"type": "number", "minimum": 0}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_converted_annotation(
+ self,
+ ):
+ """Test that provided output_schema takes precedence over converted schema from Image/Audio/File annotations."""
+
+ def func() -> Image:
+ return Image(data=b"test")
+
+ # Provide a custom output schema that differs from the converted ImageContent schema
+ custom_schema = {
+ "type": "object",
+ "properties": {"custom_image": {"type": "string"}},
+ }
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_union_annotation(self):
+ """Test that provided output_schema takes precedence over inferred schema from union annotation."""
+
+ def func() -> str | int | None:
+ return "hello"
+
+ # Provide a custom output schema that differs from the inferred union schema
+ custom_schema = {"type": "boolean"}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+ async def test_provided_output_schema_takes_precedence_over_pydantic_annotation(
+ self,
+ ):
+ """Test that provided output_schema takes precedence over inferred schema from Pydantic model annotation."""
+
+ class Person(BaseModel):
+ name: str
+ age: int
+
+ def func() -> Person:
+ return Person(name="John", age=30)
+
+ # Provide a custom output schema that differs from the inferred Person schema
+ custom_schema = {"type": "array", "items": {"type": "number"}}
+
+ tool = Tool.from_function(func, output_schema=custom_schema)
+ assert tool.output_schema == custom_schema
+
+
- class TestLegacyToolJsonParsing:
- """Tests for Tool's JSON pre-parsing functionality."""
-
- @pytest.fixture(autouse=True)
- def enable_legacy_json_parsing(self):
- with temporary_settings(tool_attempt_parse_json_args=True):
- yield
-
- async def test_json_string_arguments(self):
- """Test that JSON string arguments are parsed and validated correctly"""
-
- def simple_func(x: int, y: list[str]) -> str:
- return f"{x}-{','.join(y)}"
-
- # Create a tool to use its JSON pre-parsing logic
- tool = Tool.from_function(simple_func)
-
- # Prepare arguments where some are JSON strings
- json_args = {
- "x": 1,
- "y": '["a", "b", "c"]', # JSON string
- }
-
- # Run the tool which will do JSON parsing
- result = await tool.run(json_args)
- assert result[0].text == "1-a,b,c" # type: ignore[attr-dict]
-
- async def test_str_vs_list_str(self):
- """Test handling of string vs list[str] type annotations."""
-
- def func_with_str_types(str_or_list: str | list[str]) -> str | list[str]:
- return str_or_list
-
- tool = Tool.from_function(func_with_str_types)
-
- # Test regular string input (should remain a string)
- result = await tool.run({"str_or_list": "hello"})
- assert result[0].text == "hello" # type: ignore[attr-dict]
-
- # Test JSON string input (should be parsed as a string)
- result = await tool.run({"str_or_list": '"hello"'})
- assert result[0].text == "hello" # type: ignore[attr-dict]
-
- # Test JSON list input (should be parsed as a list)
- result = await tool.run({"str_or_list": '["hello", "world"]'})
-
- # The exact formatting might vary, so we just check that it contains the key elements
- text_without_whitespace = result[0].text.replace(" ", "").replace("\n", "") # type: ignore[attr-dict]
- assert "hello" in text_without_whitespace
- assert "world" in text_without_whitespace
- assert "[" in text_without_whitespace
- assert "]" in text_without_whitespace
-
- async def test_keep_str_as_str(self):
- """Test that string arguments are kept as strings when they're not valid JSON"""
-
- def func_with_str_types(string: str) -> str:
- return string
-
- tool = Tool.from_function(func_with_str_types)
-
- # Invalid JSON should remain a string
- invalid_json = "{'nice to meet you': 'hello', 'goodbye': 5}"
- result = await tool.run({"string": invalid_json})
- assert result[0].text == invalid_json # type: ignore[attr-dict]
-
- async def test_keep_str_union_as_str(self):
- """Test that string arguments are kept as strings when parsing would create an invalid value"""
-
- def func_with_str_types(
- string: str | dict[int, str] | None,
- ) -> str | dict[int, str] | None:
- return string
-
- tool = Tool.from_function(func_with_str_types)
-
- # Invalid JSON for the union type should remain a string
- invalid_json = "{'nice to meet you': 'hello', 'goodbye': 5}"
- result = await tool.run({"string": invalid_json})
- assert result[0].text == invalid_json # type: ignore[attr-dict]
-
- async def test_complex_type_validation(self):
- """Test that parsed JSON is validated against complex types"""
-
- class SomeModel(BaseModel):
- x: int
- y: dict[int, str]
-
- def func_with_complex_type(data: SomeModel) -> SomeModel:
- return data
-
- tool = Tool.from_function(func_with_complex_type)
-
- # Valid JSON for the model
- valid_json = '{"x": 1, "y": {"1": "hello"}}'
- result = await tool.run({"data": valid_json})
- assert '"x": 1' in result[0].text # type: ignore[attr-dict]
- assert '"y": {' in result[0].text # type: ignore[attr-dict]
- assert '"1": "hello"' in result[0].text # type: ignore[attr-dict]
-
- # Invalid JSON for the model (y has string keys, not int keys)
- # Should throw a validation error
- invalid_json = '{"x": 1, "y": {"invalid": "hello"}}'
- with pytest.raises(Exception):
- await tool.run({"data": invalid_json})
-
- 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 result[0].text == "15" # type: ignore[attr-dict]
-
- 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(
- ToolError,
- match="Error calling tool 'process_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 result[0].text == "6" # type: ignore[attr-dict]
-
- 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 result[0].text == "15" # type: ignore[attr-dict]
-
- 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" # type: ignore[attr-dict]
-
-
class TestConvertResultToContent:
"""Tests for the _convert_to_content helper function."""