Skip to content

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

3.0 KB
Raw Blame

Prompt Internal Types - Message and PromptResult

Version: 3.0.0 Impact: Breaking change for prompts returning mcp.types.PromptMessage

Summary

Prompts now use FastMCP's Message and PromptResult types internally, following the same pattern as resources (#2734). MCP SDK types are only used at the protocol boundary.

What Changed

Before (v2.x)

from mcp.types import PromptMessage, TextContent

@mcp.prompt
def my_prompt() -> PromptMessage:
    return PromptMessage(
        role="user",
        content=TextContent(type="text", text="Hello")
    )

After (v3.0)

from fastmcp.prompts import Message

@mcp.prompt
def my_prompt() -> Message:
    return Message("Hello")  # role defaults to "user"

Type Constraints

Prompt Function Return Types

str | list[Message | str] | PromptResult

Valid:

  • return "Hello" β†’ wrapped as single user Message
  • return [Message("Hi"), Message("Response", role="assistant")]
  • return ["Hi", "Response"] β†’ strings auto-wrapped as user Messages
  • return PromptResult(messages=[...], meta={...})

Invalid (now raises error):

  • return PromptMessage(...) β†’ Use Message instead
  • return Message(...) as single value β†’ Use PromptResult([Message(...)]) or return a list

Message Class

Message(
    content: Any,  # Auto-serializes non-str to JSON
    role: Literal["user", "assistant"] = "user"
)

Auto-Serialization:

  • str β†’ passes through as TextContent
  • dict β†’ JSON-serialized to text
  • list β†’ JSON-serialized to text
  • BaseModel β†’ JSON-serialized to text
  • TextContent / EmbeddedResource β†’ passes through directly

PromptResult Class

PromptResult(
    messages: str | list[Message],  # str wrapped as single Message
    description: str | None = None,
    meta: dict[str, Any] | None = None
)

Why This Change?

  1. Simpler API - Message("Hello") vs PromptMessage(role="user", content=TextContent(type="text", text="Hello"))
  2. Auto-serialization - Dicts/lists/models automatically become JSON
  3. Consistent with resources - Same pattern as ResourceContent/ResourceResult
  4. Type safety - Strict typing catches errors at development time

Migration Guide

Simple Message

# Before
from mcp.types import PromptMessage, TextContent
return PromptMessage(role="user", content=TextContent(type="text", text="Hello"))

# After
from fastmcp.prompts import Message
return Message("Hello")

Conversation

# Before
return [
    PromptMessage(role="user", content=TextContent(type="text", text="Hi")),
    PromptMessage(role="assistant", content=TextContent(type="text", text="Hello!")),
]

# After
return [
    Message("Hi"),
    Message("Hello!", role="assistant"),
]

With Metadata

from fastmcp.prompts import Message, PromptResult

return PromptResult(
    messages=[Message("Analyze this")],
    meta={"priority": "high"}
)

PR

  • #2738 - Introduce Message and PromptResult as canonical prompt types