Skip to content
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
121 changes: 65 additions & 56 deletions docs/servers/resources.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ def get_greeting() -> str:
"""Provides a simple greeting message."""
return "Hello from FastMCP Resources!"

# Resource returning JSON data (dict is auto-serialized)
# Resource returning JSON data
@mcp.resource("data://config")
def get_config() -> dict:
def get_config() -> str:
"""Provides application configuration as JSON."""
return {
return json.dumps({
"theme": "dark",
"version": "1.2.0",
"features": ["tools", "resources"],
}
})
```

**Key Concepts:**
Expand Down Expand Up @@ -76,9 +76,9 @@ mcp = FastMCP(name="DataServer")
tags={"monitoring", "status"}, # Categorization tags
meta={"version": "2.1", "team": "infrastructure"} # Custom metadata
)
def get_application_status() -> dict:
def get_application_status() -> str:
"""Internal function description (ignored if description is provided above)."""
return {"status": "ok", "uptime": 12345, "version": mcp.settings.version} # Example usage
return json.dumps({"status": "ok", "uptime": 12345, "version": mcp.settings.version})
```

<Card icon="code" title="@resource Decorator Arguments">
Expand Down Expand Up @@ -134,33 +134,36 @@ def get_application_status() -> dict:

### Return Values

FastMCP automatically converts your function's return value into the appropriate MCP resource content:
Resource functions must return one of three types:

- **`str`**: Sent as `TextResourceContents` (with `mime_type="text/plain"` by default).
- **`dict`, `list`, `pydantic.BaseModel`**: Automatically serialized to a JSON string and sent as `TextResourceContents` (with `mime_type="application/json"` by default).
- **`bytes`**: Base64 encoded and sent as `BlobResourceContents`. You should specify an appropriate `mime_type` (e.g., `"image/png"`, `"application/octet-stream"`).
- **`ResourceContent`**: Full control over content, MIME type, and metadata. See [ResourceContent](#resourcecontent) below.
- **`None`**: Results in an empty resource content list being returned.
- **`ResourceResult`**: Full control over contents, MIME types, and metadata. See [ResourceResult](#resourceresult) below.

<Note>
To return structured data like dicts or lists, serialize them to JSON strings using `json.dumps()`. This explicit approach ensures your type checker catches errors during development rather than at runtime when a client reads the resource.
</Note>

#### ResourceContent
#### ResourceResult

<VersionBadge version="2.14.1" />
<VersionBadge version="3.0.0" />

For complete control over resource responses, return a `ResourceContent` object. This lets you include metadata alongside your resource content, which is useful for cases like Content Security Policy headers for HTML widgets.
`ResourceResult` gives you explicit control over resource responses: multiple content items, per-item MIME types, and metadata at both the item and result level.

```python
from fastmcp import FastMCP
from fastmcp.resources import ResourceContent

mcp = FastMCP(name="WidgetServer")

@mcp.resource("widget://my-widget")
def get_widget() -> ResourceContent:
"""Returns an HTML widget with CSP metadata."""
return ResourceContent(
content="<html><body>My Widget</body></html>",
mime_type="text/html",
meta={"csp": "script-src 'self'"}
from fastmcp.resources import ResourceResult, ResourceContent

mcp = FastMCP()

@mcp.resource("data://users")
def get_users() -> ResourceResult:
return ResourceResult(
contents=[
ResourceContent(content='[{"id": 1}]', mime_type="application/json"),
ResourceContent(content="# Users\n...", mime_type="text/markdown"),
],
meta={"total": 1}
)
```

Expand All @@ -172,25 +175,33 @@ def get_widget() -> ResourceContent:

**`meta`** - Optional metadata dictionary that will be included in the MCP response's `meta` field. Use this for runtime metadata like Content Security Policy headers, caching hints, or other client-specific data.

For simple cases, you can pass `str` or `bytes` directly to `ResourceResult`:

```python
# Binary content with metadata
@mcp.resource("images://logo")
def get_logo() -> ResourceContent:
"""Returns a logo image with caching metadata."""
with open("logo.png", "rb") as f:
image_data = f.read()
return ResourceContent(
content=image_data,
mime_type="image/png",
meta={"cache-control": "max-age=3600"}
)
return ResourceResult("plain text") # auto-converts to ResourceContent
return ResourceResult(b"\x00\x01\x02") # binary content
```

<Note>
The `meta` field in `ResourceContent` is for runtime metadata specific to this read response. This is separate from the `meta` parameter in `@mcp.resource(meta={...})`, which provides static metadata about the resource definition itself (returned when listing resources).
</Note>
<Card title="ResourceResult">
<ParamField body="contents" type="str | bytes | list[ResourceContent]" required>
Content to return. Strings and bytes are wrapped in a single `ResourceContent`. Use a list of `ResourceContent` for multiple items or custom MIME types.
</ParamField>
<ParamField body="meta" type="dict[str, Any] | None">
Result-level metadata, included in the MCP response's `_meta` field.
</ParamField>
</Card>

You can still return plain `str` or `bytes` from your resource functions—`ResourceContent` is opt-in for when you need to include metadata.
<Card title="ResourceContent">
<ParamField body="content" type="Any" required>
The content data. Strings and bytes pass through directly. Other types (dict, list, BaseModel) are automatically JSON-serialized.
</ParamField>
<ParamField body="mime_type" type="str | None">
MIME type. Defaults to `text/plain` for strings, `application/octet-stream` for bytes, `application/json` for serialized objects.
</ParamField>
<ParamField body="meta" type="dict[str, Any] | None">
Item-level metadata for this specific content.
</ParamField>
</Card>

### Visibility Control

Expand Down Expand Up @@ -234,20 +245,20 @@ from fastmcp import FastMCP, Context
mcp = FastMCP(name="DataServer")

@mcp.resource("resource://system-status")
async def get_system_status(ctx: Context) -> dict:
async def get_system_status(ctx: Context) -> str:
"""Provides system status information."""
return {
return json.dumps({
"status": "operational",
"request_id": ctx.request_id
}
})

@mcp.resource("resource://{name}/details")
async def get_details(name: str, ctx: Context) -> dict:
async def get_details(name: str, ctx: Context) -> str:
"""Get details for a specific name."""
return {
return json.dumps({
"name": name,
"accessed_at": ctx.request_id
}
})
```

For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
Expand Down Expand Up @@ -401,9 +412,9 @@ You can add annotations to a resource using the `annotations` parameter in the `
"idempotentHint": True
}
)
def get_config() -> dict:
def get_config() -> str:
"""Get application configuration."""
return {"version": "1.0", "debug": False}
return json.dumps({"version": "1.0", "debug": False})
```

FastMCP supports these standard annotations:
Expand All @@ -430,22 +441,21 @@ Functions with `*args` are not supported as resource templates. However, unlike
Here is a complete example that shows how to define two resource templates:

```python
import json
from fastmcp import FastMCP

mcp = FastMCP(name="DataServer")

# Template URI includes {city} placeholder
@mcp.resource("weather://{city}/current")
def get_weather(city: str) -> dict:
def get_weather(city: str) -> str:
"""Provides weather information for a specific city."""
# In a real implementation, this would call a weather API
# Here we're using simplified logic for example purposes
return {
return json.dumps({
"city": city.capitalize(),
"temperature": 22,
"condition": "Sunny",
"unit": "celsius"
}
})

# Template with multiple parameters and annotations
@mcp.resource(
Expand All @@ -455,16 +465,15 @@ def get_weather(city: str) -> dict:
"idempotentHint": True
}
)
def get_repo_info(owner: str, repo: str) -> dict:
def get_repo_info(owner: str, repo: str) -> str:
"""Retrieves information about a GitHub repository."""
# In a real implementation, this would call the GitHub API
return {
return json.dumps({
"owner": owner,
"name": repo,
"full_name": f"{owner}/{repo}",
"stars": 120,
"forks": 48
}
})
```

With these two templates defined, clients can request a variety of resources:
Expand Down
3 changes: 2 additions & 1 deletion src/fastmcp/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .resource import FunctionResource, Resource, ResourceContent
from .resource import FunctionResource, Resource, ResourceContent, ResourceResult
from .template import ResourceTemplate
from .types import (
BinaryResource,
Expand All @@ -16,6 +16,7 @@
"HttpResource",
"Resource",
"ResourceContent",
"ResourceResult",
"ResourceTemplate",
"TextResource",
]
Loading