Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

Align server component docs (#4260)

Bill Eastond3b792261537
diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdx
index 42523a5cd..9175c2438 100644
--- a/docs/servers/composition.mdx
+++ b/docs/servers/composition.mdx
@@ -199,23 +199,28 @@ If low latency is critical, consider implementing caching strategies or limiting
Custom HTTP routes defined with `@server.custom_route()` are also forwarded when mounting:
```python
+from fastmcp import FastMCP
+from starlette.requests import Request
+from starlette.responses import JSONResponse, Response
+
subserver = FastMCP("Sub")
@subserver.custom_route("/health", methods=["GET"])
-async def health_check():
- return {"status": "ok"}
+async def health_check(request: Request) -> Response:
+ return JSONResponse({"status": "ok"})
main = FastMCP("Main")
main.mount(subserver, namespace="sub")
-# /health is now accessible through main's HTTP app
+# /health is now accessible through main's HTTP app.
+# Custom route paths are not namespaced by mount(namespace=...).
```
## Conflict Resolution
<VersionBadge version="3.0.0" />
-When mounting multiple servers with the same namespace (or no namespace), the **most recently mounted** server takes precedence for conflicting component names:
+When mounting multiple servers with the same namespace (or no namespace), FastMCP queries all mounted providers for a requested component and returns the highest matching version. If two unversioned components (or two equal versions) use the same identifier, the provider registered first wins.
```python
server_a = FastMCP("A")
@@ -233,5 +238,5 @@ main = FastMCP("Main")
main.mount(server_a)
main.mount(server_b)
-# shared_tool returns "From B" (most recently mounted)
+# shared_tool returns "From A" (first mounted, same unversioned key)
```
diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx
index ecd9e67ea..ccabe3d41 100644
--- a/docs/servers/context.mdx
+++ b/docs/servers/context.mdx
@@ -71,7 +71,7 @@ async def data_analysis_request(dataset: str, ctx: Context = CurrentContext()) -
- Dependency parameters are automatically excluded from the MCP schema—clients never see them.
- Context methods are async, so your function usually needs to be async as well.
-- **Each MCP request receives a new context object.** Context is scoped to a single request; state or data set in one request will not be available in subsequent requests.
+- **Each MCP request receives a new context object.** Request-scoped values, including non-serializable state, are not available in subsequent requests. Serializable session state stored with `ctx.set_state()` persists across requests in the same MCP session.
- Context is only available during a request; attempting to use context methods outside a request will raise errors.
### Legacy Type-Hint Injection
@@ -184,13 +184,13 @@ List and read data from resources registered with your FastMCP server, allowing
resources = await ctx.list_resources()
# Read a specific resource
-content_list = await ctx.read_resource("resource://config")
-content = content_list[0].content
+resource_result = await ctx.read_resource("resource://config")
+content = resource_result.contents[0].content
```
**Method signatures:**
-- **`ctx.list_resources() -> list[MCPResource]`**: <VersionBadge version="2.13.0" /> Returns list of all available resources
-- **`ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]`**: Returns a list of resource content parts
+- **`ctx.list_resources() -> list[mcp_types.Resource]`**: <VersionBadge version="2.13.0" /> Returns list of all available resources
+- **`ctx.read_resource(uri: str | AnyUrl) -> ResourceResult`**: Returns a `ResourceResult` whose `.contents` list contains the resource content parts
### Prompt Access
@@ -322,7 +322,7 @@ State set during `on_initialize` middleware persists to subsequent tool calls wh
<VersionBadge version="3.0.0" />
-Tools can customize which components are visible to their current session using `ctx.enable_components()`, `ctx.disable_components()`, and `ctx.reset_visibility()`. These methods apply visibility rules that affect only the calling session, leaving other sessions unchanged. See [Per-Session Visibility](/servers/visibility#per-session-visibility) for complete documentation, filter criteria, and patterns like namespace activation.
+Tools can customize which components are visible to their current session using `ctx.enable_components()`, `ctx.disable_components()`, and `ctx.reset_visibility()`. They accept the same filters as the server-level methods, so `names={"search"}` targets a component by name and `tags` targets a group. These methods apply visibility rules that affect only the calling session, leaving other sessions unchanged. See [Per-Session Visibility](/servers/visibility#per-session-visibility) for complete documentation, filter criteria, and patterns like namespace activation.
### Change Notifications
diff --git a/docs/servers/dependency-injection.mdx b/docs/servers/dependency-injection.mdx
index 40fc7b65b..213fd81b7 100644
--- a/docs/servers/dependency-injection.mdx
+++ b/docs/servers/dependency-injection.mdx
@@ -10,7 +10,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx";
FastMCP uses dependency injection to provide runtime values to your tools, resources, and prompts. Instead of passing context through every layer of your code, you declare what you need as parameter defaults—FastMCP resolves them automatically when your function runs.
-The dependency injection system is powered by [Docket](https://github.com/chrisguidry/docket) and its dependency system [uncalled-for](https://github.com/chrisguidry/uncalled-for). Core DI features like `Depends()` and `CurrentContext()` work without installing Docket. For background tasks and advanced task-related dependencies, install `fastmcp[tasks]`. For comprehensive coverage of dependency patterns, see the [Docket dependency documentation](https://docket.lol/en/latest/dependency-injection/).
+The dependency injection system is powered by [uncalled-for](https://github.com/chrisguidry/uncalled-for), the same dependency engine used by Docket. Core DI features like `Depends()` and `CurrentContext()` work without installing Docket. Background task execution and task-specific dependencies such as `CurrentDocket()` and `CurrentWorker()` require `fastmcp[tasks]`. For comprehensive coverage of dependency patterns, see the [Docket dependency documentation](https://docket.lol/en/latest/dependency-injection/).
<Note>
Dependency parameters are automatically excluded from the MCP schema—clients never see them as callable parameters. This separation keeps your function signatures clean while giving you access to the runtime context you need.
@@ -278,7 +278,7 @@ Common claims vary by identity provider:
<VersionBadge version="2.3.0" />
-For background task execution, FastMCP provides dependencies that integrate with [Docket](https://github.com/chrisguidry/docket). These require installing `fastmcp[tasks]`.
+For background task execution, FastMCP provides dependencies that integrate with [Docket](https://github.com/chrisguidry/docket). `CurrentDocket()` and `CurrentWorker()` require installing `fastmcp[tasks]`; `Progress()` also works during immediate foreground execution with an in-memory tracker, and delegates to Docket progress when a Docket worker context is active.
```python
from fastmcp import FastMCP
@@ -309,7 +309,7 @@ async def long_running_task(
- **`Progress()`**: Track task progress with atomic updates
<Note>
-Task dependencies require `pip install 'fastmcp[tasks]'`. They're only available within task-enabled components (`task=True`). For comprehensive task patterns, see the [Docket documentation](https://chrisguidry.github.io/docket/dependencies/).
+`CurrentDocket()` and `CurrentWorker()` require `pip install 'fastmcp[tasks]'`. They resolve once the server lifespan has initialized Docket, which happens as soon as any component on the server is task-enabled — so regular foreground tools, resources, and prompts can inject them too, not only task-enabled components. `Progress()` can be injected anywhere regardless, though cross-process task progress requires Docket. For comprehensive task patterns, see the [Docket documentation](https://chrisguidry.github.io/docket/dependencies/).
</Note>
## Custom Dependencies
diff --git a/docs/servers/elicitation.mdx b/docs/servers/elicitation.mdx
index 923e704c6..acf29d10c 100644
--- a/docs/servers/elicitation.mdx
+++ b/docs/servers/elicitation.mdx
@@ -178,16 +178,16 @@ async def confirm_purchase(ctx: Context) -> str:
These arguments only apply when FastMCP is adding the wrapper. For structured responses (`BaseModel`, dataclass, `TypedDict`), set the metadata on the individual fields via `Field(title=..., description=...)` — passing `response_title` or `response_description` alongside a model type raises `TypeError`.
-### No Response
+### Empty Responses
-Sometimes, the goal of an elicitation is to simply get a user to approve or reject an action. Pass `None` as the response type to indicate that no data is expected. The `data` field will be `None` when the user accepts.
+Passing `None` as the response type creates an empty-object schema and returns an accepted result with `data == {}`. This form is deprecated because some clients render empty forms poorly; prefer an explicit response type such as `bool` for confirmations.
```python
@mcp.tool
async def approve_action(ctx: Context) -> str:
- result = await ctx.elicit("Approve this action?", response_type=None)
+ result = await ctx.elicit("Approve this action?", response_type=bool)
- if result.action == "accept":
+ if result.action == "accept" and result.data:
return do_action()
else:
raise ValueError("Action rejected")
diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdx
index c08c06b25..a74a7bb5c 100644
--- a/docs/servers/middleware.mdx
+++ b/docs/servers/middleware.mdx
@@ -262,27 +262,36 @@ async def on_list_prompts(self, context: MiddlewareContext, call_next):
<VersionBadge version="2.13.0" />
-Called when a client connects and initializes the session. This hook cannot modify the initialization response.
+Called when a client connects and initializes the session. Middleware can reject the client before `call_next()` raises an error response, or inspect and modify the `InitializeResult` after `call_next()` returns.
+
+The request params carry the identity the client declared for itself on `client_info`, which makes this the natural place to gate access by client. Note that these fields are snake_case: the MCP wire format spells it `clientInfo`, but the Python model exposes `client_info` and treats the camelCase form as a serialization alias only.
```python
from fastmcp.exceptions import McpError
async def on_initialize(self, context: MiddlewareContext, call_next):
- client_info = context.message.params.get("clientInfo", {})
- client_name = client_info.get("name", "unknown")
+ client_name = context.message.params.client_info.name
# Reject before call_next to send error to client
if client_name == "blocked-client":
raise McpError(code=-32000, message="Client not supported")
- await call_next(context)
+ result = await call_next(context)
print(f"Client {client_name} initialized")
+ return result
```
-**Returns:** `None` — The initialization response is handled internally by the MCP protocol.
+**Returns:** `InitializeResult | None` — The value you return is what gets serialized to the client, so modifying the result from `call_next()` changes what the client receives, including fields like `instructions` and `server_info`.
+
+```python
+async def on_initialize(self, context: MiddlewareContext, call_next):
+ result = await call_next(context)
+ result.instructions = "Custom instructions for this client"
+ return result
+```
<Warning>
-Raising `McpError` after `call_next()` will only log the error, not send it to the client. The response has already been sent. Always reject **before** `call_next()`.
+Rejection works only **before** `call_next()`. Raising `McpError` afterward logs the error without sending it — the client still receives a successful initialize response.
</Warning>
### Raw Handler
diff --git a/docs/servers/pagination.mdx b/docs/servers/pagination.mdx
index c23e296bc..b78f09bb1 100644
--- a/docs/servers/pagination.mdx
+++ b/docs/servers/pagination.mdx
@@ -14,7 +14,7 @@ When a server exposes many tools, resources, or prompts, returning them all in a
## Server Configuration
-By default, FastMCP servers return all components in a single response for backward compatibility. To enable pagination, set the `list_page_size` parameter when creating your server. This value determines the maximum number of items returned per page across all list operations.
+By default, FastMCP servers return all components in a single response for backward compatibility. To enable pagination, set the `list_page_size` parameter when creating your server. This value must be a positive integer and determines the maximum number of items returned per page across all list operations.
```python
from fastmcp import FastMCP
diff --git a/docs/servers/progress.mdx b/docs/servers/progress.mdx
index 9600a05ce..7dadb73a4 100644
--- a/docs/servers/progress.mdx
+++ b/docs/servers/progress.mdx
@@ -11,7 +11,7 @@ Progress reporting allows MCP tools to notify clients about the progress of long
## Basic Usage
-Use `ctx.report_progress()` to send progress updates to the client. The method accepts a `progress` value representing how much work is complete, and an optional `total` representing the full scope of work.
+Use `ctx.report_progress()` to send progress updates to the client. The method accepts a `progress` value representing how much work is complete, an optional `total` representing the full scope of work, and an optional `message` with human-readable status text.
```python
from fastmcp import FastMCP, Context
@@ -26,7 +26,7 @@ async def process_items(items: list[str], ctx: Context) -> dict:
results = []
for i, item in enumerate(items):
- await ctx.report_progress(progress=i, total=total)
+ await ctx.report_progress(progress=i, total=total, message=f"Processing {item}")
await asyncio.sleep(0.1)
results.append(item.upper())
diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdx
index b5cf2f6e9..4e824dec0 100644
--- a/docs/servers/prompts.mdx
+++ b/docs/servers/prompts.mdx
@@ -95,10 +95,6 @@ def data_analysis_prompt(
A set of strings used to categorize the prompt. These can be used by the server and, in some cases, by clients to filter or group available prompts.
</ParamField>
-<ParamField body="enabled" type="bool" default="True">
- <Warning>Deprecated in v3.0.0. Use `mcp.enable()` / `mcp.disable()` at the server level instead.</Warning>
- A boolean to enable or disable the prompt. See [Component Visibility](#component-visibility) for the recommended approach.
-</ParamField>
<ParamField body="icons" type="list[Icon] | None">
<VersionBadge version="2.13.0" />
@@ -314,7 +310,7 @@ return PromptResult("Please help me with this task") # auto-converts to single
Messages to return. Strings are wrapped as a single user Message.
</ParamField>
<ParamField body="description" type="str | None">
- Optional description of the prompt result. If not provided, defaults to the prompt's docstring.
+ Optional description of this rendered prompt result. Plain `str` and `list[Message | str]` returns inherit the prompt definition description automatically, but an explicit `PromptResult` uses the description you pass here and otherwise leaves it unset.
</ParamField>
<ParamField body="meta" type="dict[str, Any] | None">
Result-level metadata, included in the MCP response's `_meta` field. Use this for runtime metadata like categorization, priority, or other client-specific data.
@@ -367,7 +363,7 @@ def internal_prompt() -> str:
return "Internal system prompt"
# Disable specific prompts by key
-mcp.disable(keys={"prompt:internal_prompt"})
+mcp.disable(names={"internal_prompt"})
# Disable prompts by tag
mcp.disable(tags={"internal"})
@@ -434,8 +430,8 @@ def example_prompt() -> str:
# These operations trigger notifications:
mcp.add_prompt(example_prompt) # Sends prompts/list_changed notification
-mcp.disable(keys={"prompt:example_prompt"}) # Sends prompts/list_changed notification
-mcp.enable(keys={"prompt:example_prompt"}) # Sends prompts/list_changed notification
+mcp.disable(names={"example_prompt"}) # Sends prompts/list_changed notification
+mcp.enable(names={"example_prompt"}) # Sends prompts/list_changed notification
```
Notifications are only sent when these operations occur within an active MCP request context (e.g., when called from within a tool or other MCP operation). Operations performed during server initialization do not trigger notifications.
diff --git a/docs/servers/providers/local.mdx b/docs/servers/providers/local.mdx
index 86726655a..147ef7e59 100644
--- a/docs/servers/providers/local.mdx
+++ b/docs/servers/providers/local.mdx
@@ -124,10 +124,10 @@ def get_status() -> str:
mcp.disable(tags={"admin"})
# Or only enable specific tools
-mcp.enable(keys={"tool:get_status"}, only=True)
+mcp.enable(names={"get_status"}, only=True)
```
-See [Visibility](/servers/visibility) for the full documentation on keys, tags, allowlist mode, and provider-level control.
+See [Visibility](/servers/visibility) for the full documentation on names, tags, keys, allowlist mode, and provider-level control.
## Standalone LocalProvider
diff --git a/docs/servers/providers/overview.mdx b/docs/servers/providers/overview.mdx
index d3e3e4e5f..c19073f78 100644
--- a/docs/servers/providers/overview.mdx
+++ b/docs/servers/providers/overview.mdx
@@ -57,9 +57,9 @@ Transforms can be added to individual providers (affecting just that source) or
## Provider Order
-When a client requests a tool, FastMCP queries providers in registration order. The first provider that has the tool handles the request.
+When a client requests a component by name or URI, FastMCP queries providers and returns the highest matching version across the providers that have it. For unversioned components, or for components with equal versions, provider registration order is the tie-breaker.
-`LocalProvider` is always first, so your decorator-defined tools take precedence. Additional providers are queried in the order you added them. This means if two providers have a tool with the same name, the first one wins.
+`LocalProvider` is always registered first, so your decorator-defined components take precedence over equal-version components from mounted or proxied providers. Additional providers are registered in the order you add them.
## When to Care About Providers
diff --git a/docs/servers/providers/skills.mdx b/docs/servers/providers/skills.mdx
index 0f8eff5e7..01214d3d4 100644
--- a/docs/servers/providers/skills.mdx
+++ b/docs/servers/providers/skills.mdx
@@ -38,10 +38,10 @@ Each subdirectory containing a `SKILL.md` file becomes a discoverable skill. Cli
from fastmcp import Client
async with Client(mcp) as client:
- # List all skill resources
+ # List each skill's main file and manifest
resources = await client.list_resources()
for r in resources:
- print(r.uri) # skill://my-skill/SKILL.md, skill://my-skill/_manifest, ...
+ print(r.uri) # skill://my-skill/SKILL.md, skill://my-skill/_manifest
# Read a skill's main instruction file
result = await client.read_resource("skill://my-skill/SKILL.md")
diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx
index 1318eedf9..7f45c7280 100644
--- a/docs/servers/resources.mdx
+++ b/docs/servers/resources.mdx
@@ -90,6 +90,10 @@ def get_application_status() -> str:
A human-readable name. If not provided, defaults to function name
</ParamField>
+<ParamField body="title" type="str | None">
+ A human-readable display title for the resource or template
+</ParamField>
+
<ParamField body="description" type="str | None">
Explanation of the resource. If not provided, defaults to docstring
</ParamField>
@@ -102,11 +106,6 @@ def get_application_status() -> str:
A set of strings used to categorize the resource. These can be used by the server and, in some cases, by clients to filter or group available resources.
</ParamField>
-<ParamField body="enabled" type="bool" default="True">
- <Warning>Deprecated in v3.0.0. Use `mcp.enable()` / `mcp.disable()` at the server level instead.</Warning>
- A boolean to enable or disable the resource. See [Component Visibility](#component-visibility) for the recommended approach.
-</ParamField>
-
<ParamField body="icons" type="list[Icon] | None">
<VersionBadge version="2.13.0" />
@@ -144,14 +143,16 @@ For decorating instance or class methods, use the standalone `@resource` decorat
### Return Values
-Resource functions must return one of three types:
+Resource functions can return these supported shapes:
- **`str`**: Sent as `TextResourceContents` (with `mime_type="text/plain"` by default).
- **`bytes`**: Base64 encoded and sent as `BlobResourceContents`. You should specify an appropriate `mime_type` (e.g., `"image/png"`, `"application/octet-stream"`).
-- **`ResourceResult`**: Full control over contents, MIME types, and metadata. See [ResourceResult](#resourceresult) below.
+- **JSON-native values** (`dict`, `list`, `tuple`, numbers, booleans, or `None`): Serialized to JSON text, keeping the resource's declared MIME type — which is `text/plain` unless you set one. Pass `mime_type="application/json"` on the decorator whenever clients rely on the content type to parse the payload.
+- **`list[ResourceContent]`**: Multiple content items with per-item MIME types and metadata.
+- **`ResourceResult`**: Full control over contents, MIME types, and result-level 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.
+For custom classes that are not JSON-native, return a `ResourceResult` or wrap values in a `ResourceContent` list so serialization and MIME types are explicit.
</Note>
#### ResourceResult
@@ -231,7 +232,7 @@ def get_public(): return "public"
def get_secret(): return "secret"
# Disable specific resources by key
-mcp.disable(keys={"resource:data://secret"})
+mcp.disable(names={"data://secret"})
# Disable resources by tag
mcp.disable(tags={"internal"})
@@ -369,8 +370,8 @@ def example_resource() -> str:
# These operations trigger notifications:
mcp.add_resource(example_resource) # Sends resources/list_changed notification
-mcp.disable(keys={"resource:data://example"}) # Sends resources/list_changed notification
-mcp.enable(keys={"resource:data://example"}) # Sends resources/list_changed notification
+mcp.disable(names={"data://example"}) # Sends resources/list_changed notification
+mcp.enable(names={"data://example"}) # Sends resources/list_changed notification
```
Notifications are only sent when these operations occur within an active MCP request context (e.g., when called from within a tool or other MCP operation). Operations performed during server initialization do not trigger notifications.
diff --git a/docs/servers/server.mdx b/docs/servers/server.mdx
index 9f6374a5d..71bd425b4 100644
--- a/docs/servers/server.mdx
+++ b/docs/servers/server.mdx
@@ -100,15 +100,15 @@ The `FastMCP` constructor accepts parameters organized into four categories: ide
These parameters control how your server presents itself to clients.
<Card>
-<ParamField body="name" type="str" default="FastMCP">
- A human-readable name for your server, shown in client applications and logs
+<ParamField body="name" type="str | None" default="None">
+ A human-readable name for your server, shown in client applications and logs. If omitted, FastMCP generates a random name
</ParamField>
<ParamField body="instructions" type="str | None">
Description of how to interact with this server. Clients surface these instructions to help LLMs understand the server's purpose and available functionality
</ParamField>
-<ParamField body="version" type="str | None">
+<ParamField body="version" type="str | int | float | None">
Version string for your server. Defaults to the FastMCP library version if not provided
</ParamField>
@@ -136,29 +136,29 @@ These parameters control how your server presents itself to clients.
These parameters control what your server is built from — its components, middleware, providers, and lifecycle.
<Card>
-<ParamField body="tools" type="list[Tool | Callable] | None">
+<ParamField body="tools" type="Sequence[Tool | Callable] | None">
Tools to register on the server. An alternative to the `@mcp.tool` decorator when you need to add tools programmatically
</ParamField>
-<ParamField body="auth" type="OAuthProvider | TokenVerifier | None">
+<ParamField body="auth" type="AuthProvider | None">
Authentication provider for securing HTTP-based transports. See [Authentication](/servers/auth/authentication) for configuration
</ParamField>
-<ParamField body="middleware" type="list[Middleware] | None">
+<ParamField body="middleware" type="Sequence[Middleware] | None">
[Middleware](/servers/middleware) that intercepts and transforms every MCP message flowing through the server — requests, responses, and notifications in both directions. Use for cross-cutting concerns like logging, error handling, and rate limiting
</ParamField>
-<ParamField body="providers" type="list[Provider] | None">
+<ParamField body="providers" type="Sequence[Provider] | None">
[Providers](/servers/providers/overview) that supply tools, resources, and prompts dynamically. Providers are queried at request time, so they can serve components from databases, APIs, or other external sources
</ParamField>
-<ParamField body="transforms" type="list[Transform] | None">
+<ParamField body="transforms" type="Sequence[Transform] | None">
<VersionBadge version="3.1.0" />
Server-level [transforms](/servers/transforms/transforms) to apply to all components. Transforms modify how tools, resources, and prompts are presented to clients — for example, [search transforms](/servers/transforms/tool-search) replace large catalogs with on-demand discovery
</ParamField>
-<ParamField body="lifespan" type="Lifespan | AsyncContextManager | None">
+<ParamField body="lifespan" type="Lifespan | LifespanCallable | None">
Server-level setup and teardown logic that runs when the server starts and stops. See [Lifespans](/servers/lifespan) for composable lifespans
</ParamField>
</Card>
@@ -185,7 +185,7 @@ These parameters tune how the server processes requests and communicates with cl
<ParamField body="list_page_size" type="int | None" default="None">
<VersionBadge version="3.0.0" />
- Maximum items per page for list operations (`tools/list`, `resources/list`, etc.). When `None`, all results are returned in a single response. See [Pagination](/servers/pagination) for details
+ Maximum items per page for list operations (`tools/list`, `resources/list`, etc.). Must be a positive integer when set. When `None`, all results are returned in a single response. See [Pagination](/servers/pagination) for details
</ParamField>
<ParamField body="tasks" type="bool | None" default="False">
@@ -273,7 +273,7 @@ The filtering logic works as follows:
- **Precedence**: Later calls override earlier ones, so call `disable` after `enable` to exclude from an allowlist
<Tip>
-To ensure a component is never exposed, you can set `enabled=False` on the component itself. See the component-specific documentation for details.
+To hide a component by default, disable it at the server level with `mcp.disable(names={"admin_tool"})`. This is a default rather than a guarantee — a later `enable()` call or a per-session visibility rule can bring the component back. When something must never be reachable, leave it unregistered or guard it with [authentication](/servers/auth/authentication) instead of relying on visibility.
</Tip>
```python
diff --git a/docs/servers/tasks.mdx b/docs/servers/tasks.mdx
index d4aae9f54..a676782be 100644
--- a/docs/servers/tasks.mdx
+++ b/docs/servers/tasks.mdx
@@ -144,7 +144,7 @@ If your server defines any synchronous tools, resources, or prompts, you will ne
### Graceful Degradation
-When a client requests background execution but the component has `mode="forbidden"`, FastMCP executes synchronously and returns the result inline. This follows the SEP-1686 specification for graceful degradation—clients can always request background execution without worrying about server capabilities.
+When a client requests background execution but the component has `mode="forbidden"`, FastMCP rejects the task-augmented request with a `METHOD_NOT_FOUND` error saying the component does not support task execution. The high-level FastMCP tool client can surface this as an immediate errored `ToolTask` when you call `client.call_tool(..., task=True, raise_on_error=False)`, but the server does not run the forbidden component synchronously for that task request.
Conversely, when a component has `mode="required"` but the client doesn't request background execution, FastMCP returns an error indicating that task execution is required.
diff --git a/docs/servers/telemetry.mdx b/docs/servers/telemetry.mdx
index 77fb0f1de..5e26a58f1 100644
--- a/docs/servers/telemetry.mdx
+++ b/docs/servers/telemetry.mdx
@@ -350,7 +350,7 @@ All custom attributes use the `fastmcp.` prefix for features unique to FastMCP:
|-----------|-------------|
| `fastmcp.server.name` | Server name |
| `fastmcp.component.type` | `tool`, `resource`, `prompt`, or `resource_template` |
-| `fastmcp.component.key` | Full component identifier (e.g., `tool:greet`) |
+| `fastmcp.component.key` | Full component key, including type and version delimiter (e.g., `tool:greet@` or `tool:greet@v2`) |
| `fastmcp.provider.type` | Provider class (`LocalProvider`, `FastMCPProvider`, `ProxyProvider`) |
Provider-specific attributes for delegation context:
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index bc5b7d228..01fbbab30 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -73,14 +73,14 @@ def search_products_implementation(query: str, category: str | None = None) -> l
Provides the description exposed via MCP. If set, the function's docstring is ignored for the tool description, though docstring-derived parameter descriptions still apply (see [Docstring Descriptions](#docstring-descriptions)).
</ParamField>
+<ParamField body="title" type="str | None">
+ A human-readable display title for the tool. If omitted, FastMCP falls back to `annotations.title` when present.
+</ParamField>
+
<ParamField body="tags" type="set[str] | None">
A set of strings used to categorize the tool. These can be used by the server and, in some cases, by clients to filter or group available tools.
</ParamField>
-<ParamField body="enabled" type="bool" default="True">
- <Warning>Deprecated in v3.0.0. Use `mcp.enable()` / `mcp.disable()` at the server level instead.</Warning>
- A boolean to enable or disable the tool. See [Component Visibility](#component-visibility) for the recommended approach.
-</ParamField>
<ParamField body="icons" type="list[Icon] | None">
<VersionBadge version="2.13.0" />
@@ -918,7 +918,7 @@ def public_action() -> str:
return "Done"
# Disable specific tools by key
-mcp.disable(keys={"tool:admin_action"})
+mcp.disable(names={"admin_action"})
# Disable tools by tag
mcp.disable(tags={"admin"})
@@ -1034,8 +1034,8 @@ def example_tool() -> str:
# These operations trigger notifications:
mcp.add_tool(example_tool) # Sends tools/list_changed notification
-mcp.disable(keys={"tool:example_tool"}) # Sends tools/list_changed notification
-mcp.enable(keys={"tool:example_tool"}) # Sends tools/list_changed notification
+mcp.disable(names={"example_tool"}) # Sends tools/list_changed notification
+mcp.enable(names={"example_tool"}) # Sends tools/list_changed notification
mcp.local_provider.remove_tool("example_tool") # Sends tools/list_changed notification
```
diff --git a/docs/servers/versioning.mdx b/docs/servers/versioning.mdx
index 4c44a73bd..0dfa0bc69 100644
--- a/docs/servers/versioning.mdx
+++ b/docs/servers/versioning.mdx
@@ -114,7 +114,7 @@ def process(data: str, mode: str = "default") -> str:
return data.upper()
```
-Both versions are registered. When a client lists tools, they see only `process` with version 2.0 (the highest). When they invoke `process`, version 2.0 executes. The same pattern applies to resources and prompts.
+Both versions are registered. Server-side `list_tools()` returns every registered version, while MCP client list operations deduplicate by identifier and expose the highest version with metadata describing the available versions. When a client invokes `process` without specifying a version, version 2.0 executes. The same pattern applies to resources and prompts.
### Versioned vs Unversioned Components
@@ -189,7 +189,7 @@ By default, clients receive and invoke the highest version of each component. Wh
### FastMCP Client
-The FastMCP client's `call_tool` and `get_prompt` methods accept an optional `version` parameter. When specified, the server executes that exact version instead of the highest.
+The FastMCP client's `call_tool`, `read_resource`, and `get_prompt` methods accept an optional `version` parameter. When specified, the server executes that exact version instead of the highest.
```python
from fastmcp import Client
@@ -201,6 +201,9 @@ async with Client(server) as client:
# Call a specific version
result_v1 = await client.call_tool("calculate", {"x": 1, "y": 2}, version="1.0")
+ # Read a specific resource version
+ data = await client.read_resource("config://app", version="1.0")
+
# Get a specific prompt version
prompt = await client.get_prompt("summarize", {"text": "..."}, version="1.0")
```
@@ -209,13 +212,16 @@ If the requested version doesn't exist, the server raises a `NotFoundError`. Thi
### MCP Protocol
-For generic MCP clients that don't have built-in version support, pass the version through the `_meta` field in arguments. FastMCP servers extract the version from `_meta.fastmcp.version` before processing.
+For generic MCP clients that don't have built-in version support, pass the version through the request params `_meta` field. FastMCP servers extract the version from `_meta.fastmcp.version` before processing.
<CodeGroup>
-```json Tool Call Arguments
+```json Tool Call Request Params
{
- "x": 1,
- "y": 2,
+ "name": "calculate",
+ "arguments": {
+ "x": 1,
+ "y": 2
+ },
"_meta": {
"fastmcp": {
"version": "1.0"
@@ -224,9 +230,12 @@ For generic MCP clients that don't have built-in version support, pass the versi
}
```
-```json Prompt Arguments
+```json Prompt Request Params
{
- "text": "Summarize this document...",
+ "name": "summarize",
+ "arguments": {
+ "text": "Summarize this document..."
+ },
"_meta": {
"fastmcp": {
"version": "1.0"
diff --git a/docs/servers/visibility.mdx b/docs/servers/visibility.mdx
index 509bd7068..edd3127d4 100644
--- a/docs/servers/visibility.mdx
+++ b/docs/servers/visibility.mdx
@@ -57,29 +57,27 @@ mcp.enable(tags={"admin"})
# Clients now see all three tools
```
-## Keys and Tags
+## Targeting Components
-Visibility filtering works with two identifiers: keys (for specific components) and tags (for groups).
+Every filter parameter narrows the same way: `enable()` and `disable()` act on the components matching all the criteria you supply. Reach for the simplest one that expresses your intent — usually names or tags.
-### Component Keys
-
-Every component has a unique key in the format `{type}:{identifier}`.
-
-| Component | Key Format | Example |
-|-----------|------------|---------|
-| Tool | `tool:{name}` | `tool:delete_everything` |
-| Resource | `resource:{uri}` | `resource:data://config` |
-| Template | `template:{uri}` | `template:file://{path}` |
-| Prompt | `prompt:{name}` | `prompt:analyze` |
+### Names
-Use keys to target specific components.
+`names` matches components by their name, or by their URI for resources and templates. This is the common case.
```python
# Disable a specific tool
-mcp.disable(keys={"tool:delete_everything"})
+mcp.disable(names={"delete_everything"})
-# Disable multiple specific components
-mcp.disable(keys={"tool:reset_system", "resource:data://secrets"})
+# Disable several components at once
+mcp.disable(names={"reset_system", "data://secrets"})
+```
+
+A name matches across component types, so a tool and a prompt that share a name are both affected. Add `components` when you want only one type.
+
+```python
+# Disable only the tool named "config", leaving the resource alone
+mcp.disable(names={"config"}, components={"tool"})
```
### Tags
@@ -112,15 +110,62 @@ mcp.disable(tags={"dangerous"})
A component is disabled if it has **any** of the disabled tags. The component doesn't need all the tags; one match is enough.
-### Combining Keys and Tags
+### Versions
+
+When a component has several registered versions, `names` matches every one of them. To act on a particular version, filter by `version` with a [`VersionSpec`](/servers/versioning).
+
+```python
+from fastmcp.utilities.versions import VersionSpec
+
+# Retire v1 of every versioned component, leaving later versions live
+mcp.disable(version=VersionSpec(eq="v1"))
+```
+
+### Component Keys
+
+`keys` targets components by their canonical key, which encodes type, identifier, and version together. It is the only filter that can single out **one specific version of one specific component** — use it when `names` would sweep too broadly and `version` would sweep across too many components.
+
+```python
+# Disable only v1 of search, leaving v1 of every other component untouched
+mcp.disable(keys={"tool:search@v1"})
+```
+
+Keys take the form `{type}:{identifier}@{version}`, where the `@` separates the identifier from the version and is **always present**. An unversioned component has an empty version, so its key ends in a bare `@`.
+
+| Component | Key Format | Example |
+|-----------|------------|---------|
+| Tool | `tool:{name}@{version}` | `tool:delete_everything@` |
+| Resource | `resource:{uri}@{version}` | `resource:data://config@` |
+| Template | `template:{uri_template}@{version}` | `template:file://{path}@` |
+| Prompt | `prompt:{name}@{version}` | `prompt:analyze@` |
+
+The delimiter is unconditional because resource URIs may themselves contain `@`. Always emitting it means a key is parsed by splitting on the last `@`, so `resource:data://[email protected]/profile@` is unambiguous.
-You can specify both keys and tags in a single call. The filters combine additively.
+<Warning>
+Keys are matched by exact string equality, so a key that omits the trailing `@` — `tool:delete_everything` rather than `tool:delete_everything@` — matches nothing. FastMCP raises a `UserWarning` when it sees a key with no `@`, since such a key can never match. Prefer `names` unless you need version-level precision, and read a key off `component.key` rather than assembling it by hand.
+</Warning>
+
+### Combining Filters
+
+Criteria in a single call **narrow** each other: a component must satisfy every one of them to match. Combining a name with a tag targets the intersection, not the union.
+
+```python
+# Disables debug_info only if it is ALSO tagged "dangerous"
+mcp.disable(names={"debug_info"}, tags={"dangerous"})
+```
+
+To act on a union, make one call per criterion. Because later calls override earlier ones only where they overlap, successive disables accumulate.
```python
-# Disable specific tools AND all dangerous-tagged components
-mcp.disable(keys={"tool:debug_info"}, tags={"dangerous"})
+# Disables debug_info AND everything tagged "dangerous"
+mcp.disable(names={"debug_info"})
+mcp.disable(tags={"dangerous"})
```
+<Warning>
+Intersection is easy to misread as union, and a rule that matches nothing fails silently. `disable(names={"debug_info"}, tags={"dangerous"})` disables nothing at all when `debug_info` lacks that tag — the components you meant to hide stay exposed.
+</Warning>
+
## Allowlist Mode
By default, visibility filtering uses blocklist mode: everything is enabled unless explicitly disabled. The `only=True` parameter switches to allowlist mode, where **only** specified components are enabled.
@@ -165,7 +210,7 @@ When you call `enable(only=True)`:
```python
# Start fresh - only enable these specific tools
-mcp.enable(keys={"tool:safe_read", "tool:safe_write"}, only=True)
+mcp.enable(names={"safe_read", "safe_write"}, only=True)
# Later, switch to a different allowlist
mcp.enable(tags={"production"}, only=True)
@@ -177,7 +222,7 @@ Later `enable()` and `disable()` calls override earlier ones. This lets you crea
```python
mcp.enable(tags={"api"}, only=True) # Allow all api-tagged
-mcp.disable(keys={"tool:api_admin"}) # Later disable overrides for this tool
+mcp.disable(names={"api_admin"}) # Later disable overrides for this tool
# api_admin is disabled because the later disable() overrides the allowlist
```
@@ -322,7 +367,7 @@ The session visibility methods accept the same filter criteria as `server.enable
| Parameter | Description |
|-----------|-------------|
| `names` | Component names or URIs to match |
-| `keys` | Component keys (e.g., `{"tool:my_tool"}`) |
+| `keys` | Component keys (e.g., `{"tool:my_tool@"}` for an unversioned tool, or `{"tool:my_tool@v1"}` for a versioned tool) |
| `tags` | Tags to match (component must have at least one) |
| `version` | Version specification to match |
| `components` | Component types (`{"tool"}`, `{"resource"}`, `{"prompt"}`, `{"template"}`) |
diff --git a/fastmcp_slim/fastmcp/resources/base.py b/fastmcp_slim/fastmcp/resources/base.py
index b4e4d0d1d..abb835bc9 100644
--- a/fastmcp_slim/fastmcp/resources/base.py
+++ b/fastmcp_slim/fastmcp/resources/base.py
@@ -214,6 +214,92 @@ class ResourceResult(pydantic.BaseModel):
)
+def _public_content_meta(meta: dict[str, Any] | None) -> dict[str, Any] | None:
+ """Strip FastMCP's internal bookkeeping out of component meta.
+
+ Component `meta` carries private entries under the `fastmcp` namespace
+ (e.g. `_internal.visibility`) that must never reach the wire. Listings
+ already filter these via `FastMCPComponent.get_meta()`; content items
+ served by `resources/read` need the same treatment.
+
+ Returns None when nothing public remains, so resources without user
+ metadata keep an absent `_meta` rather than an empty object.
+ """
+ if not meta:
+ return None
+
+ public = dict(meta)
+ fastmcp_meta = public.get("fastmcp")
+ if isinstance(fastmcp_meta, dict):
+ public_fastmcp = {
+ key: value for key, value in fastmcp_meta.items() if not key.startswith("_")
+ }
+ if public_fastmcp:
+ public["fastmcp"] = public_fastmcp
+ else:
+ public.pop("fastmcp")
+
+ return public or None
+
+
+def convert_raw_to_resource_result(
+ raw_value: Any,
+ *,
+ mime_type: str | None,
+ meta: dict[str, Any] | None,
+) -> ResourceResult:
+ """Wrap a user function's return value in a ResourceResult.
+
+ Shared by `Resource` and `ResourceTemplate` so both honor the MIME type
+ the component declares in listings. A component that advertises
+ `text/csv` must not serve `text/plain` on read.
+
+ Args:
+ raw_value: The value returned by the user's function.
+ mime_type: The component's declared MIME type, forwarded to content items.
+ meta: Component-level meta (e.g. `ui` metadata for MCP Apps CSP/permissions)
+ propagated to each content item.
+ """
+ if isinstance(raw_value, ResourceResult):
+ return raw_value
+
+ meta = _public_content_meta(meta)
+
+ # For plain str/bytes returns, wrap in ResourceContent with the
+ # component's MIME type and meta so the wire response carries the
+ # correct type and metadata (e.g. CSP for MCP Apps).
+ if isinstance(raw_value, (str, bytes)):
+ return ResourceResult(
+ [ResourceContent(raw_value, mime_type=mime_type, meta=meta)]
+ )
+
+ # For JSON-native types (dict, list, tuple, int, float, bool, None),
+ # serialize and wrap in ResourceContent with the component's meta,
+ # matching the str/bytes path above so CSP/permissions propagate.
+ # Exclude list[ResourceContent] which should go through ResourceResult
+ # normalization below.
+ if (
+ isinstance(raw_value, dict | list | tuple | int | float | bool)
+ or raw_value is None
+ ) and not (
+ isinstance(raw_value, list)
+ and raw_value
+ and isinstance(raw_value[0], ResourceContent)
+ ):
+ return ResourceResult(
+ [
+ ResourceContent(
+ json.dumps(raw_value),
+ mime_type=mime_type or "application/json",
+ meta=meta,
+ )
+ ]
+ )
+
+ # All other types fall through to ResourceResult for error handling
+ return ResourceResult(raw_value)
+
+
class Resource(FastMCPComponent):
"""Base class for all resources."""
@@ -324,42 +410,9 @@ class Resource(FastMCPComponent):
MCP Apps CSP/permissions) is propagated to each content item so
that hosts can read it from the ``resources/read`` response.
"""
- if isinstance(raw_value, ResourceResult):
- return raw_value
-
- # For plain str/bytes returns, wrap in ResourceContent with the
- # resource's MIME type and component meta so the wire response
- # carries the correct type and metadata (e.g. CSP for MCP Apps).
- if isinstance(raw_value, (str, bytes)):
- return ResourceResult(
- [ResourceContent(raw_value, mime_type=self.mime_type, meta=self.meta)]
- )
-
- # For JSON-native types (dict, list, tuple, int, float, bool, None),
- # serialize and wrap in ResourceContent with the component's meta,
- # matching the str/bytes path above so CSP/permissions propagate.
- # Exclude list[ResourceContent] which should go through ResourceResult
- # normalization below.
- if (
- isinstance(raw_value, dict | list | tuple | int | float | bool)
- or raw_value is None
- ) and not (
- isinstance(raw_value, list)
- and raw_value
- and isinstance(raw_value[0], ResourceContent)
- ):
- return ResourceResult(
- [
- ResourceContent(
- json.dumps(raw_value),
- mime_type=self.mime_type or "application/json",
- meta=self.meta,
- )
- ]
- )
-
- # All other types fall through to ResourceResult for error handling
- return ResourceResult(raw_value)
+ return convert_raw_to_resource_result(
+ raw_value, mime_type=self.mime_type, meta=self.meta
+ )
@overload
async def _read(self, task_meta: None = None) -> ResourceResult: ...
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index 00cceaeec..2a6622b40 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -23,7 +23,11 @@ from pydantic import (
validate_call,
)
-from fastmcp.resources.base import Resource, ResourceResult
+from fastmcp.resources.base import (
+ Resource,
+ ResourceResult,
+ convert_raw_to_resource_result,
+)
from fastmcp.resources.security import (
INHERIT_SECURITY,
InheritSecurity,
@@ -278,13 +282,13 @@ class ResourceTemplate(FastMCPComponent):
2. In tasks_result_handler() to convert Docket task results to ResourceResult
Handles ResourceResult passthrough and converts raw values using
- ResourceResult's normalization.
+ ResourceResult's normalization. The template's own ``mime_type`` is
+ forwarded so that reads match the MIME type the template advertises
+ in ``resources/templates/list``.
"""
- if isinstance(raw_value, ResourceResult):
- return raw_value
-
- # ResourceResult.__init__ handles all normalization
- return ResourceResult(raw_value)
+ return convert_raw_to_resource_result(
+ raw_value, mime_type=self.mime_type, meta=self.meta
+ )
@overload
async def _read(
diff --git a/fastmcp_slim/fastmcp/server/transforms/visibility.py b/fastmcp_slim/fastmcp/server/transforms/visibility.py
index d294d49ef..0e6a7fe5a 100644
--- a/fastmcp_slim/fastmcp/server/transforms/visibility.py
+++ b/fastmcp_slim/fastmcp/server/transforms/visibility.py
@@ -7,6 +7,7 @@ Final filtering happens at the Provider level.
from __future__ import annotations
+import warnings
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Literal, TypeVar
@@ -81,6 +82,19 @@ class Visibility(Transform):
components: Component types to match (e.g., {"tool", "prompt"}).
match_all: If True, matches all components regardless of other criteria.
"""
+ if keys:
+ malformed = sorted(key for key in keys if "@" not in key)
+ if malformed:
+ warnings.warn(
+ f"Component keys are missing the '@' version delimiter and will "
+ f"match nothing: {malformed}. A key always ends in '@' for an "
+ f"unversioned component (e.g. 'tool:my_tool@') or '@<version>' "
+ f"for a versioned one. Read the value from `component.key`, or "
+ f"filter by `names` instead.",
+ UserWarning,
+ stacklevel=3,
+ )
+
self._enabled = enabled
self.names = names
self.keys = keys
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index d4238cd94..58960c4b7 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -4,7 +4,7 @@ from urllib.parse import quote
import pytest
from pydantic import BaseModel
-from fastmcp import Context, FastMCP
+from fastmcp import Client, Context, FastMCP
from fastmcp.resources import ResourceTemplate
from fastmcp.resources.function_resource import FunctionResource
from fastmcp.resources.template import (
@@ -1014,3 +1014,129 @@ class TestMatchExpandRoundTrip:
"""Expanding params and matching them back reproduces the original values."""
uri = expand_uri_template(template, params)
assert match_uri_template(uri, template) == params
+
+
+class TestTemplateMimeType:
+ """A template must serve the MIME type it advertises in listings."""
+
+ @pytest.mark.parametrize(
+ "declared,expected",
+ [
+ ("text/csv", "text/csv"),
+ ("text/html", "text/html"),
+ (None, "text/plain"),
+ ],
+ )
+ async def test_declared_mime_type_is_served_on_read(
+ self, declared: str | None, expected: str
+ ):
+ """A string return honors the template's declared mime_type."""
+ mcp = FastMCP()
+
+ kwargs = {"mime_type": declared} if declared else {}
+
+ @mcp.resource("data://report/{name}", **kwargs)
+ def report(name: str) -> str:
+ return f"col_a,col_b\n{name},1"
+
+ async with Client(mcp) as client:
+ result = await client.read_resource("data://report/x")
+
+ assert result[0].mime_type == expected
+
+ async def test_read_mime_type_matches_listed_mime_type(self):
+ """resources/templates/list and resources/read must agree."""
+ mcp = FastMCP()
+
+ @mcp.resource("data://item/{id}", mime_type="text/csv")
+ def item(id: str) -> str:
+ return f"id\n{id}"
+
+ async with Client(mcp) as client:
+ listed = await client.list_resource_templates()
+ read = await client.read_resource("data://item/7")
+
+ assert listed[0].mime_type == read[0].mime_type == "text/csv"
+
+ async def test_json_native_return_matches_concrete_resource(self):
+ """A dict return behaves the same for templates and concrete resources."""
+ mcp = FastMCP()
+
+ @mcp.resource("data://concrete")
+ def concrete() -> dict:
+ return {"k": 1}
+
+ @mcp.resource("data://templated/{id}")
+ def templated(id: str) -> dict:
+ return {"k": id}
+
+ async with Client(mcp) as client:
+ concrete_result = await client.read_resource("data://concrete")
+ templated_result = await client.read_resource("data://templated/1")
+
+ assert concrete_result[0].mime_type == templated_result[0].mime_type
+
+ async def test_component_meta_propagates_to_content(self):
+ """Template-level meta reaches content items, as it does for resources."""
+ mcp = FastMCP()
+
+ @mcp.resource("data://tagged/{id}", meta={"team": "infra"})
+ def tagged(id: str) -> str:
+ return id
+
+ async with Client(mcp) as client:
+ result = await client.read_resource("data://tagged/9")
+
+ assert result[0].meta is not None
+ assert result[0].meta["team"] == "infra"
+
+
+class TestInternalMetaNotLeaked:
+ """FastMCP's private visibility marker must never reach the wire."""
+
+ @pytest.mark.parametrize(
+ "uri,read_uri",
+ [
+ ("data://plain", "data://plain"),
+ ("data://tmpl/{id}", "data://tmpl/1"),
+ ],
+ )
+ async def test_visibility_marker_stripped_from_content_meta(
+ self, uri: str, read_uri: str
+ ):
+ """Applying a visibility rule must not add internal meta to content."""
+ mcp = FastMCP()
+
+ if "{" in uri:
+
+ @mcp.resource(uri)
+ def templated(id: str) -> str:
+ return id
+ else:
+
+ @mcp.resource(uri)
+ def concrete() -> str:
+ return "value"
+
+ # Applying any visibility rule stamps the internal marker on meta
+ mcp.enable(names={"templated" if "{" in uri else "concrete"})
+
+ async with Client(mcp) as client:
+ result = await client.read_resource(read_uri)
+
+ assert result[0].meta is None
+
+ async def test_user_meta_survives_stripping(self):
+ """Only the internal namespace is removed; user meta is preserved."""
+ mcp = FastMCP()
+
+ @mcp.resource("data://tagged/{id}", meta={"team": "infra"})
+ def tagged(id: str) -> str:
+ return id
+
+ mcp.enable(names={"tagged"})
+
+ async with Client(mcp) as client:
+ result = await client.read_resource("data://tagged/1")
+
+ assert result[0].meta == {"team": "infra"}
diff --git a/tests/server/transforms/test_visibility.py b/tests/server/transforms/test_visibility.py
index d3434cc4a..73379baf5 100644
--- a/tests/server/transforms/test_visibility.py
+++ b/tests/server/transforms/test_visibility.py
@@ -273,3 +273,50 @@ class TestTransformChain:
enabled = [t for t in result if is_enabled(t)]
assert [t.name for t in enabled] == ["public"]
+
+
+class TestMalformedKeyWarning:
+ """Keys missing the '@' delimiter match nothing, so warn at construction."""
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "tool:my_tool",
+ "resource:data://config",
+ "prompt:analyze",
+ ],
+ )
+ def test_warns_on_key_without_delimiter(self, key: str):
+ """A key with no '@' can never match a real component key."""
+ with pytest.warns(UserWarning, match="missing the '@' version delimiter"):
+ Visibility(False, keys={key})
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "tool:my_tool@",
+ "tool:my_tool@v1",
+ "resource:data://config@",
+ "resource:data://[email protected]/profile@",
+ ],
+ )
+ def test_no_warning_on_well_formed_key(self, key: str, recwarn):
+ """Well-formed keys, including URIs containing '@', pass silently."""
+ Visibility(False, keys={key})
+ assert [w for w in recwarn if issubclass(w.category, UserWarning)] == []
+
+ def test_warning_lists_only_malformed_keys(self):
+ """The message names the offending keys and omits the valid ones."""
+ with pytest.warns(UserWarning) as record:
+ Visibility(False, keys={"tool:good@", "tool:bad"})
+
+ message = str(record[0].message)
+ assert "tool:bad" in message
+ assert "tool:good@" not in message
+
+ def test_other_filters_do_not_warn(self, recwarn):
+ """Only `keys` is subject to this validation."""
+ Visibility(False, names={"my_tool"})
+ Visibility(False, tags={"internal"})
+ Visibility(False, match_all=True)
+ assert [w for w in recwarn if issubclass(w.category, UserWarning)] == []