Skip to content

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

fix(proxy): relay non-object tool results across MCP versions (#5763)

Felix Pan78ccaf8d840b
diff --git a/docs/servers/providers/proxy.mdx b/docs/servers/providers/proxy.mdx
index e4e2bba9b..4fdf0b92d 100644
--- a/docs/servers/providers/proxy.mdx
+++ b/docs/servers/providers/proxy.mdx
@@ -203,7 +203,9 @@ backend = ProxyClient(
<VersionBadge version="4.0.0" />
-A proxy passes a backend's tool results through untouched, including results that don't match the output schema the backend advertised. Deciding whether a server honored its own contract belongs to the client consuming the result, and that client validates for itself.
+A proxy does not validate backend tool results against the advertised output schema. Deciding whether a server honored its own contract belongs to the client consuming the result, and that client validates for itself.
+
+When a 2026-07-28 backend returns structured content with a non-object schema, a 2026-07-28 caller receives the original schema and value. Earlier MCP clients require an object output schema, so the proxy advertises a `result` property and wraps the structured value under that key. FastMCP clients still expose the original value through `CallToolResult.data`.
This matters when a backend's declared schema is subtly wrong β€” an enum missing a variant it actually returns, say. A proxy that enforced the schema would replace the backend's working response with an error of its own, and the client would never see what the backend actually said.
diff --git a/fastmcp_slim/fastmcp/server/middleware/caching.py b/fastmcp_slim/fastmcp/server/middleware/caching.py
index ec2de6928..5e9851951 100644
--- a/fastmcp_slim/fastmcp/server/middleware/caching.py
+++ b/fastmcp_slim/fastmcp/server/middleware/caching.py
@@ -34,7 +34,12 @@ from fastmcp.resources.base import (
)
from fastmcp.server.dependencies import get_access_token
from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext
-from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResult
+from fastmcp.tools.base import (
+ InputRequiredToolResult,
+ RawStructuredToolResult,
+ Tool,
+ ToolResult,
+)
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import FastMCPBaseModel
@@ -139,9 +144,10 @@ class CacheableResourceResult(FastMCPBaseModel):
class CacheableToolResult(FastMCPBaseModel):
content: list[mcp_types.ContentBlock]
- structured_content: dict[str, Any] | None
+ structured_content: Any
meta: dict[str, Any] | None
is_error: bool = False
+ raw_structured_content: bool = False
@classmethod
def wrap(cls, value: ToolResult) -> Self:
@@ -150,15 +156,20 @@ class CacheableToolResult(FastMCPBaseModel):
structured_content=value.structured_content,
meta=value.meta,
is_error=value.is_error,
+ raw_structured_content=isinstance(value, RawStructuredToolResult),
)
def unwrap(self) -> ToolResult:
- return ToolResult(
+ result_type = (
+ RawStructuredToolResult if self.raw_structured_content else ToolResult
+ )
+ result = result_type(
content=self.content,
structured_content=self.structured_content,
meta=self.meta,
is_error=self.is_error,
)
+ return result
class CacheableMessage(FastMCPBaseModel):
@@ -474,7 +485,12 @@ class ResponseCachingMiddleware(Middleware):
return await call_next(context)
cache_key: str = _make_call_tool_cache_key(
- msg=context.message, auth_key=_get_auth_partition_key()
+ msg=context.message,
+ auth_key=_get_auth_partition_key(),
+ modern_protocol=(
+ context.fastmcp_context is not None
+ and context.fastmcp_context._is_modern_protocol()
+ ),
)
if cached_value := await self._call_tool_cache.get(key=cache_key):
@@ -692,12 +708,14 @@ def _get_component_version_cache_key(msg: mcp_types.RequestParams) -> str:
def _make_call_tool_cache_key(
- msg: mcp_types.CallToolRequestParams, auth_key: str = ANONYMOUS_AUTH_KEY
+ msg: mcp_types.CallToolRequestParams,
+ auth_key: str = ANONYMOUS_AUTH_KEY,
+ modern_protocol: bool = False,
) -> str:
- """Make a cache key for a tool call using name, version, and arguments."""
+ """Make a cache key for a tool call using protocol era, name, version, and arguments."""
return _hash_cache_key(
- f"{auth_key}:{_get_component_version_cache_key(msg)}:{msg.name}:"
+ f"{auth_key}:{modern_protocol}:{_get_component_version_cache_key(msg)}:{msg.name}:"
f"{_get_arguments_str(msg.arguments)}"
)
diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
index fc6b43310..ee6a10772 100644
--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
@@ -36,11 +36,16 @@ from fastmcp.server.dependencies import (
bind_request_context,
extract_version_spec,
)
-from fastmcp.tools.base import InputRequiredToolResult, ToolResult
+from fastmcp.tools.base import (
+ InputRequiredToolResult,
+ RawStructuredToolResult,
+ ToolResult,
+)
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
+from fastmcp.utilities.json_schema import is_object_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.pagination import CursorState, paginate_sequence
from fastmcp.utilities.versions import VersionSpec, dedupe_with_versions
@@ -147,7 +152,44 @@ class MCPOperationsMixin:
tools = dedupe_with_versions(
list(await self.list_tools()), lambda t: t.name
)
- sdk_tools = [tool.to_mcp_tool(name=tool.name) for tool in tools]
+ sdk_tools = []
+ for tool in tools:
+ output_schema = tool.output_schema
+ if (
+ ctx.protocol_version not in MODERN_PROTOCOL_VERSIONS
+ and output_schema is not None
+ ):
+ if (
+ is_object_schema(output_schema)
+ and output_schema.get("type") != "object"
+ ):
+ # Implicit and nullable object schemas are valid JSON
+ # Schema, but legacy MCP requires a literal object type
+ # at the root. A null result is sent without structured
+ # content, which legacy clients already accept.
+ output_schema = {**output_schema, "type": "object"}
+ elif not is_object_schema(output_schema):
+ output_schema = {
+ "type": "object",
+ "properties": {"result": output_schema},
+ "required": ["result"],
+ "x-fastmcp-wrap-result": True,
+ # Local references inside the original schema still
+ # resolve from the document root after wrapping.
+ **(
+ {"$defs": output_schema["$defs"]}
+ if "$defs" in output_schema
+ else {}
+ ),
+ **(
+ {"definitions": output_schema["definitions"]}
+ if "definitions" in output_schema
+ else {}
+ ),
+ }
+ sdk_tools.append(
+ tool.to_mcp_tool(name=tool.name, outputSchema=output_schema)
+ )
# Refresh the Mcp-Param schema cache (served to the SDK's
# `get_tool_input_schema` hook, mcp>=2.3) from the full visible
# set, pre-pagination: these are the authoritative wire schemas,
@@ -316,6 +358,33 @@ class MCPOperationsMixin:
),
)
return result.input_required
+ # Tool._run marks results declared by a non-object output schema
+ # as raw; legacy clients receive them under the advertised
+ # `result` wrapper.
+ if ctx.protocol_version not in MODERN_PROTOCOL_VERSIONS and (
+ isinstance(result, RawStructuredToolResult)
+ or (
+ result.structured_content is not None
+ and not isinstance(result.structured_content, dict)
+ )
+ ):
+ fastmcp_meta = result.meta.get("fastmcp") if result.meta else None
+ already_wrapped = (
+ isinstance(fastmcp_meta, dict)
+ and fastmcp_meta.get("wrap_result") is True
+ )
+ if not already_wrapped:
+ meta = dict(result.meta or {})
+ meta["fastmcp"] = {
+ **(fastmcp_meta if isinstance(fastmcp_meta, dict) else {}),
+ "wrap_result": True,
+ }
+ result = ToolResult(
+ content=result.content,
+ structured_content={"result": result.structured_content},
+ meta=meta,
+ is_error=result.is_error,
+ )
return _normalize_call_tool_result(result.to_mcp_result())
async def _on_read_resource(
diff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.py
index 8d0aac18e..7f9c7c9f7 100644
--- a/fastmcp_slim/fastmcp/server/providers/proxy.py
+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py
@@ -63,8 +63,14 @@ from fastmcp.server.providers.aggregate import ProviderErrorStrategy
from fastmcp.server.providers.base import Provider
from fastmcp.server.server import FastMCP
from fastmcp.telemetry import inject_trace_context
-from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResult
+from fastmcp.tools.base import (
+ InputRequiredToolResult,
+ RawStructuredToolResult,
+ Tool,
+ ToolResult,
+)
from fastmcp.utilities.components import FastMCPComponent, get_fastmcp_metadata
+from fastmcp.utilities.json_schema import is_object_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.tasks import TaskConfig
from fastmcp.utilities.versions import VersionSpec, version_sort_key
@@ -484,10 +490,29 @@ class ProxyTool(Tool):
# backend's content (including non-text and structured content),
# and the client still raises on isError by default.
# Preserve backend's meta (includes task metadata for background tasks)
+ structured_content = tool_result.structured_content
+ meta = _forwardable_server_meta(tool_result.meta, self._identity) or None
+ has_structured_content = (
+ "structured_content" in tool_result.model_fields_set
+ )
+ if has_structured_content and (
+ not isinstance(structured_content, dict)
+ or (
+ self.output_schema is not None
+ and not is_object_schema(self.output_schema)
+ )
+ ):
+ return RawStructuredToolResult(
+ content=tool_result.content,
+ structured_content=structured_content,
+ meta=meta,
+ is_error=tool_result.is_error,
+ )
+
return ToolResult(
content=tool_result.content,
- structured_content=tool_result.structured_content,
- meta=_forwardable_server_meta(tool_result.meta, self._identity) or None,
+ structured_content=structured_content,
+ meta=meta,
is_error=tool_result.is_error,
)
diff --git a/fastmcp_slim/fastmcp/tools/base.py b/fastmcp_slim/fastmcp/tools/base.py
index f1b96f966..616f4eba5 100644
--- a/fastmcp_slim/fastmcp/tools/base.py
+++ b/fastmcp_slim/fastmcp/tools/base.py
@@ -36,6 +36,7 @@ from pydantic.json_schema import SkipJsonSchema
from fastmcp.exceptions import ToolError
from fastmcp.utilities.authorization import AuthCheck
from fastmcp.utilities.components import FastMCPComponent
+from fastmcp.utilities.json_schema import is_object_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.prefab import (
is_prefab_app,
@@ -244,6 +245,40 @@ class ToolResult(BaseModel):
return self.content, self.structured_content
+class RawStructuredToolResult(ToolResult):
+ """A proxied result whose structured value need not be an object."""
+
+ structured_content: Any = None
+
+ def __init__(
+ self,
+ content: list[ContentBlock],
+ structured_content: Any,
+ meta: dict[str, Any] | None = None,
+ is_error: bool = False,
+ ) -> None:
+ # The proxy already received wire-format content from the backend.
+ # ToolResult's constructor intentionally rejects non-object values for
+ # ordinary tools; the wire handler wraps these for legacy clients.
+ BaseModel.__init__(
+ self,
+ content=content,
+ structured_content=structured_content,
+ meta=meta,
+ is_error=is_error,
+ )
+
+ def to_mcp_result(self) -> CallToolResult:
+ # Serialize the current public fields so response middleware edits are
+ # reflected on the wire, including when it uses model_copy().
+ return CallToolResult(
+ content=self.content,
+ structured_content=self.structured_content,
+ is_error=self.is_error,
+ _meta=self.meta, # type: ignore[call-arg]
+ )
+
+
class InputRequiredToolResult(ToolResult):
"""The full result of a single multi-round-trip leg (SEP-2322).
@@ -502,7 +537,32 @@ class Tool(FastMCPComponent):
subclasses can customize dispatch. For example, ``FastMCPProviderTool``
overrides this to delegate to child-server middleware.
"""
- return await self.run(arguments)
+ result = await self.run(arguments)
+ return self._mark_non_object_result(result)
+
+ def _mark_non_object_result(self, result: ToolResult) -> ToolResult:
+ """Mark structured content declared by a non-object output schema.
+
+ Legacy MCP clients require object structured content, so the wire
+ handler wraps a `RawStructuredToolResult` under `result` to match the
+ wrapper it advertises for non-object schemas.
+ """
+ if (
+ isinstance(result, RawStructuredToolResult | InputRequiredToolResult)
+ or result.structured_content is None
+ or self.output_schema is None
+ or is_object_schema(self.output_schema)
+ ):
+ return result
+ fastmcp_meta = result.meta.get("fastmcp") if result.meta else None
+ if isinstance(fastmcp_meta, dict) and fastmcp_meta.get("wrap_result") is True:
+ return result
+ return RawStructuredToolResult(
+ content=result.content,
+ structured_content=result.structured_content,
+ meta=result.meta,
+ is_error=result.is_error,
+ )
@classmethod
def from_tool(
diff --git a/fastmcp_slim/fastmcp/tools/function_parsing.py b/fastmcp_slim/fastmcp/tools/function_parsing.py
index d267047f2..e9abb6e33 100644
--- a/fastmcp_slim/fastmcp/tools/function_parsing.py
+++ b/fastmcp_slim/fastmcp/tools/function_parsing.py
@@ -18,7 +18,7 @@ from typing_extensions import TypeVar as TypeVarExt
from fastmcp.tools.base import ToolResult
from fastmcp.utilities.docstring_parsing import ParsedDocstring, parse_docstring
-from fastmcp.utilities.json_schema import compress_schema
+from fastmcp.utilities.json_schema import compress_schema, is_object_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.prefab import is_prefab_type
from fastmcp.utilities.types import (
@@ -216,54 +216,6 @@ class _UnserializableType:
pass
-def _is_object_schema(
- schema: dict[str, Any],
- *,
- _root_schema: dict[str, Any] | None = None,
- _seen_refs: set[str] | None = None,
-) -> bool:
- """Check if a JSON schema represents an object type."""
- root_schema = _root_schema or schema
- seen_refs = _seen_refs or set()
-
- # Direct object type
- if schema.get("type") == "object":
- return True
-
- # Schema with properties but no explicit type is treated as object
- if "properties" in schema:
- return True
-
- # Resolve local $ref definitions and recurse into the target schema.
- ref = schema.get("$ref")
- if not isinstance(ref, str) or not ref.startswith("#/"):
- return False
-
- if ref in seen_refs:
- return False
-
- # Walk the JSON Pointer path from the root schema, unescaping each
- # token per RFC 6901 (~1 β†’ /, ~0 β†’ ~).
- pointer = ref.removeprefix("#/")
- segments = pointer.split("/")
- target: Any = root_schema
- for segment in segments:
- unescaped = segment.replace("~1", "/").replace("~0", "~")
- if not isinstance(target, dict) or unescaped not in target:
- return False
- target = target[unescaped]
-
- target_schema = target
- if not isinstance(target_schema, dict):
- return False
-
- return _is_object_schema(
- target_schema,
- _root_schema=root_schema,
- _seen_refs=seen_refs | {ref},
- )
-
-
@dataclass
class ParsedFunction:
fn: Callable[..., Any]
@@ -522,7 +474,7 @@ class ParsedFunction:
# because MCP requires that output schemas are objects
# Check if schema is an object type, resolving $ref references
# (self-referencing types use $ref at root level)
- if wrap_non_object_output_schema and not _is_object_schema(base_schema):
+ if wrap_non_object_output_schema and not is_object_schema(base_schema):
# Use the wrapped result schema directly
wrapped_type = _WrappedResult[clean_output_type]
wrapped_adapter = get_cached_typeadapter(wrapped_type)
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.py
index 0706dd409..d388b47e9 100644
--- a/fastmcp_slim/fastmcp/tools/function_tool.py
+++ b/fastmcp_slim/fastmcp/tools/function_tool.py
@@ -36,13 +36,14 @@ from fastmcp.tools.base import (
Tool,
ToolResult,
)
-from fastmcp.tools.function_parsing import ParsedFunction, _is_object_schema
+from fastmcp.tools.function_parsing import ParsedFunction
from fastmcp.utilities._callable_cache import cache_on_callable
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
from fastmcp.utilities.authorization import AuthCheck
+from fastmcp.utilities.json_schema import is_object_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.tasks import TaskConfig
from fastmcp.utilities.types import (
@@ -393,7 +394,7 @@ class FunctionTool(Tool):
final_output_schema = metadata.output_schema
if final_output_schema is not None and isinstance(final_output_schema, dict):
- if not _is_object_schema(final_output_schema):
+ if not is_object_schema(final_output_schema):
raise ValueError(
f"Output schemas must represent object types due to MCP spec limitations. "
f"Received: {final_output_schema!r}"
diff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.py
index 85b7fd5c0..acaf24bf8 100644
--- a/fastmcp_slim/fastmcp/tools/tool_transform.py
+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py
@@ -22,14 +22,18 @@ from fastmcp.tools.base import (
Tool,
ToolResult,
)
-from fastmcp.tools.function_parsing import ParsedFunction, _is_object_schema
+from fastmcp.tools.function_parsing import ParsedFunction
from fastmcp.tools.function_tool import FunctionTool, _ToolBodyError, _wrap_body_errors
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
from fastmcp.utilities.components import _convert_set_default_none
-from fastmcp.utilities.json_schema import _METADATA_KEYS, compress_schema
+from fastmcp.utilities.json_schema import (
+ _METADATA_KEYS,
+ compress_schema,
+ is_object_schema,
+)
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
FastMCPBaseModel,
@@ -501,9 +505,13 @@ class TransformedTool(Tool):
# If transform function returns ToolResult, respect our output_schema setting
if isinstance(result, ToolResult):
+ if self.output_schema == self.parent_tool.output_schema:
+ # A forwarding transform inherits its parent's result
+ # shape, including modern raw values and legacy wrappers.
+ return result
if self.output_schema is None:
return result
- elif not _is_object_schema(
+ elif not is_object_schema(
self.output_schema
) and not self.output_schema.get("x-fastmcp-wrap-result"):
# Non-object explicit schemas disable structured content
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema.py b/fastmcp_slim/fastmcp/utilities/json_schema.py
index 9cf7e22a4..3a4079e41 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema.py
@@ -988,3 +988,57 @@ def compress_schema(
)
return schema
+
+
+def is_object_schema(
+ schema: dict[str, Any],
+ *,
+ _root_schema: dict[str, Any] | None = None,
+ _seen_refs: set[str] | None = None,
+) -> bool:
+ """Check if a JSON schema represents an object type."""
+ root_schema = _root_schema or schema
+ seen_refs = _seen_refs or set()
+
+ # An explicit type takes precedence over properties, which only constrain
+ # objects and do not exclude other allowed types. A null alternative maps
+ # to absent structured content, so ["object", "null"] still describes an
+ # object result.
+ schema_type = schema.get("type")
+ if isinstance(schema_type, list):
+ return [t for t in schema_type if t != "null"] == ["object"]
+ if "type" in schema:
+ return schema_type == "object"
+
+ # Schema with properties but no explicit type is treated as object
+ if "properties" in schema:
+ return True
+
+ # Resolve local $ref definitions and recurse into the target schema.
+ ref = schema.get("$ref")
+ if not isinstance(ref, str) or not ref.startswith("#/"):
+ return False
+
+ if ref in seen_refs:
+ return False
+
+ # Walk the JSON Pointer path from the root schema, unescaping each
+ # token per RFC 6901 (~1 β†’ /, ~0 β†’ ~).
+ pointer = ref.removeprefix("#/")
+ segments = pointer.split("/")
+ target: Any = root_schema
+ for segment in segments:
+ unescaped = segment.replace("~1", "/").replace("~0", "~")
+ if not isinstance(target, dict) or unescaped not in target:
+ return False
+ target = target[unescaped]
+
+ target_schema = target
+ if not isinstance(target_schema, dict):
+ return False
+
+ return is_object_schema(
+ target_schema,
+ _root_schema=root_schema,
+ _seen_refs=seen_refs | {ref},
+ )
diff --git a/tests/server/middleware/test_caching.py b/tests/server/middleware/test_caching.py
index f3a9b8439..48fd08235 100644
--- a/tests/server/middleware/test_caching.py
+++ b/tests/server/middleware/test_caching.py
@@ -724,6 +724,28 @@ class TestCacheableToolResult:
assert cached_tool_result.is_error is True
+ def test_cached_raw_mcp_result_uses_edited_public_fields(self):
+ original = mcp_types.CallToolResult(
+ content=[mcp_types.TextContent(type="text", text="secret")],
+ structured_content={"secret": "original"},
+ _meta={"source": "backend"},
+ )
+ cached = CacheableToolResult.wrap(ToolResult.from_mcp_result(original)).unwrap()
+ edited = cached.model_copy(
+ update={
+ "content": [mcp_types.TextContent(type="text", text="redacted")],
+ "structured_content": {"secret": "redacted"},
+ "meta": {"source": "middleware"},
+ }
+ )
+
+ wire = edited.to_mcp_result()
+ assert isinstance(wire, mcp_types.CallToolResult)
+ assert isinstance(wire.content[0], mcp_types.TextContent)
+ assert wire.content[0].text == "redacted"
+ assert wire.structured_content == {"secret": "redacted"}
+ assert wire.meta == {"source": "middleware"}
+
class TestCachedPromptResult:
async def test_resource_link_survives_cache(self):
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 df311a95e..8cb732e11 100644
--- a/tests/server/providers/local_provider_tools/test_output_schema.py
+++ b/tests/server/providers/local_provider_tools/test_output_schema.py
@@ -10,10 +10,9 @@ from mcp_types import (
from pydantic import AnyUrl, BaseModel, TypeAdapter
from typing_extensions import TypeAliasType, TypedDict
-from fastmcp import FastMCP
+from fastmcp import Client, FastMCP
from fastmcp.tools.base import ToolResult
-from fastmcp.tools.function_parsing import _is_object_schema
-from fastmcp.utilities.json_schema import compress_schema
+from fastmcp.utilities.json_schema import compress_schema, is_object_schema
def _normalize_anyof_order(schema):
@@ -335,8 +334,44 @@ class TestToolOutputSchema:
assert result.structured_content == {"result": "foo"}
+ ("schema_type", "expected"),
+ [
+ ("object", True),
+ (["object", "null"], True),
+ (["object", "array"], False),
+ ("array", False),
+ ],
+)
+def test_explicit_type_decides_object_schema(schema_type: Any, expected: bool):
+ schema = {"type": schema_type, "properties": {"value": {"type": "integer"}}}
+ assert is_object_schema(schema) is expected
+
+
[email protected]("mode", ["legacy", "auto"])
+async def test_nullable_object_output_schema_is_registrable(mode: str):
+ schema = {
+ "type": ["object", "null"],
+ "properties": {"value": {"type": "integer"}},
+ }
+ mcp = FastMCP()
+
+ @mcp.tool(output_schema=schema)
+ def maybe_value() -> dict[str, int]:
+ return {"value": 1}
+
+ async with Client(mcp, mode=mode) as client:
+ advertised = (await client.list_tools())[0].output_schema
+ result = await client.call_tool("maybe_value", {})
+
+ expected_type = "object" if mode == "legacy" else ["object", "null"]
+ assert advertised is not None
+ assert advertised["type"] == expected_type
+ assert result.structured_content == {"value": 1}
+
+
class TestIsObjectSchemaRefResolution:
- """Tests for $ref resolution in _is_object_schema, including JSON Pointer
+ """Tests for $ref resolution in is_object_schema, including JSON Pointer
escaping and nested $defs paths."""
def test_simple_ref_to_object(self):
@@ -346,14 +381,14 @@ class TestIsObjectSchemaRefResolution:
"MyModel": {"type": "object", "properties": {"x": {"type": "int"}}}
},
}
- assert _is_object_schema(schema) is True
+ assert is_object_schema(schema) is True
def test_simple_ref_to_non_object(self):
schema = {
"$ref": "#/$defs/MyEnum",
"$defs": {"MyEnum": {"enum": ["a", "b"]}},
}
- assert _is_object_schema(schema) is False
+ assert is_object_schema(schema) is False
def test_nested_defs_path(self):
"""Refs like #/$defs/Outer/$defs/Inner should walk into nested dicts."""
@@ -370,7 +405,7 @@ class TestIsObjectSchemaRefResolution:
},
},
}
- assert _is_object_schema(schema) is True
+ assert is_object_schema(schema) is True
def test_nested_defs_non_object(self):
schema = {
@@ -383,7 +418,7 @@ class TestIsObjectSchemaRefResolution:
},
},
}
- assert _is_object_schema(schema) is False
+ assert is_object_schema(schema) is False
def test_json_pointer_tilde_escape(self):
"""~0 should unescape to ~ and ~1 should unescape to /."""
@@ -391,7 +426,7 @@ class TestIsObjectSchemaRefResolution:
"$ref": "#/$defs/has~1slash~0tilde",
"$defs": {"has/slash~tilde": {"type": "object", "properties": {}}},
}
- assert _is_object_schema(schema) is True
+ assert is_object_schema(schema) is True
def test_missing_nested_segment_returns_false(self):
schema = {
@@ -402,4 +437,4 @@ class TestIsObjectSchemaRefResolution:
},
},
}
- assert _is_object_schema(schema) is False
+ assert is_object_schema(schema) is False
diff --git a/tests/server/providers/proxy/test_non_object_outputs.py b/tests/server/providers/proxy/test_non_object_outputs.py
new file mode 100644
index 000000000..1eb3b508b
--- /dev/null
+++ b/tests/server/providers/proxy/test_non_object_outputs.py
@@ -0,0 +1,339 @@
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import mcp_types
+import pytest
+from jsonschema import validate
+from mcp.server.context import ServerRequestContext
+from mcp.server.lowlevel.server import Server
+from mcp.server.transport_security import TransportSecuritySettings
+
+from fastmcp import Client, FastMCP
+from fastmcp.server.middleware import Middleware
+from fastmcp.server.middleware.caching import ResponseCachingMiddleware
+from fastmcp.server.providers.proxy import ProxyClient, ProxyProvider, ProxyTool
+from fastmcp.server.transforms.tool_transform import ToolTransform
+from fastmcp.tools.base import RawStructuredToolResult, Tool, ToolResult
+from fastmcp.tools.tool_transform import ToolTransformConfig
+from fastmcp.utilities.asgi_transport import run_asgi_lifespan
+from fastmcp.utilities.tests import ASGIServer
+
+
[email protected]("mode", ["legacy", "auto"])
[email protected]("cache_results", [False, True])
[email protected]("transform_results", [False, True])
+async def test_proxy_preserves_non_object_tool_outputs_across_protocol_versions(
+ mode: str,
+ cache_results: bool,
+ transform_results: bool,
+) -> None:
+ schemas = {
+ "numbers": {"type": "array", "items": {"type": "integer"}},
+ "flag": {"type": "boolean"},
+ "record": {"type": "object", "properties": {"value": {"type": "integer"}}},
+ "matrix": {
+ "type": "array",
+ "items": {"$ref": "#/$defs/row"},
+ "$defs": {"row": {"type": "array", "items": {"type": "integer"}}},
+ },
+ "old_matrix": {
+ "type": "array",
+ "items": {"$ref": "#/definitions/row"},
+ "definitions": {"row": {"type": "array", "items": {"type": "integer"}}},
+ },
+ "missing": None,
+ "unconstrained": {},
+ "choice": {
+ "oneOf": [
+ {"type": "object", "properties": {"value": {"type": "integer"}}},
+ {"type": "array", "items": {"type": "integer"}},
+ ]
+ },
+ }
+ values = {
+ "numbers": [1, 2, 3],
+ "flag": False,
+ "record": {"value": 1},
+ "matrix": [[1, 2]],
+ "old_matrix": [[3, 4]],
+ "choice": {"value": 2},
+ "unconstrained": {"value": 3},
+ }
+ calls = {name: 0 for name in schemas}
+
+ async def list_tools(
+ ctx: ServerRequestContext[Any, Any],
+ params: mcp_types.PaginatedRequestParams | None,
+ ) -> mcp_types.ListToolsResult:
+ return mcp_types.ListToolsResult(
+ tools=[
+ mcp_types.Tool(
+ name=name,
+ input_schema={"type": "object", "properties": {}},
+ output_schema=schema,
+ )
+ for name, schema in schemas.items()
+ ]
+ )
+
+ async def call_tool(
+ ctx: ServerRequestContext[Any, Any],
+ params: mcp_types.CallToolRequestParams,
+ ) -> mcp_types.CallToolResult:
+ calls[params.name] += 1
+ if params.name == "missing":
+ return mcp_types.CallToolResult(content=[])
+ value = values[params.name]
+ return mcp_types.CallToolResult(
+ content=[mcp_types.TextContent(type="text", text=str(value))],
+ structured_content=value,
+ _meta={"source": "backend"},
+ )
+
+ backend = Server("backend", on_list_tools=list_tools, on_call_tool=call_tool)
+ app = backend.streamable_http_app(
+ stateless_http=True,
+ transport_security=TransportSecuritySettings(allowed_hosts=["127.0.0.1"]),
+ )
+ async with run_asgi_lifespan(app):
+ upstream = ASGIServer("http://127.0.0.1/mcp", app, "http")
+ proxy = FastMCP("proxy")
+ proxy.add_provider(
+ ProxyProvider(lambda: ProxyClient(upstream.transport(), mode="auto"))
+ )
+ tool_name = "renamed_numbers" if transform_results else "numbers"
+ if transform_results:
+ proxy.add_transform(
+ ToolTransform({"numbers": ToolTransformConfig(name="renamed_numbers")})
+ )
+
+ @proxy.tool(output_schema={"properties": {"value": {"type": "integer"}}})
+ def plain_record() -> dict[str, int]:
+ return {"value": 7}
+
+ @proxy.tool
+ async def nested_numbers() -> dict[str, Any]:
+ result = await proxy.call_tool(tool_name, {})
+ return {"value": result.structured_content}
+
+ if cache_results:
+ proxy.add_middleware(ResponseCachingMiddleware())
+
+ async with Client(proxy, mode=mode) as client:
+ tools = {tool.name: tool for tool in await client.list_tools()}
+ numbers = await client.call_tool(tool_name, {})
+ flag = await client.call_tool("flag", {})
+ record = await client.call_tool("record", {})
+ matrix = await client.call_tool("matrix", {})
+ old_matrix = await client.call_tool("old_matrix", {})
+ missing = await client.call_tool_mcp("missing", {})
+ choice = await client.call_tool("choice", {})
+ unconstrained = await client.call_tool("unconstrained", {})
+ plain = await client.call_tool("plain_record", {})
+ nested = await client.call_tool("nested_numbers", {})
+ if cache_results:
+ numbers_cached = await client.call_tool(tool_name, {})
+ assert numbers_cached.structured_content == numbers.structured_content
+ assert calls["numbers"] == 1
+
+ if cache_results:
+ other_mode = "auto" if mode == "legacy" else "legacy"
+ async with Client(proxy, mode=other_mode) as other_client:
+ other_numbers = await other_client.call_tool(tool_name, {})
+ assert other_numbers.structured_content == (
+ [1, 2, 3] if mode == "legacy" else {"result": [1, 2, 3]}
+ )
+ assert calls["numbers"] == 2
+
+ assert numbers.data == [1, 2, 3]
+ assert flag.data is False
+ assert record.data.value == 1
+ assert numbers.meta["source"] == "backend"
+ assert flag.meta["source"] == "backend"
+ assert record.structured_content == {"value": 1}
+ assert matrix.data == [[1, 2]]
+ assert old_matrix.data == [[3, 4]]
+ assert choice.data == {"value": 2}
+ assert unconstrained.data == {"value": 3}
+ assert missing.structured_content is None
+ assert plain.structured_content == {"value": 7}
+ assert nested.structured_content == {"value": [1, 2, 3]}
+ assert tools["plain_record"].output_schema == {
+ **({"type": "object"} if mode == "legacy" else {}),
+ "properties": {"value": {"type": "integer"}},
+ }
+ assert tools["record"].output_schema == schemas["record"]
+ if mode == "auto":
+ assert tools[tool_name].output_schema == schemas["numbers"]
+ assert tools["unconstrained"].output_schema == {}
+ assert numbers.structured_content == [1, 2, 3]
+ assert flag.structured_content is False
+ assert choice.structured_content == {"value": 2}
+ else:
+ assert tools[tool_name].output_schema["type"] == "object"
+ assert (
+ tools[tool_name].output_schema["properties"]["result"] == schemas["numbers"]
+ )
+ assert tools["unconstrained"].output_schema["type"] == "object"
+ assert tools["unconstrained"].output_schema["properties"]["result"] == {}
+ assert numbers.structured_content == {"result": [1, 2, 3]}
+ assert unconstrained.structured_content == {"result": {"value": 3}}
+ assert flag.structured_content == {"result": False}
+ assert choice.structured_content == {"result": {"value": 2}}
+ validate(matrix.structured_content, tools["matrix"].output_schema)
+ validate(old_matrix.structured_content, tools["old_matrix"].output_schema)
+
+
[email protected]("mode", ["legacy", "auto"])
+async def test_proxy_middleware_edits_reach_clients_and_cache(mode: str) -> None:
+ observed: list[Any] = []
+ backend_calls = 0
+
+ async def list_tools(
+ ctx: ServerRequestContext[Any, Any],
+ params: mcp_types.PaginatedRequestParams | None,
+ ) -> mcp_types.ListToolsResult:
+ return mcp_types.ListToolsResult(
+ tools=[
+ mcp_types.Tool(
+ name="numbers",
+ input_schema={"type": "object"},
+ output_schema={"type": "array", "items": {"type": "integer"}},
+ )
+ ]
+ )
+
+ async def call_tool(
+ ctx: ServerRequestContext[Any, Any],
+ params: mcp_types.CallToolRequestParams,
+ ) -> mcp_types.CallToolResult:
+ nonlocal backend_calls
+ backend_calls += 1
+ return mcp_types.CallToolResult(
+ content=[mcp_types.TextContent(type="text", text="original")],
+ structured_content=[1, 2, 3],
+ _meta={"source": "backend"},
+ )
+
+ class RedactMiddleware(Middleware):
+ async def on_call_tool(self, context, call_next):
+ result = await call_next(context)
+ observed.append(result.structured_content)
+ return result.model_copy(update={"structured_content": [9]})
+
+ backend = Server("backend", on_list_tools=list_tools, on_call_tool=call_tool)
+ app = backend.streamable_http_app(
+ stateless_http=True,
+ transport_security=TransportSecuritySettings(allowed_hosts=["127.0.0.1"]),
+ )
+ async with run_asgi_lifespan(app):
+ upstream = ASGIServer("http://127.0.0.1/mcp", app, "http")
+ proxy = FastMCP("proxy")
+ proxy.add_provider(
+ ProxyProvider(lambda: ProxyClient(upstream.transport(), mode="auto"))
+ )
+ proxy.add_middleware(ResponseCachingMiddleware())
+ proxy.add_middleware(RedactMiddleware())
+
+ async with Client(proxy, mode=mode) as client:
+ first = await client.call_tool("numbers", {})
+ cached = await client.call_tool("numbers", {})
+
+ assert observed == [[1, 2, 3]]
+ expected = {"result": [9]} if mode == "legacy" else [9]
+ assert first.structured_content == expected
+ assert cached.structured_content == expected
+ assert first.meta["source"] == "backend"
+ assert backend_calls == 1
+
+
+async def test_legacy_proxy_wraps_explicit_null_from_backend_model() -> None:
+ # The SDK currently omits null fields during wire serialization, so
+ # inject the backend model directly to exercise presence detection.
+ explicit_null = mcp_types.CallToolResult(content=[], structured_content=None)
+ absent = mcp_types.CallToolResult(content=[])
+ assert "structured_content" in explicit_null.model_fields_set
+ assert "structured_content" not in absent.model_fields_set
+
+ backend = FastMCP("backend")
+ proxy = FastMCP("proxy")
+ proxy.add_tool(
+ ProxyTool(
+ client_factory=lambda: ProxyClient(backend, mode="legacy"),
+ name="nullable",
+ parameters={"type": "object"},
+ output_schema={"type": "null"},
+ )
+ )
+
+ with patch.object(
+ ProxyClient,
+ "call_tool_mcp",
+ new_callable=AsyncMock,
+ return_value=explicit_null,
+ ):
+ async with Client(proxy, mode="legacy") as client:
+ result = await client.call_tool_mcp("nullable", {})
+
+ assert result.structured_content == {"result": None}
+
+
[email protected]("mode", ["legacy", "auto"])
[email protected]("transform_results", [False, True])
[email protected]("raw_output", [False, True])
+ "schema",
+ [
+ {},
+ {
+ "oneOf": [
+ {"type": "object", "properties": {"value": {"type": "integer"}}},
+ {"type": "array", "items": {"type": "integer"}},
+ ]
+ },
+ {
+ "type": ["object", "array"],
+ "properties": {"value": {"type": "integer"}},
+ },
+ ],
+)
+async def test_custom_tool_result_matches_legacy_advertised_wrapper(
+ mode: str,
+ transform_results: bool,
+ raw_output: bool,
+ schema: dict[str, Any],
+) -> None:
+ class CustomTool(Tool):
+ async def run(self, arguments: dict[str, Any]) -> ToolResult:
+ if raw_output:
+ return RawStructuredToolResult(content=[], structured_content=[1])
+ return self.convert_result({"value": 1})
+
+ server = FastMCP("custom")
+ server.add_tool(
+ CustomTool(
+ name="custom",
+ parameters={"type": "object", "properties": {}},
+ output_schema=schema,
+ )
+ )
+ tool_name = "renamed_custom" if transform_results else "custom"
+ if transform_results:
+ server.add_transform(
+ ToolTransform({"custom": ToolTransformConfig(name=tool_name)})
+ )
+
+ direct = await server.call_tool(tool_name, {})
+ expected = [1] if raw_output else {"value": 1}
+ assert direct.structured_content == expected
+
+ async with Client(server, mode=mode) as client:
+ advertised = (await client.list_tools())[0].output_schema
+ result = await client.call_tool_mcp(tool_name, {})
+
+ if mode == "legacy":
+ assert advertised["properties"]["result"] == schema
+ assert result.structured_content == {"result": expected}
+ else:
+ assert advertised == schema
+ assert result.structured_content == expected
diff --git a/tests/tools/tool_transform/test_schemas.py b/tests/tools/tool_transform/test_schemas.py
index 05471a4d9..09d70df78 100644
--- a/tests/tools/tool_transform/test_schemas.py
+++ b/tests/tools/tool_transform/test_schemas.py
@@ -138,7 +138,7 @@ class TestTransformToolOutputSchema:
):
"""A transform_fn's ToolResult is returned unchanged when the explicit
output schema is an object without a top-level "type": "object" key
- (properties-only), matching _is_object_schema classification."""
+ (properties-only), matching is_object_schema classification."""
async def custom_fn(x: int) -> ToolResult:
return ToolResult(
@@ -165,7 +165,7 @@ class TestTransformToolOutputSchema:
async def test_transform_fn_result_kept_for_root_ref_schema(self, base_string_tool):
"""A transform_fn's ToolResult is returned unchanged when the explicit
output schema is an object via a root-level $ref, matching
- _is_object_schema classification."""
+ is_object_schema classification."""
async def custom_fn(x: int) -> ToolResult:
return ToolResult(