Skip to content

chore: create union for working with message content #939

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,7 @@ def main(
app = Server("mcp-streamable-http-stateless-demo")

@app.call_tool()
async def call_tool(
name: str, arguments: dict
) -> list[
types.TextContent
| types.ImageContent
| types.AudioContent
| types.EmbeddedResource
]:
async def call_tool(name: str, arguments: dict) -> list[types.Content]:
ctx = app.request_context
interval = arguments.get("interval", 1.0)
count = arguments.get("count", 5)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,7 @@ def main(
app = Server("mcp-streamable-http-demo")

@app.call_tool()
async def call_tool(
name: str, arguments: dict
) -> list[
types.TextContent
| types.ImageContent
| types.AudioContent
| types.EmbeddedResource
]:
async def call_tool(name: str, arguments: dict) -> list[types.Content]:
ctx = app.request_context
interval = arguments.get("interval", 1.0)
count = arguments.get("count", 5)
Expand Down
13 changes: 2 additions & 11 deletions examples/servers/simple-tool/mcp_simple_tool/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@

async def fetch_website(
url: str,
) -> list[
types.TextContent | types.ImageContent | types.AudioContent | types.EmbeddedResource
]:
) -> list[types.Content]:
headers = {
"User-Agent": "MCP Test Server (github.com/modelcontextprotocol/python-sdk)"
}
Expand All @@ -31,14 +29,7 @@ def main(port: int, transport: str) -> int:
app = Server("mcp-website-fetcher")

@app.call_tool()
async def fetch_tool(
name: str, arguments: dict
) -> list[
types.TextContent
| types.ImageContent
| types.AudioContent
| types.EmbeddedResource
]:
async def fetch_tool(name: str, arguments: dict) -> list[types.Content]:
if name != "fetch":
raise ValueError(f"Unknown tool: {name}")
if "url" not in arguments:
Expand Down
12 changes: 5 additions & 7 deletions src/mcp/server/fastmcp/prompts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@
import pydantic_core
from pydantic import BaseModel, Field, TypeAdapter, validate_call

from mcp.types import AudioContent, EmbeddedResource, ImageContent, TextContent

CONTENT_TYPES = TextContent | ImageContent | AudioContent | EmbeddedResource
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will accept this PR as I don't think anyone is importing this directly.

from mcp.types import Content, TextContent


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

role: Literal["user", "assistant"]
content: CONTENT_TYPES
content: Content

def __init__(self, content: str | CONTENT_TYPES, **kwargs: Any):
def __init__(self, content: str | Content, **kwargs: Any):
if isinstance(content, str):
content = TextContent(type="text", text=content)
super().__init__(content=content, **kwargs)
Expand All @@ -29,7 +27,7 @@ class UserMessage(Message):

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

def __init__(self, content: str | CONTENT_TYPES, **kwargs: Any):
def __init__(self, content: str | Content, **kwargs: Any):
super().__init__(content=content, **kwargs)


Expand All @@ -38,7 +36,7 @@ class AssistantMessage(Message):

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

def __init__(self, content: str | CONTENT_TYPES, **kwargs: Any):
def __init__(self, content: str | Content, **kwargs: Any):
super().__init__(content=content, **kwargs)


Expand Down
12 changes: 4 additions & 8 deletions src/mcp/server/fastmcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@
from mcp.shared.context import LifespanContextT, RequestContext, RequestT
from mcp.types import (
AnyFunction,
AudioContent,
EmbeddedResource,
Content,
GetPromptResult,
ImageContent,
TextContent,
ToolAnnotations,
)
Expand Down Expand Up @@ -256,9 +254,7 @@ def get_context(self) -> Context[ServerSession, object, Request]:
request_context = None
return Context(request_context=request_context, fastmcp=self)

async def call_tool(
self, name: str, arguments: dict[str, Any]
) -> Sequence[TextContent | ImageContent | AudioContent | EmbeddedResource]:
async def call_tool(self, name: str, arguments: dict[str, Any]) -> Sequence[Content]:
"""Call a tool by name with arguments."""
context = self.get_context()
result = await self._tool_manager.call_tool(name, arguments, context=context)
Expand Down Expand Up @@ -842,12 +838,12 @@ async def get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -

def _convert_to_content(
result: Any,
) -> Sequence[TextContent | ImageContent | AudioContent | EmbeddedResource]:
) -> Sequence[Content]:
"""Convert a result to a sequence of content objects."""
if result is None:
return []

