mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-23 05:54:19 +02:00
Update docs
This commit is contained in:
parent
5520102821
commit
c412a63d4e
7 changed files with 575 additions and 46 deletions
|
|
@ -288,28 +288,100 @@ Use `async def` when your tool needs to perform operations that might wait for e
|
|||
|
||||
### Return Values
|
||||
|
||||
#### Output Conversion
|
||||
|
||||
FastMCP automatically converts the value returned by your function into the appropriate MCP content format for the client:
|
||||
FastMCP tools can return data in two complementary formats: **traditional content blocks** (like text and images) and **structured outputs** (machine-readable JSON). When you add return type annotations, FastMCP automatically generates **output schemas** to validate the structured data and enables clients to deserialize results back to Python objects.
|
||||
|
||||
- **`str`**: Sent as `TextContent`.
|
||||
- **`dict`, `list`, Pydantic `BaseModel`**: Serialized to a JSON string and sent as `TextContent`.
|
||||
- **`bytes`**: Base64 encoded and sent as `BlobResourceContents` (often within an `EmbeddedResource`).
|
||||
- **`fastmcp.utilities.types.Image`**: A helper class for easily returning image data. Sent as `ImageContent`.
|
||||
- **`fastmcp.utilities.types.Audio`**: A helper class for easily returning audio data. Sent as `AudioContent`.
|
||||
- **`fastmcp.utilities.types.File`**: A helper class for easily returning binary data as base64-encoded content. Sent as `EmbeddedResource`.
|
||||
- **A list of any of the above**: Automatically converts each item appropriately.
|
||||
- **`None`**: Results in an empty response (no content is sent back to the client).
|
||||
Understanding how these three concepts work together:
|
||||
|
||||
FastMCP will attempt to serialize other types to a string if possible.
|
||||
- **Return Values**: What your Python function returns (determines both content blocks and structured data)
|
||||
- **Structured Outputs**: JSON data sent alongside traditional content for machine processing
|
||||
- **Output Schemas**: JSON Schema declarations that describe and validate the structured output format
|
||||
|
||||
#### Output Schemas
|
||||
The following sections explain each concept in detail.
|
||||
|
||||
#### Content Blocks
|
||||
|
||||
FastMCP automatically converts tool return values into appropriate MCP content blocks:
|
||||
|
||||
- **`str`**: Sent as `TextContent`
|
||||
- **`bytes`**: Base64 encoded and sent as `BlobResourceContents` (within an `EmbeddedResource`)
|
||||
- **`fastmcp.utilities.types.Image`**: Sent as `ImageContent`
|
||||
- **`fastmcp.utilities.types.Audio`**: Sent as `AudioContent`
|
||||
- **`fastmcp.utilities.types.File`**: Sent as base64-encoded `EmbeddedResource`
|
||||
- **A list of any of the above**: Converts each item appropriately
|
||||
- **`None`**: Results in an empty response
|
||||
|
||||
#### Structured Output
|
||||
|
||||
<VersionBadge version="2.10.0" />
|
||||
|
||||
FastMCP will automatically generate MCP [output schemas](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema) for your tools based on their return type annotations. This helps MCP clients understand what type of data to expect from your tool, enabling better validation and type safety.
|
||||
The 6/18/2025 MCP spec update [introduced](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content) structured content, which is a new way to return data from tools. Structured content is a JSON object that is sent alongside traditional content. FastMCP automatically creates structured outputs alongside traditional content when your tool returns data that has a JSON object representation. This provides machine-readable JSON data that clients can deserialize back to Python objects.
|
||||
|
||||
When you add a return type annotation to your tool function, FastMCP will generate a JSON schema describing the expected output format and include it in the tool definition sent to MCP clients.
|
||||
**Automatic Structured Content Rules:**
|
||||
- **Object-like results** (`dict`, Pydantic models, dataclasses) → Always become structured content (even without output schema)
|
||||
- **Non-object results** (`int`, `str`, `list`) → Only become structured content if there's an output schema to validate/serialize them
|
||||
- **All results** → Always become traditional content blocks for backward compatibility
|
||||
|
||||
<Note>
|
||||
This automatic behavior enables clients to receive machine-readable data alongside human-readable content without requiring explicit output schemas for object-like returns.
|
||||
</Note>
|
||||
|
||||
##### Object-like Results (Automatic Structured Content)
|
||||
|
||||
<CodeGroup>
|
||||
```python Dict Return (No Schema Needed)
|
||||
@mcp.tool
|
||||
def get_user_data(user_id: str) -> dict:
|
||||
"""Get user data without type annotation."""
|
||||
return {"name": "Alice", "age": 30, "active": True}
|
||||
```
|
||||
|
||||
```json Traditional Content
|
||||
"{\n \"name\": \"Alice\",\n \"age\": 30,\n \"active\": true\n}"
|
||||
```
|
||||
|
||||
```json Structured Content (Automatic)
|
||||
{
|
||||
"name": "Alice",
|
||||
"age": 30,
|
||||
"active": true
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
##### Non-object Results (Schema Required)
|
||||
|
||||
<CodeGroup>
|
||||
```python Integer Return (No Schema)
|
||||
@mcp.tool
|
||||
def calculate_sum(a: int, b: int):
|
||||
"""Calculate sum without return annotation."""
|
||||
return a + b # Returns 8
|
||||
```
|
||||
|
||||
```json Traditional Content Only
|
||||
"8"
|
||||
```
|
||||
|
||||
```python Integer Return (With Schema)
|
||||
@mcp.tool
|
||||
def calculate_sum(a: int, b: int) -> int:
|
||||
"""Calculate sum with return annotation."""
|
||||
return a + b # Returns 8
|
||||
```
|
||||
|
||||
```json Traditional Content
|
||||
"8"
|
||||
```
|
||||
|
||||
```json Structured Content (From Schema)
|
||||
{
|
||||
"result": 8
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
##### Complex Type Example
|
||||
|
||||
<CodeGroup>
|
||||
```python Tool Definition
|
||||
|
|
@ -334,19 +406,110 @@ def get_user_profile(user_id: str) -> Person:
|
|||
{
|
||||
"properties": {
|
||||
"name": {"title": "Name", "type": "string"},
|
||||
"age": {"title": "Age", "type": "integer"},
|
||||
"age": {"title": "Age", "type": "integer"},
|
||||
"email": {"title": "Email", "type": "string"}
|
||||
},
|
||||
"required": ["name", "age", "email"],
|
||||
"title": "Person",
|
||||
"type": "object"
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
```json Structured Output
|
||||
{
|
||||
"name": "Alice",
|
||||
"age": 30,
|
||||
"email": "alice@example.com"
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
The output schema is automatically generated for most common types including basic types, collections, union types, Pydantic models, TypedDict structures, and dataclasses. For FastMCP's special types (`Image`, `Audio`, `File`), the output schema reflects their MCP equivalents rather than the FastMCP wrapper types.
|
||||
|
||||
#### Output Schemas
|
||||
|
||||
<VersionBadge version="2.10.0" />
|
||||
|
||||
The 6/18/2025 MCP spec update [introduced](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema) output schemas, which are a new way to describe the expected output format of a tool. When an output schema is provided, the tool *must* return structured output that matches the schema.
|
||||
|
||||
When you add return type annotations to your functions, FastMCP automatically generates JSON schemas that describe the expected output format. These schemas help MCP clients understand and validate the structured data they receive.
|
||||
|
||||
##### Primitive Type Wrapping
|
||||
|
||||
For primitive return types (like `int`, `str`, `bool`), FastMCP automatically wraps the result under a `"result"` key to create valid structured output:
|
||||
|
||||
<CodeGroup>
|
||||
```python Primitive Return Type
|
||||
@mcp.tool
|
||||
def calculate_sum(a: int, b: int) -> int:
|
||||
"""Add two numbers together."""
|
||||
return a + b
|
||||
```
|
||||
|
||||
```json Generated Schema (Wrapped)
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"result": {"type": "integer"}
|
||||
},
|
||||
"x-fastmcp-wrap-result": true
|
||||
}
|
||||
```
|
||||
|
||||
```json Structured Output
|
||||
{
|
||||
"result": 8
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
##### Manual Schema Control
|
||||
|
||||
You can override the automatically generated schema by providing a custom `output_schema`:
|
||||
|
||||
```python
|
||||
@mcp.tool(output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {"type": "string"},
|
||||
"metadata": {"type": "object"}
|
||||
}
|
||||
})
|
||||
def custom_schema_tool() -> dict:
|
||||
"""Tool with custom output schema."""
|
||||
return {"data": "Hello", "metadata": {"version": "1.0"}}
|
||||
```
|
||||
|
||||
Schema generation works for most common types including basic types, collections, union types, Pydantic models, TypedDict structures, and dataclasses.
|
||||
|
||||
<Warning>
|
||||
**Important Constraints**:
|
||||
- Output schemas must be object types (`"type": "object"`)
|
||||
- If you provide an output schema, your tool **must** return structured output that matches it
|
||||
- However, you can provide structured output without an output schema (using `ToolResult`)
|
||||
</Warning>
|
||||
|
||||
#### Full Control with ToolResult
|
||||
|
||||
For complete control over both traditional content and structured output, return a `ToolResult` object:
|
||||
|
||||
```python
|
||||
from fastmcp.tools.tool import ToolResult
|
||||
|
||||
@mcp.tool
|
||||
def advanced_tool() -> ToolResult:
|
||||
"""Tool with full control over output."""
|
||||
return ToolResult(
|
||||
content=[TextContent(text="Human-readable summary")],
|
||||
structured_content={"data": "value", "count": 42}
|
||||
)
|
||||
```
|
||||
|
||||
When returning `ToolResult`:
|
||||
- You control exactly what content and structured data is sent
|
||||
- Output schemas are optional - structured content can be provided without a schema
|
||||
- Clients receive both traditional content blocks and structured data
|
||||
|
||||
<Note>
|
||||
If your return type annotation cannot be converted to a JSON schema (e.g., complex custom classes without Pydantic support), the output schema will be omitted from the tool definition. The tool will still function normally, but clients won't receive type information about the expected output.
|
||||
If your return type annotation cannot be converted to a JSON schema (e.g., complex custom classes without Pydantic support), the output schema will be omitted but the tool will still function normally with traditional content.
|
||||
</Note>
|
||||
|
||||
### Error Handling
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue