Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/servers/structured-output.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ The opposite, `structured_output=True`, turns the automatic detection into a req

## A class without type hints

There is one way to end up unstructured without asking for it: return a class that has **no annotations on its body**.
Content blocks and media (`TextContent`, `EmbeddedResource`, `Image`, `Audio` and friends, alone or inside a `list` or union) are not structured automatically: they are for the model to read (**[Images, audio & icons](media.md)** covers `Image` and `Audio`). Beyond those, there is one way to end up unstructured without asking for it: return a class that has **no annotations on its body**.

```python title="server.py" hl_lines="6-9"
--8<-- "docs_src/structured_output/tutorial009.py"
Comment thread
maxisbey marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -240,6 +240,6 @@ There is one way to end up unstructured without asking for it: return a class th
* Scalars, lists, tuples and unions are wrapped in `{"result": ...}`. Models, `TypedDict`s, dataclasses, annotated classes and `dict[str, ...]` are objects already and stay as they are.
* Every result carries `content` (text, for the model) **and** `structured_content` (data, for the application).
* What you return is validated against the schema. A mismatch is a tool error, not a corrupt result.
* `structured_output=False` opts a tool out. A class without type hints opts out silently; watch for it.
* `structured_output=False` opts a tool out. Content blocks, `Image` and `Audio` opt out by default; a class without type hints opts out silently, so watch for it.

You now own everything a tool can say back. Next, the second primitive: **[Resources](resources.md)**.
1 change: 0 additions & 1 deletion src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,5 +946,4 @@ async def list_tools(
@deprecated("The roots capability is deprecated as of 2026-07-28 (SEP-2577).", category=MCPDeprecationWarning)
async def send_roots_list_changed(self) -> None:
"""Send a notification that the roots list has changed."""
# TODO(Marcelo): Currently, there is no way for the server to handle this. We should add support.
await self.session.send_roots_list_changed() # pyright: ignore[reportDeprecated]
4 changes: 4 additions & 0 deletions src/mcp/server/mcpserver/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
)

from .context import Context
from .prompts.base import AssistantMessage, Message, UserMessage
Comment thread
maxisbey marked this conversation as resolved.
Resolved
from .resolve import (
AcceptedElicitation,
CancelledElicitation,
Expand All @@ -32,6 +33,9 @@
"Context",
"Image",
"Audio",
"Message",
"UserMessage",
"AssistantMessage",
"Icon",
"Resolve",
"Elicit",
Expand Down
17 changes: 13 additions & 4 deletions src/mcp/server/mcpserver/prompts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from mcp.server.mcpserver.utilities.context_injection import find_context_parameter, inject_context
from mcp.server.mcpserver.utilities.func_metadata import func_metadata
from mcp.server.mcpserver.utilities.types import Audio, Image
from mcp.shared._callable_inspection import is_async_callable
from mcp.shared.exceptions import MCPError

Expand All @@ -22,14 +23,22 @@


class Message(BaseModel):
"""Base class for all prompt messages."""
"""Base class for all prompt messages.

`content` may be a plain string (wrapped in `TextContent`), an `Image` or `Audio`
helper (converted to `ImageContent` / `AudioContent`), or any ready-made content block.
"""
Comment thread
maxisbey marked this conversation as resolved.
Resolved

role: Literal["user", "assistant"]
content: ContentBlock

def __init__(self, content: str | ContentBlock, **kwargs: Any):
def __init__(self, content: str | ContentBlock | Image | Audio, **kwargs: Any):
Comment thread
maxisbey marked this conversation as resolved.
Resolved
if isinstance(content, str):
content = TextContent(type="text", text=content)
elif isinstance(content, Image):
content = content.to_image_content()
elif isinstance(content, Audio):
content = content.to_audio_content()

Check warning on line 41 in src/mcp/server/mcpserver/prompts/base.py

View check run for this annotation

Claude / Claude Code Review

[quality] Message.__init__ re-implements the Image/Audio-to-content-block conversion that already exists in func_metadata._convert_to_content (src/mcp/server/mcpserver/utilities/func_metadata.py:576-580): two independent isinstance chains now map Image ->

[quality] Message.__init__ re-implements the Image/Audio-to-content-block conversion that already exists in func_metadata._convert_to_content (src/mcp/server/mcpserver/utilities/func_metadata.py:576-580): two independent isinstance chains now map Image -> to_image_content() and Audio -> to_audio_content(). A tiny shared helper (e.g. in utilities/types.py, next to the Image/Audio classes) that normalizes one value to a ContentBlock would keep the tool path and the prompt path in lockstep. This is
Comment thread
maxisbey marked this conversation as resolved.
Resolved
super().__init__(content=content, **kwargs)


Expand All @@ -38,7 +47,7 @@

role: Literal["user", "assistant"] = "user"

def __init__(self, content: str | ContentBlock, **kwargs: Any):
def __init__(self, content: str | ContentBlock | Image | Audio, **kwargs: Any):
super().__init__(content=content, **kwargs)


Expand All @@ -47,7 +56,7 @@

role: Literal["user", "assistant"] = "assistant"

def __init__(self, content: str | ContentBlock, **kwargs: Any):
def __init__(self, content: str | ContentBlock | Image | Audio, **kwargs: Any):
super().__init__(content=content, **kwargs)


Expand Down
19 changes: 19 additions & 0 deletions src/mcp/server/mcpserver/utilities/func_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@
return isinstance(obj, type) and issubclass(obj, InputRequiredResult)


_CONTENT_TYPES = (*get_args(ContentBlock), Image, Audio)


def _contains_content_type(tp: Any) -> bool:
Comment thread
maxisbey marked this conversation as resolved.
Resolved
"""Whether `tp` is, or is parameterized by, a content block class or the `Image`/`Audio` helpers."""
if get_origin(tp) is not None:
return any(_contains_content_type(arg) for arg in get_args(tp))
return isinstance(tp, type) and issubclass(tp, _CONTENT_TYPES)
Comment thread
maxisbey marked this conversation as resolved.
Resolved
Comment thread
maxisbey marked this conversation as resolved.
Resolved


class StrictJsonSchema(GenerateJsonSchema):
"""A JSON schema generator that raises exceptions instead of emitting warnings.

Expand Down Expand Up @@ -222,6 +232,9 @@
- TypedDict - converted to a Pydantic model with same fields
- Dataclasses and other annotated classes - converted to Pydantic models
- Generic types (list, dict, Union, etc.) - wrapped in a model with a 'result' field
- Content blocks (TextContent, EmbeddedResource, ...), Image and Audio, anywhere in the
annotation - unstructured when auto-detecting; structured_output=True bypasses this rule
(a content block then publishes its own schema; Image/Audio have none and raise)

Returns:
A FuncMetadata object containing:
Expand Down Expand Up @@ -345,7 +358,13 @@
else:
original_annotation = effective_annotation

if structured_output is None and _contains_content_type(return_type_expr):
# Content blocks and the Image/Audio helpers are what the model reads, not data for the
# application: deriving a schema would publish the block's own model as output_schema and
# echo every block into structured_content. structured_output=True still forces one.
return FuncMetadata(arg_model=arguments_model)

output_model, output_schema, wrap_output = _try_create_model_and_schema(

Check notice on line 367 in src/mcp/server/mcpserver/utilities/func_metadata.py

View check run for this annotation

Claude / Claude Code Review

Pre-existing: with structured_output=True, a return annotation like list[Image] or tuple[Audio, ...] makes _try_create_model_and_schema raise a raw PydanticSchemaGenerationError (wrapper model built outside the try) instead of the intended InvalidSignatur

Pre-existing: with structured_output=True, a return annotation like list[Image] or tuple[Audio, ...] makes _try_create_model_and_schema raise a raw PydanticSchemaGenerationError (wrapper model built outside the try) instead of the intended InvalidSignature; the new content-type rule only shields the structured_output=None path, and the new docstring at line 237 says such annotations "raise" without noting it is an unhandled pydantic internal error.
Comment thread
maxisbey marked this conversation as resolved.
Resolved
original_annotation, return_type_expr, func.__name__
)

Expand Down
19 changes: 18 additions & 1 deletion tests/server/mcpserver/prompts/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@

import pytest
from mcp_types import (
AudioContent,
ElicitRequest,
ElicitRequestFormParams,
EmbeddedResource,
ImageContent,
InputRequiredResult,
TextContent,
TextResourceContents,
)

from mcp.server.mcpserver import Context
from mcp.server.mcpserver import Audio, Context, Image
from mcp.server.mcpserver.prompts.base import AssistantMessage, Message, Prompt, UserMessage


Expand Down Expand Up @@ -243,3 +245,18 @@ def asking_prompt() -> InputRequiredResult:
prompt = Prompt.from_function(asking_prompt)
result = await prompt.render(None, Context())
assert result is sentinel


@pytest.mark.parametrize(
("helper", "expected"),
[
(Image(data=b"img", format="png"), ImageContent(type="image", data="aW1n", mime_type="image/png")),
(Audio(data=b"snd", format="wav"), AudioContent(type="audio", data="c25k", mime_type="audio/wav")),
],
)
def test_message_converts_image_and_audio_helpers_to_content_blocks(
helper: Image | Audio, expected: ImageContent | AudioContent
) -> None:
"""SDK-defined: prompt messages accept the same `Image`/`Audio` helpers tools return."""
assert UserMessage(helper).content == expected
assert AssistantMessage(content=helper).content == expected
58 changes: 57 additions & 1 deletion tests/server/mcpserver/test_func_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
import annotated_types
import pytest
from dirty_equals import IsPartialDict
from mcp_types import CallToolResult, InputRequiredResult
from mcp_types import CallToolResult, ContentBlock, EmbeddedResource, InputRequiredResult, TextContent
from pydantic import BaseModel, Field

from mcp.server.mcpserver import Audio, Image
from mcp.server.mcpserver.exceptions import InvalidSignature
from mcp.server.mcpserver.utilities.func_metadata import func_metadata

Expand Down Expand Up @@ -854,6 +855,61 @@ def func_returning_unannotated() -> UnannotatedClass: # pragma: no cover
assert meta.output_schema is None


def _returns_block() -> EmbeddedResource:
raise NotImplementedError


def _returns_blocks() -> list[ContentBlock]:
raise NotImplementedError


def _returns_strings_and_images() -> list[str | Image]:
raise NotImplementedError


def _returns_audio_clips() -> tuple[Audio, ...]:
raise NotImplementedError


def _returns_call_tool_result_annotated_with_blocks() -> Annotated[CallToolResult, list[TextContent]]:
raise NotImplementedError


@pytest.mark.parametrize(
"tool",
[
_returns_block,
_returns_blocks,
_returns_strings_and_images,
_returns_audio_clips,
_returns_call_tool_result_annotated_with_blocks,
],
)
def test_content_block_return_annotation_yields_no_output_schema(tool: Callable[..., Any]):
"""SDK-defined: content blocks and the Image/Audio helpers anywhere in the return annotation are
presentation, not data, so auto-detection derives no output schema (and `list[str | Image]` /
`tuple[Audio, ...]`, which pydantic cannot build a schema for, register instead of raising)."""
assert func_metadata(tool).output_schema is None


def test_structured_output_true_overrides_the_content_block_rule():
"""SDK-defined: the explicit flag still publishes the block's own schema for callers who want it."""
assert func_metadata(_returns_block, structured_output=True).output_model is EmbeddedResource


def test_model_with_a_content_block_field_stays_structured():
"""SDK-defined: only the return annotation is inspected for content types, never a model's fields."""

class Report(BaseModel):
summary: str
attachment: EmbeddedResource

def tool() -> Report:
raise NotImplementedError

assert func_metadata(tool).output_model is Report


def test_tool_call_result_is_unstructured_and_not_converted():
def func_returning_call_tool_result() -> CallToolResult:
return CallToolResult(content=[])
Expand Down
26 changes: 6 additions & 20 deletions tests/server/mcpserver/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,20 +437,8 @@ async def test_tool_mixed_content(self):
assert isinstance(content3, AudioContent)
assert content3.mime_type == "audio/wav"
assert content3.data == "def"
assert result.structured_content is not None
assert "result" in result.structured_content
structured_result = result.structured_content["result"]
assert len(structured_result) == 3

expected_content = [
{"type": "text", "text": "Hello"},
{"type": "image", "data": "abc", "mimeType": "image/png"},
{"type": "audio", "data": "def", "mimeType": "audio/wav"},
]

for i, expected in enumerate(expected_content):
for key, value in expected.items():
assert structured_result[i][key] == value
# Content blocks are for the model, not data: no output schema, nothing echoed as structured
assert result.structured_content is None

async def test_tool_mixed_list_with_audio_and_image(self, tmp_path: Path):
"""Test that lists containing Image objects and other types are handled
Expand All @@ -463,10 +451,8 @@ async def test_tool_mixed_list_with_audio_and_image(self, tmp_path: Path):
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"test audio data")

# TODO(Marcelo): It seems if we add the proper type hint, it generates an invalid JSON schema.
# We need to fix this.
def mixed_list_fn() -> list: # type: ignore
return [ # type: ignore
def mixed_list_fn() -> list[str | Image | Audio | dict[str, str] | TextContent]:
return [
"text message",
Image(image_path),
Audio(audio_path),
Expand All @@ -475,7 +461,7 @@ def mixed_list_fn() -> list: # type: ignore
]

mcp = MCPServer()
mcp.add_tool(mixed_list_fn) # type: ignore
mcp.add_tool(mixed_list_fn)
async with Client(mcp) as client:
result = await client.call_tool("mixed_list_fn", {})
assert len(result.content) == 5
Expand All @@ -501,7 +487,7 @@ def mixed_list_fn() -> list: # type: ignore
content5 = result.content[4]
assert isinstance(content5, TextContent)
assert content5.text == "direct content"
# Check structured content - untyped list with Image objects should NOT have structured output
# Image/Audio/TextContent in the annotation: no output schema, so nothing echoed as structured
assert result.structured_content is None

async def test_tool_structured_output_basemodel(self):
Expand Down
Loading