FastMCP: Defining Prompts
Relevant source files
The following files were used as context for generating this wiki page:
In the FastMCP framework, "Prompts" are server-defined, parameterizable templates used to generate a sequence of messages. This feature allows a server to expose pre-defined conversational structures or instructions that a client can request and use, often to prime a large language model. Prompts are defined on the server using a simple decorator on a Python function and are managed internally by a PromptManager.
Clients can discover available prompts, request a specific prompt with arguments, and receive the rendered messages. This system provides a clean separation of concerns, allowing prompt logic to be maintained on the server while clients can dynamically utilize them without hardcoding the content.
The @mcp.prompt Decorator
The primary way to define a prompt is by using the @mcp.prompt() decorator on a function within a FastMCP application instance. The decorated function contains the logic for generating the prompt content.
Sources: tests/server/fastmcp/test_server.py:1003-1008
The decorator takes several optional arguments to configure the prompt's metadata.
| Parameter | Type | Description |
|---|---|---|
name | str | The unique name for the prompt. If not provided, it defaults to the function's name. |
description | str | A description of the prompt's purpose. If not provided, it defaults to the function's docstring. |
title | str | A user-friendly display name for the prompt. |
Sources: tests/server/fastmcp/test_server.py:1011-1030, tests/server/fastmcp/test_title.py:40-45
Here is a basic example:
mcp = FastMCP()
@mcp.prompt(title="Code Review Helper", description="Generates a prompt to review code.")
def review_code(code: str) -> str:
"""This docstring is used if no description is provided."""
return f"Please review this code:\n\n{code}"
Sources: tests/server/fastmcp/test_integration.py:270-274, tests/server/fastmcp/test_server.py:1051-1055
It is important to use the decorator with parentheses, e.g., @mcp.prompt(), even if no arguments are passed. Using it without parentheses (@mcp.prompt) will result in a TypeError.
Sources: tests/server/fastmcp/test_server.py:1032-1037
Architecture and Management
The prompt system is built around two key classes: Prompt and PromptManager, which are orchestrated by the main FastMCP instance.
This diagram shows the relationship between the main components.
The Prompt Class
The Prompt class encapsulates a single prompt definition. It is typically created via the Prompt.from_function() class method, which is what the @mcp.prompt decorator uses internally.
This diagram shows the key attributes and methods of the Prompt class.
The render() method is responsible for executing the decorated function with the provided arguments and normalizing the output into a list of Message objects.
Sources: src/mcp/server/fastmcp/prompts/base.py:159-161
The PromptManager Class
The PromptManager is responsible for storing and managing all prompts registered with a FastMCP server. Each FastMCP instance has its own _prompt_manager.
Key responsibilities include:
- Adding Prompts: The
add_prompt()method registers aPromptobject. It warns if a prompt with the same name is added, unlesswarn_on_duplicate_promptsis set toFalse. - Listing Prompts: The
list_prompts()method returns all registered prompts. - Retrieving Prompts: The
get_prompt()method retrieves a single prompt by its name. - Rendering Prompts: The
render_prompt()method finds a prompt by name, validates arguments, and calls itsrender()method.
Sources: src/mcp/server/fastmcp/prompts/manager.py, tests/server/fastmcp/prompts/test_manager.py
Prompt Rendering and Return Types
The function decorated with @mcp.prompt can return several types of data, which are automatically normalized into a standardized list of Message objects (UserMessage or AssistantMessage).
The following return types are supported:
str: Normalized to a singleUserMessagecontainingTextContent.list[str]: Normalized to a list ofUserMessageobjects.Message: A singleUserMessageorAssistantMessageobject, wrapped in a list.list[Message]: A list ofMessageobjects, passed through as-is.dict: A dictionary that can be parsed into aMessage.
This diagram illustrates the normalization process.
Prompt Arguments
Function parameters in the decorated function become the arguments for the prompt. Type hints are required and are used to determine the argument's type. Parameters with default values are considered optional.
@mcp.prompt()
def simple_prompt(
topic: str, # Required argument
context: str | None = None # Optional argument
) -> list[str]:
# ... implementation
If a client calls get_prompt without providing a required argument, the server will raise an error.
Sources: tests/server/fastmcp/test_server.py:1068-1077, tests/server/fastmcp/prompts/test_manager.py:70-78
Rich Content
Prompts are not limited to text. A prompt function can return Message objects containing rich content, such as EmbeddedResource. This allows prompts to reference other server resources directly.
from mcp.server.fastmcp.prompts.base import UserMessage
from mcp.types import EmbeddedResource, TextResourceContents
from pydantic import AnyUrl
@mcp.prompt()
def fn() -> UserMessage:
return UserMessage(
content=EmbeddedResource(
type="resource",
resource=TextResourceContents(
uri=AnyUrl("file://file.txt"),
text="File contents",
mimeType="text/plain",
),
)
)
Sources: tests/server/fastmcp/prompts/test_base.py:90-108
Client Interaction
Clients interact with prompts through two main MCP methods: list_prompts and get_prompt.
This sequence diagram shows the typical flow of a client discovering and using a prompt.
list_prompts: The client requests the list of all available prompts. The server returns aListPromptsResultcontaining an array ofPromptmetadata objects, including their names, descriptions, and arguments.
Sources: tests/server/fastmcp/test_server.py:1040-1050get_prompt: The client requests a specific prompt by name, providing a dictionary of arguments. The server uses thePromptManagerto find and render the prompt, returning aGetPromptResultwhich contains the final list ofMessageobjects.
Sources: tests/server/fastmcp/test_server.py:1053-1065
If the client requests an unknown prompt or fails to provide required arguments, the server responds with an McpError.
Sources: tests/server/fastmcp/test_server.py:1102-1114
Conclusion
The prompt system in FastMCP provides a structured and powerful mechanism for servers to define and expose reusable, dynamic message templates. By using the @mcp.prompt decorator, developers can easily create prompts from simple Python functions, supporting various return types, arguments, and rich content. The clear client-server protocol for listing and retrieving prompts enables flexible and maintainable applications where complex prompt engineering logic is centralized on the server.