Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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,10 +210,10 @@

## 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"

Check warning on line 216 in docs/servers/structured-output.md

View check run for this annotation

Claude / Claude Code Review

[quality] nit: docs describe the content-type opt-out as "alone or inside a `list` or union", but `_contains_content_type()` matches any generic parameterization (tuple, dict, nested Annotated), and the unchanged recap bullet still claims `dict[str, ...]`

[quality] nit: docs describe the content-type opt-out as "alone or inside a `list` or union", but `_contains_content_type()` matches any generic parameterization (tuple, dict, nested Annotated), and the unchanged recap bullet still claims `dict[str, ...]` returns stay structured
Comment thread
maxisbey marked this conversation as resolved.
Resolved
```

`Station` sets `name` and `online` inside `__init__`, but the *class* declares nothing. The SDK reads class annotations, finds none, and gives up.
Expand All @@ -240,6 +240,6 @@
* 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()
Comment thread
maxisbey marked this conversation as resolved.
Resolved
super().__init__(content=content, **kwargs)


Expand All @@ -38,7 +47,7 @@ class UserMessage(Message):

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 @@ class AssistantMessage(Message):

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
39 changes: 37 additions & 2 deletions src/mcp/server/mcpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,12 +890,47 @@ def decorator(fn: _CallableT) -> _CallableT:

return decorator

def add_prompt(self, prompt: Prompt) -> None:
@overload
def add_prompt(self, prompt: Prompt) -> None: ...

@overload
def add_prompt(
self,
fn: Callable[..., Any],
/,
*,
name: str | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
) -> None: ...

def add_prompt(
self,
prompt: Prompt | Callable[..., Any],
*,
name: str | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
) -> None:
"""Add a prompt to the server.

Pass the function that renders the prompt: its name, docstring and parameters become
the prompt's name, description and arguments, exactly as with `@prompt()`. A ready-made
`Prompt` instance is registered as-is.

Args:
prompt: A Prompt instance to add
prompt: The function to register as a prompt, or a `Prompt` instance
name: Optional name for the prompt (defaults to the function name)
title: Optional human-readable title for the prompt
description: Optional description (defaults to the function's docstring)
icons: Optional list of icons for the prompt
"""
if not isinstance(prompt, Prompt):
prompt = Prompt.from_function(prompt, name=name, title=title, description=description, icons=icons)
elif any(arg is not None for arg in (name, title, description, icons)):
raise TypeError("name, title, description and icons can only be set when registering a function")
self._prompt_manager.add_prompt(prompt)

def remove_prompt(self, name: str) -> None:
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)

Check failure on line 43 in src/mcp/server/mcpserver/utilities/func_metadata.py

View check run for this annotation

Claude / Claude Code Review

_contains_content_type() recurses into the type args of ANY parameterized generic, so a user-defined generic data model parameterized by a content block (e.g. a generic TypedDict `Box[TextContent]` or a Generic[T] dataclass) is silently reclassified as un

_contains_content_type() recurses into the type args of ANY parameterized generic, so a user-defined generic data model parameterized by a content block (e.g. a generic TypedDict `Box[TextContent]` or a Generic[T] dataclass) is silently reclassified as unstructured — a regression from the base commit, where such annotations produced a wrapped output model and published an outputSchema. This contradicts the change's own invariant (pinned by test_model_with_a_content_block_field_stays_structured
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,6 +358,12 @@
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(
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
Loading
Loading