Skip to content

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

Strip internal visibility meta from prompt results and static resources (#5330)

Asem ahmed43c54b49f1af
diff --git a/fastmcp_slim/fastmcp/prompts/base.py b/fastmcp_slim/fastmcp/prompts/base.py
index b7e4fa3f6..c9c8e7625 100644
--- a/fastmcp_slim/fastmcp/prompts/base.py
+++ b/fastmcp_slim/fastmcp/prompts/base.py
@@ -26,7 +26,7 @@ from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
from fastmcp.utilities.authorization import AuthCheck
-from fastmcp.utilities.components import FastMCPComponent
+from fastmcp.utilities.components import FastMCPComponent, public_result_meta
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
FastMCPBaseModel,
@@ -327,7 +327,11 @@ class Prompt(FastMCPComponent):
return InputRequiredPromptResult(raw_value)
if isinstance(raw_value, str):
- return PromptResult(raw_value, description=self.description, meta=self.meta)
+ return PromptResult(
+ raw_value,
+ description=self.description,
+ meta=public_result_meta(self.meta),
+ )
if isinstance(raw_value, list | tuple):
messages: list[Message] = []
@@ -341,7 +345,11 @@ class Prompt(FastMCPComponent):
f"messages[{i}] must be Message or str, got {type(item).__name__}. "
f"Use Message({item!r}) to wrap the value."
)
- return PromptResult(messages, description=self.description, meta=self.meta)
+ return PromptResult(
+ messages,
+ description=self.description,
+ meta=public_result_meta(self.meta),
+ )
raise TypeError(
f"Prompt must return str, list[Message], or PromptResult, "
diff --git a/fastmcp_slim/fastmcp/resources/base.py b/fastmcp_slim/fastmcp/resources/base.py
index 30ed132ea..db4a78294 100644
--- a/fastmcp_slim/fastmcp/resources/base.py
+++ b/fastmcp_slim/fastmcp/resources/base.py
@@ -28,7 +28,7 @@ from pydantic.json_schema import SkipJsonSchema
from typing_extensions import Self
from fastmcp.utilities.authorization import AuthCheck
-from fastmcp.utilities.components import FastMCPComponent
+from fastmcp.utilities.components import FastMCPComponent, public_result_meta
class ResourceContent(pydantic.BaseModel):
@@ -239,34 +239,6 @@ class InputRequiredResourceResult(ResourceResult):
)
-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,
*,
@@ -294,7 +266,7 @@ def convert_raw_to_resource_result(
# handler unwraps it.
return InputRequiredResourceResult(raw_value)
- meta = _public_content_meta(meta)
+ meta = public_result_meta(meta)
# For plain str/bytes returns, wrap in ResourceContent with the
# component's MIME type and meta so the wire response carries the
diff --git a/fastmcp_slim/fastmcp/resources/types.py b/fastmcp_slim/fastmcp/resources/types.py
index 19b3b90a9..8aa6260e2 100644
--- a/fastmcp_slim/fastmcp/resources/types.py
+++ b/fastmcp_slim/fastmcp/resources/types.py
@@ -13,6 +13,7 @@ from typing_extensions import override
from fastmcp.exceptions import ResourceError
from fastmcp.resources.base import Resource, ResourceContent, ResourceResult
+from fastmcp.utilities.components import public_result_meta
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
@@ -28,7 +29,9 @@ class TextResource(Resource):
return ResourceResult(
contents=[
ResourceContent(
- content=self.text, mime_type=self.mime_type, meta=self.meta
+ content=self.text,
+ mime_type=self.mime_type,
+ meta=public_result_meta(self.meta),
)
]
)
@@ -44,7 +47,9 @@ class BinaryResource(Resource):
return ResourceResult(
contents=[
ResourceContent(
- content=self.data, mime_type=self.mime_type, meta=self.meta
+ content=self.data,
+ mime_type=self.mime_type,
+ meta=public_result_meta(self.meta),
)
]
)
diff --git a/fastmcp_slim/fastmcp/utilities/components.py b/fastmcp_slim/fastmcp/utilities/components.py
index b59ac9b73..68d9feb57 100644
--- a/fastmcp_slim/fastmcp/utilities/components.py
+++ b/fastmcp_slim/fastmcp/utilities/components.py
@@ -36,6 +36,35 @@ def get_fastmcp_metadata(meta: dict[str, Any] | None) -> FastMCPMeta:
return {}
+def public_result_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()`; results that
+ carry component meta (resource contents, prompt results) need the same
+ treatment.
+
+ Returns None when nothing public remains, so components 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_set_default_none(maybe_set: set[T] | Sequence[T] | None) -> set[T]:
"""Convert a sequence to a set, defaulting to an empty set if None."""
if maybe_set is None:
diff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.py
index d44668783..841c173da 100644
--- a/tests/prompts/test_prompt.py
+++ b/tests/prompts/test_prompt.py
@@ -5,6 +5,7 @@ import pytest
from mcp_types import EmbeddedResource, TextResourceContents
from pydantic import Field
+from fastmcp import Client, FastMCP
from fastmcp.prompts.base import (
Message,
Prompt,
@@ -783,6 +784,27 @@ class TestPromptResult:
assert mcp_result.meta == {"key": "value"}
+class TestInternalMetaNotLeaked:
+ """FastMCP's private visibility marker must never reach the wire."""
+
+ async def test_visibility_marker_stripped_from_result_meta(self):
+ mcp = FastMCP()
+
+ @mcp.prompt(meta={"team": "infra", "fastmcp": {"owner": "docs"}})
+ def greet(name: str) -> str:
+ return f"Hello {name}"
+
+ # Applying any visibility rule stamps the internal marker on meta
+ mcp.enable(names={"greet"})
+
+ async with Client(mcp) as client:
+ result = await client.get_prompt("greet", {"name": "Ada"})
+
+ assert result.meta is not None
+ assert result.meta["team"] == "infra"
+ assert result.meta["fastmcp"] == {"owner": "docs"}
+
+
class TestPromptFieldDefaults:
"""Test prompts with Field() defaults."""
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index cdc8c0081..14f453b36 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -14,6 +14,7 @@ from fastmcp.resources.template import (
expand_uri_template,
match_uri_template,
)
+from fastmcp.resources.types import BinaryResource, TextResource
from fastmcp.server import create_proxy
@@ -1455,6 +1456,25 @@ class TestInternalMetaNotLeaked:
assert result[0].meta is None
+ @pytest.mark.parametrize(
+ "resource",
+ [
+ TextResource(uri="data://text", name="text", text="value"),
+ BinaryResource(uri="data://binary", name="binary", data=b"value"),
+ ],
+ )
+ async def test_visibility_marker_stripped_from_static_resource_meta(
+ self, resource: TextResource | BinaryResource
+ ):
+ mcp = FastMCP()
+ mcp.add_resource(resource)
+ mcp.enable(names={str(resource.uri)})
+
+ async with Client(mcp) as client:
+ result = await client.read_resource(str(resource.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()