if isinstance(result, TextContent | ImageContent | AudioContent | EmbeddedResource):
if isinstance(result, Content):
return [result]

if isinstance(result, Image):
Expand Down
4 changes: 1 addition & 3 deletions src/mcp/server/lowlevel/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,9 +384,7 @@ def call_tool(self):
def decorator(
func: Callable[
...,
Awaitable[
Iterable[types.TextContent | types.ImageContent | types.AudioContent | types.EmbeddedResource]
],
Awaitable[Iterable[types.Content]],
],
):
logger.debug("Registering handler for CallToolRequest")
Expand Down
7 changes: 5 additions & 2 deletions src/mcp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,11 +667,14 @@ class EmbeddedResource(BaseModel):
model_config = ConfigDict(extra="allow")


Content = TextContent | ImageContent | AudioContent | EmbeddedResource


class PromptMessage(BaseModel):
"""Describes a message returned as part of a prompt."""

role: Role
content: TextContent | ImageContent | AudioContent | EmbeddedResource
content: Content
model_config = ConfigDict(extra="allow")


Expand Down Expand Up @@ -787,7 +790,7 @@ class CallToolRequest(Request[CallToolRequestParams, Literal["tools/call"]]):
class CallToolResult(Result):
"""The server's response to a tool call."""

content: list[TextContent | ImageContent | AudioContent | EmbeddedResource]
content: list[Content]
isError: bool = False


Expand Down
4 changes: 2 additions & 2 deletions tests/issues/test_88_random_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from mcp.client.session import ClientSession
from mcp.server.lowlevel import Server
from mcp.shared.exceptions import McpError
from mcp.types import AudioContent, EmbeddedResource, ImageContent, TextContent
from mcp.types import Content, TextContent


@pytest.mark.anyio
Expand All @@ -31,7 +31,7 @@ async def test_notification_validation_error(tmp_path: Path):
slow_request_complete = anyio.Event()

@server.call_tool()
async def slow_tool(name: str, arg) -> Sequence[TextContent | ImageContent | AudioContent | EmbeddedResource]:
async def slow_tool(name: str, arg) -> Sequence[Content]:
nonlocal request_count
request_count += 1

Expand Down
6 changes: 4 additions & 2 deletions tests/server/fastmcp/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from starlette.routing import Mount, Route

from mcp.server.fastmcp import Context, FastMCP
from mcp.server.fastmcp.prompts.base import EmbeddedResource, Message, UserMessage
from mcp.server.fastmcp.prompts.base import Message, UserMessage
from mcp.server.fastmcp.resources import FileResource, FunctionResource
from mcp.server.fastmcp.utilities.types import Image
from mcp.shared.exceptions import McpError
Expand All @@ -18,6 +18,8 @@
from mcp.types import (
AudioContent,
BlobResourceContents,
Content,
EmbeddedResource,
ImageContent,
TextContent,
TextResourceContents,
Expand Down Expand Up @@ -192,7 +194,7 @@ def image_tool_fn(path: str) -> Image:
return Image(path)


def mixed_content_tool_fn() -> list[TextContent | ImageContent | AudioContent]:
def mixed_content_tool_fn() -> list[Content]:
return [
TextContent(type="text", text="Hello"),
ImageContent(type="image", data="abc", mimeType="image/png"),
Expand Down
Loading