Skip to content

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

fix: don't infer an output schema for unconstrained sequences (#4999)

Francis Secada032b9f63823e
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 44d1f23fa..37bafb425 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -546,7 +546,7 @@ def get_user_data(user_id: str) -> dict:
#### Primitives and Collections
-When your tool returns a primitive type (int, str, bool) or a collection (list, set), FastMCP needs a return type annotation to generate structured content. The annotation tells FastMCP how to validate and serialize the result.
+When your tool returns a primitive type (int, str, bool) or a collection (list, set), FastMCP needs a return type annotation to generate structured content. The annotation tells FastMCP how to validate and serialize the result. The annotation has to say something about the items: a bare `list`, `tuple`, or `Sequence` (or `list[Any]`) describes nothing, so FastMCP infers no output schema for it, the same as for `Any`. Use `list[int]`, `list[dict]`, and so on when you want structured output for a collection.
Without a type annotation, the tool only produces `content`:
diff --git a/fastmcp_slim/fastmcp/tools/function_parsing.py b/fastmcp_slim/fastmcp/tools/function_parsing.py
index 72d594794..59fd1e830 100644
--- a/fastmcp_slim/fastmcp/tools/function_parsing.py
+++ b/fastmcp_slim/fastmcp/tools/function_parsing.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import functools
import inspect
import types
-from collections.abc import Callable
+from collections.abc import Callable, Sequence
from dataclasses import dataclass
from typing import Annotated, Any, Generic, Union, get_args, get_origin, get_type_hints
@@ -41,6 +41,9 @@ def _contains_bytes_type(tp: Any) -> bool:
return False
+_UNCONSTRAINED_SEQUENCE_ORIGINS = (list, tuple, Sequence)
+
+
def _contains_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if is_prefab_type(tp):
@@ -51,6 +54,31 @@ def _contains_prefab_type(tp: Any) -> bool:
return False
+def _is_unconstrained_sequence(tp: Any) -> bool:
+ """A sequence annotation that says nothing about its items.
+
+ Bare `list`, `tuple`, `Sequence` (and their `typing` spellings), plus
+ `list[Any]`, `Sequence[Any]` and the variadic `tuple[Any, ...]`. The schema
+ these produce -- ``{"result": {"items": {}, "type": "array"}}`` -- constrains
+ nothing, which is why `Any` itself is already excluded from inference. A
+ fixed-length `tuple[Any, Any]` still pins its length, so it keeps its schema.
+ """
+ tp = _unwrap_type_alias(tp)
+ if get_origin(tp) is Annotated:
+ tp = get_args(tp)[0]
+ if tp in _UNCONSTRAINED_SEQUENCE_ORIGINS:
+ return True
+ origin = get_origin(tp)
+ if origin not in _UNCONSTRAINED_SEQUENCE_ORIGINS:
+ return False
+ args = get_args(tp)
+ if not args:
+ return True
+ if origin is tuple:
+ return len(args) == 2 and args[0] is Any and args[1] is Ellipsis
+ return all(a is Any for a in args)
+
+
def _unwrap_type_alias(tp: Any) -> Any:
"""Resolve a PEP 695 ``type X = ...`` alias to its underlying value.
@@ -403,6 +431,19 @@ class ParsedFunction:
if _contains_input_required(output_type):
output_type = _UnserializableType
+ # A bare `list`/`tuple` carries no item type, so `replace_type`
+ # below has nothing to match and the content types it exists to
+ # suppress slip through. The schema that results constrains
+ # nothing, and inferring it is not free: an output schema forces
+ # structured content, so a tool returning `[ImageContent, {...}]`
+ # under a `-> list` annotation sends the base64 image BOTH as an
+ # image block and again inside `structuredContent`. Clients
+ # mishandle that in both directions -- some render the JSON blob
+ # instead of the picture, others inject the base64 into model
+ # context and blow their tool-output token cap.
+ if _is_unconstrained_sequence(output_type):
+ output_type = _UnserializableType
+
# there are a variety of types that we don't want to attempt to
# serialize because they are either used by FastMCP internally,
# or are MCP content types that explicitly don't form structured
diff --git a/tests/server/providers/local_provider_tools/test_output_schema.py b/tests/server/providers/local_provider_tools/test_output_schema.py
index a5f87d42d..df311a95e 100644
--- a/tests/server/providers/local_provider_tools/test_output_schema.py
+++ b/tests/server/providers/local_provider_tools/test_output_schema.py
@@ -45,7 +45,7 @@ class PersonDataclass:
class TestToolOutputSchema:
- @pytest.mark.parametrize("annotation", [str, int, float, bool, list, AnyUrl])
+ @pytest.mark.parametrize("annotation", [str, int, float, bool, AnyUrl])
async def test_simple_output_schema(self, annotation):
mcp = FastMCP()
diff --git a/tests/tools/tool/test_output_schema.py b/tests/tools/tool/test_output_schema.py
index c650134d9..2b15b53d7 100644
--- a/tests/tools/tool/test_output_schema.py
+++ b/tests/tools/tool/test_output_schema.py
@@ -1,6 +1,10 @@
+import json
+import typing
+from collections.abc import Sequence
from dataclasses import dataclass
from typing import Annotated, Any
+import mcp_types
import pytest
from inline_snapshot import snapshot
from mcp_types import (
@@ -13,6 +17,7 @@ from mcp_types import (
from pydantic import AnyUrl, BaseModel, Field, TypeAdapter
from typing_extensions import TypedDict
+from fastmcp import Client, FastMCP
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.types import Audio, File, Image
@@ -34,7 +39,6 @@ class TestToolFromFunctionOutputSchema:
bool,
str,
int | float,
- list,
list[int],
list[int | float],
dict,
@@ -623,3 +627,91 @@ class TestWrapResultMeta:
result = await tool.run({})
assert result.structured_content == {"key": "val"}
assert result.meta is None
+
+
+class TestUnconstrainedSequenceReturns:
+ """A `list`/`tuple` with no item type infers no output schema.
+
+ `Any` is already excluded from inference because the schema it yields
+ constrains nothing. A bare `list` is the sequence-shaped equivalent: its
+ schema is ``{"result": {"items": {}, "type": "array"}}``, which permits
+ every value that no schema at all permits.
+
+ Inferring it is not free. An output schema forces structured content, and
+ `replace_type` cannot suppress the MCP content types inside a `list` that
+ has no item type to match. So a tool annotated `-> list` that returns
+ `[ImageContent(...), {...}]` -- the shape the docs recommend for pairing a
+ picture with its metadata -- put the base64 image on the wire twice: once
+ as an image block, once serialised into `structuredContent`. Clients break
+ on that in both directions, some rendering the JSON blob instead of the
+ picture and others injecting the base64 into model context.
+ """
+
+ @pytest.mark.parametrize(
+ "annotation",
+ [
+ list,
+ tuple,
+ Sequence,
+ list,
+ tuple,
+ typing.Sequence,
+ list[Any],
+ Sequence[Any],
+ tuple[Any, ...],
+ Annotated[list, "meta"],
+ "bare",
+ ],
+ )
+ def test_no_schema_is_inferred(self, annotation):
+ if annotation == "bare":
+
+ def func():
+ return []
+ else:
+
+ def func() -> annotation: # type: ignore[valid-type]
+ return []
+
+ assert Tool.from_function(func).output_schema is None
+
+ @pytest.mark.parametrize(
+ "annotation",
+ [
+ list[int],
+ dict,
+ str,
+ tuple[int, str],
+ tuple[Any],
+ tuple[Any, Any],
+ Sequence[str],
+ ],
+ )
+ def test_a_constrained_sequence_still_infers(self, annotation):
+ """The guard must not swallow annotations that do say something."""
+
+ def func() -> annotation: # type: ignore[valid-type]
+ return []
+
+ assert Tool.from_function(func).output_schema is not None
+
+ async def test_an_image_is_not_duplicated_into_structured_content(self):
+ """The regression this exists to prevent."""
+ png = (
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8"
+ "z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+ )
+ mcp = FastMCP("test")
+
+ @mcp.tool
+ def render() -> list:
+ return [
+ mcp_types.ImageContent(type="image", data=png, mime_type="image/png"),
+ {"note": "metadata"},
+ ]
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("render")
+
+ assert [b.type for b in result.content] == ["image", "text"]
+ assert png not in json.dumps(result.structured_content or {})