π The fast, Pythonic way to build MCP servers and clients.
Apply transforms, enabled state, and auth to hashed tool lookups (#5415)
Jeremiah Lowin21dc2a038e85
diff --git a/docs/apps/architecture.mdx b/docs/apps/architecture.mdxindex c7f316be3..9e0ff1826 100644--- a/docs/apps/architecture.mdx+++ b/docs/apps/architecture.mdx@@ -95,17 +95,15 @@ Give each copy its own app name. Two tenants running the same product want `Fast### The hashed lookup fallback-The identity-addressed form `<hash>_<local_name>` remains callable. FastMCP first tries normal tool resolution; if no tool matches and the name has that shape, it calls `get_tool_by_hash(hash, local_name)`, which walks the provider tree directly, skipping transforms.+The identity-addressed form `<hash>_<local_name>` remains callable. FastMCP first tries normal tool resolution; if no tool matches and the name has that shape, it calls `get_tool_by_hash(hash, local_name)`, which resolves the tool through the same lookup as its listed name. Transforms, enabled state, and authorization apply to a hashed name exactly as they do to a name call.When one identity is claimed by more than one tool β which happens when the same app is composed into two branches β the call is refused rather than resolved, since picking either one would silently route into the wrong branch.-Authorization still applies. The hashed path skips name and visibility transforms, but auth checks still run against the tool's `auth` config before execution.-Hashed tool names provide stable routing identities, not secrets or access controls. Knowing a hashed name grants no additional authorization, and hiding it from a model's tool list does not restrict access.### Provider delegation-`get_tool_by_hash` is defined on the `Provider` base class and overridden by aggregate and wrapped providers. Aggregate providers fan out the lookup across child providers in parallel. Wrapped providers (like `FastMCPProvider`, which wraps a nested `FastMCP` server) delegate to the inner server's hashed lookup. Backend tools are reachable through any depth of composition.+`get_tool_by_hash` is defined on the `Provider` base class. Providers override `_get_tool_by_hash` to find a tool by its identity, and the base class resolves the result through the provider's public `get_tool`. Aggregate providers fan out the lookup across child providers in parallel. Wrapped providers (like `FastMCPProvider`, which wraps a nested `FastMCP` server) delegate to the inner server's hashed lookup. Backend tools are reachable through any depth of composition.## The rendererdiff --git a/fastmcp_remote/fastmcp_remote/cli.py b/fastmcp_remote/fastmcp_remote/cli.pyindex 6c917eef9..f72aacb6c 100644--- a/fastmcp_remote/fastmcp_remote/cli.py+++ b/fastmcp_remote/fastmcp_remote/cli.py@@ -23,6 +23,7 @@ from fastmcp import Clientfrom fastmcp.client.auth import OAuthfrom fastmcp.client.transports import SSETransport, StreamableHttpTransportfrom fastmcp.server import create_proxy+from fastmcp.server.providers.proxy import FastMCPProxyfrom fastmcp.server.transforms import GetToolNext, Transformfrom fastmcp.tools import Toolfrom fastmcp.utilities.versions import VersionSpec@@ -259,15 +260,19 @@ def build_transport(config: RemoteConfig) -> SSETransport | StreamableHttpTransp)-async def run(config: RemoteConfig) -> None:- client = Client(build_transport(config))+def build_proxy(client: Client, ignore_tools: Sequence[str]) -> FastMCPProxy:server = create_proxy(client,name="fastmcp-remote",provider_error_strategy="raise",)- if config.ignore_tools:- server.add_transform(IgnoreTools(config.ignore_tools))+ if ignore_tools:+ server.add_transform(IgnoreTools(ignore_tools))+ return server+++async def run(config: RemoteConfig) -> None:+ server = build_proxy(Client(build_transport(config)), config.ignore_tools)await server.run_async(transport="stdio",show_banner=config.show_banner,diff --git a/fastmcp_slim/fastmcp/server/providers/addressing.py b/fastmcp_slim/fastmcp/server/providers/addressing.pyindex 7a9b09d4b..5b8ef0a27 100644--- a/fastmcp_slim/fastmcp/server/providers/addressing.py+++ b/fastmcp_slim/fastmcp/server/providers/addressing.py@@ -4,9 +4,10 @@ Each FastMCPApp backend tool gets a deterministic hash computed from itsapp name + tool name. The hash serves two purposes:1. **Backend-tool routing.** Tools with ``"app"`` in their visibility are- callable via ``<hash>_<local_name>``. The dispatcher parses the prefix,- then walks providers recursively (same pattern as the old ``get_app_tool``)- to find a tool whose stored hash matches.+ callable via ``<hash>_<local_name>``. The dispatcher parses the prefix+ and calls ``get_tool_by_hash``, which finds the tool whose stored hash+ matches and applies the same transforms, visibility, and auth as a lookup+ by the tool's listed name.2. **Per-tool Prefab renderer URIs.** Each prefab tool gets a unique rendererresource at ``ui://prefab/tool/<hash>/renderer.html``. ``list_resources``@@ -28,6 +29,10 @@ forwarding, so it must survive the wire.from __future__ import annotationsimport hashlib+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from fastmcp.tools.base import Tool#: Length of the hex hash prefix used in URIs and backend-tool names.HASH_LENGTH = 12@@ -45,6 +50,26 @@ def hash_tool(app_name: str, tool_name: str) -> str:return hashlib.sha256(payload).hexdigest()[:HASH_LENGTH]+def tool_identity(tool: Tool) -> str | None:+ """Read a tool's stored identity hash, if it carries one."""+ meta = tool.meta+ if not meta:+ return None+ fastmcp_meta = meta.get("fastmcp")+ if not isinstance(fastmcp_meta, dict):+ return None+ identity = fastmcp_meta.get(TOOL_HASH_META_KEY)+ return identity if isinstance(identity, str) else None+++def is_app_tool_with_identity(tool: Tool, tool_hash: str) -> bool:+ """Whether a tool carries this identity hash and is callable by apps."""+ meta = tool.meta or {}+ ui_meta = meta.get("ui")+ visibility = ui_meta.get("visibility", []) if isinstance(ui_meta, dict) else []+ return tool_identity(tool) == tool_hash and "app" in visibility++def hashed_backend_name(app_name: str, tool_name: str) -> str:"""Format the universal name for a backend tool: ``<hash>_<local_name>``."""return f"{hash_tool(app_name, tool_name)}_{tool_name}"diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.pyindex 3334c7ff0..a31cb7a01 100644--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py@@ -286,9 +286,12 @@ class AggregateProvider(Provider):return rreturn None- async def get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:+ async def _get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:"""Query all child providers for a tool matching a hash.+ Each child applies its own transforms, so a child that hides the tool+ does not answer.+The hash identifies a tool by app name and registered name, with nomount-point component, so composing one app into two branches yieldstwo distinct tools claiming the same identity. That is ambiguousdiff --git a/fastmcp_slim/fastmcp/server/providers/base.py b/fastmcp_slim/fastmcp/server/providers/base.pyindex 1eb08f663..8119a5e81 100644--- a/fastmcp_slim/fastmcp/server/providers/base.py+++ b/fastmcp_slim/fastmcp/server/providers/base.py@@ -30,11 +30,17 @@ from __future__ import annotationsfrom collections.abc import AsyncIterator, Iterator, Sequencefrom contextlib import asynccontextmanager, contextmanager+from contextvars import ContextVar+from dataclasses import dataclassfrom functools import partialfrom typing import TYPE_CHECKING, Any, Literal, TypeVar, castfrom typing_extensions import Self+from fastmcp.server.providers.addressing import (+ is_app_tool_with_identity,+ tool_identity,+)from fastmcp.server.transforms.visibility import Visibilityfrom fastmcp.utilities.async_utils import gatherfrom fastmcp.utilities.components import FastMCPComponent@@ -209,7 +215,15 @@ class Provider:"""async def base(n: str, *, version: VersionSpec | None = None) -> Tool | None:- return await self._get_tool(n, version)+ found = hashed_lookup_target(self)+ if found is None or n != found.name:+ return await self._get_tool(n, version)+ if version is None or version.matches(found.version):+ return await self._check_hashed_target(found)+ other = await self._get_tool(n, version)+ if other is not None and tool_identity(other) == tool_identity(found):+ return other+ return Nonechain: GetToolNext = cast("GetToolNext", base)for transform in self.transforms:@@ -247,28 +261,74 @@ class Provider:return Noneasync def get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:- """Look up an app-visible tool by its deterministic hash.+ """Get an app-visible tool by its identity hash, through `get_tool()`.++ The identity hash survives renaming, so `_get_tool_by_hash()` finds+ the tool beneath this provider's transforms. Its name above the+ transforms comes from their listing, and the tool is then looked up+ under that name with `get_tool()`, the same public lookup a name call+ uses. While that lookup runs, the bottom of the chain answers the+ found tool for its own name and looks up every other name as usual,+ so transforms and `get_tool()` overrides decide exactly as they would+ for a name call, while a different tool sharing the name cannot take+ the found tool's place. A version constraint the found tool does not+ meet is looked up as usual and accepted only for the same identity.+ A nested lookup of that same name on this provider while the hashed+ lookup runs resolves to the found tool; tasks started during the+ lookup resolve names as usual once it finishes.++ Note: Like `get_tool()`, this does NOT filter disabled components. The+ Server (FastMCP) performs enabled filtering after all transforms.++ Args:+ tool_hash: The identity hash from a `<hash>_<local_name>` name.+ tool_name: The local tool name from the same name.- Same recursive-walk semantics as ``get_app_tool`` but matches on- ``meta["fastmcp"]["tool_hash"]`` instead of the app name tag.- Used by the dispatcher when receiving hashed backend-tool calls.+ Returns:+ The tool if found and not hidden (may be marked disabled), else None."""- from fastmcp.server.providers.addressing import TOOL_HASH_META_KEY+ found = await self._get_tool_by_hash(tool_hash, tool_name)+ if found is None:+ return None+ name = await _listed_name(self.transforms, found)+ if name is None:+ return None+ state = _HashedLookup(provider=self, tool=found)+ token = _hashed_lookup.set(state)+ try:+ tool = await self.get_tool(name)+ finally:+ state.active = False+ _hashed_lookup.reset(token)++ if tool is None or tool_identity(tool) != tool_hash:+ return None+ return tool++ async def _check_hashed_target(self, tool: Tool) -> Tool | None:+ """Apply this provider's own checks to the tool a hashed lookup found.++ During `get_tool_by_hash()` the bottom of the `get_tool()` chain+ answers the found tool in place of `_get_tool()`. A provider whose+ `_get_tool()` checks the tool it returns, as the server does for auth,+ overrides this to make the same check, so the found tool is checked+ before any transform runs, as a name lookup checks it. The default+ accepts the tool.+ """+ return tool++ async def _get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:+ """Look up an app-visible tool by its identity hash, before transforms.++ Matches on ``meta["fastmcp"]["tool_hash"]`` and requires ``"app"`` in+ the tool's visibility. The default looks the tool up by its local name+ via `_get_tool()`. Providers whose tools can be renamed beneath them+ override this to search by identity instead.+ """tool = await self._get_tool(tool_name)- if tool is not None:- meta = tool.meta or {}- fastmcp_meta = meta.get("fastmcp")- ui_meta = meta.get("ui")- visibility = (- ui_meta.get("visibility", []) if isinstance(ui_meta, dict) else []- )- if (- isinstance(fastmcp_meta, dict)- and fastmcp_meta.get(TOOL_HASH_META_KEY) == tool_hash- and "app" in visibility- ):- return tool+ if tool is not None and is_app_tool_with_identity(tool, tool_hash):+ return toolreturn Noneasync def list_resources(self) -> Sequence[Resource]:@@ -712,3 +772,54 @@ class Provider:))return self+++@dataclass+class _HashedLookup:+ """A running `get_tool_by_hash()` on one provider.++ Tasks started during the lookup copy the context that holds this object,+ so `active` is cleared when the lookup ends rather than relying on the+ context variable being reset in every copy.+ """++ provider: Provider+ tool: Tool+ active: bool = True+++_hashed_lookup: ContextVar[_HashedLookup | None] = ContextVar(+ "_hashed_lookup", default=None+)+++def hashed_lookup_target(provider: Provider) -> Tool | None:+ """The tool a running `get_tool_by_hash()` on `provider` found, if any."""+ current = _hashed_lookup.get()+ if current is None or not current.active or current.provider is not provider:+ return None+ return current.tool+++async def _listed_name(transforms: Sequence[Transform], tool: Tool) -> str | None:+ """The name `tool` is listed under after passing through `transforms`.++ Each transform's listing gives the tool's name above it. A transform that+ does not list the tool, such as a catalog transform that replaces the+ listing, leaves the name unchanged, which is the name a lookup through it+ would use. Returns None if a transform lists the identity under more+ than one name.+ """+ identity = tool_identity(tool)+ current = tool+ for transform in transforms:+ listed = [+ t+ for t in await transform.list_tools([current])+ if tool_identity(t) == identity+ ]+ if len({t.name for t in listed}) > 1:+ return None+ if listed:+ current = listed[0]+ return current.namediff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.pyindex 46cb1d71c..d71675b5c 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -464,8 +464,14 @@ class FastMCPProvider(Provider):wrapped._original_name = hashed_backend_name(app_name, tool_name)return wrapped- async def get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:- """Delegate to nested server's get_tool_by_hash, wrapping for middleware."""+ async def _get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:+ """Delegate to nested server's get_tool_by_hash, wrapping for middleware.++ The nested server applies its own transforms, visibility, and auth.+ The call is forwarded under the hashed name so the nested server+ resolves the same tool again rather than whatever its listed name+ reaches.+ """raw_tool = await self.server.get_tool_by_hash(tool_hash, tool_name)if raw_tool is None:return Nonediff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.pyindex 23f04a3f7..967c4858a 100644--- a/fastmcp_slim/fastmcp/server/providers/proxy.py+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py@@ -57,6 +57,7 @@ from fastmcp.resources.template import forward_urifrom fastmcp.server.context import Contextfrom fastmcp.server.dependencies import fastmcp_request_ctx, get_contextfrom fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext+from fastmcp.server.providers.addressing import is_app_tool_with_identityfrom fastmcp.server.providers.aggregate import ProviderErrorStrategyfrom fastmcp.server.providers.base import Providerfrom fastmcp.server.server import FastMCP@@ -951,7 +952,7 @@ class ProxyProvider(Provider):return Nonereturn max(matching, key=version_sort_key)- async def get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:+ async def _get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:"""Resolve an identity against the remote listing.The base implementation looks the tool up by its registered name,@@ -965,28 +966,15 @@ class ProxyProvider(Provider):on the same terms ``AggregateProvider`` refuses it, so a duplicatedapp is caught wherever it is composed rather than only nearby."""- from fastmcp.server.providers.addressing import TOOL_HASH_META_KEY-cache = self._tools_cacheif cache is None or not cache.is_fresh(self._cache_ttl):await self._list_tools()cache = self._tools_cacheassert cache is not None- matches: list[Tool] = []- for tool in cache.items:- meta = tool.meta or {}- fastmcp_meta = meta.get("fastmcp")- ui_meta = meta.get("ui")- visibility = (- ui_meta.get("visibility", []) if isinstance(ui_meta, dict) else []- )- if (- isinstance(fastmcp_meta, dict)- and fastmcp_meta.get(TOOL_HASH_META_KEY) == tool_hash- and "app" in visibility- ):- matches.append(tool)+ matches = [+ tool for tool in cache.items if is_app_tool_with_identity(tool, tool_hash)+ ]if not matches:return Nonediff --git a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.pyindex 1e0beed4a..b844c06c1 100644--- a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py@@ -80,8 +80,8 @@ class _WrappedProvider(Provider):"""Delegate to inner, bypassing this wrapper's transforms."""return await self._inner.get_app_tool(app_name, tool_name)- async def get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:- """Delegate to inner, bypassing this wrapper's transforms."""+ async def _get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None:+ """Delegate to inner's get_tool_by_hash (includes inner's transforms)."""return await self._inner.get_tool_by_hash(tool_hash, tool_name)async def _list_resources(self) -> Sequence[Resource]:diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex c6cfd1057..24aba653a 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -89,7 +89,12 @@ from fastmcp.server.middleware.middleware import (from fastmcp.server.mixins import LifespanMixin, MCPOperationsMixin, TransportMixinfrom fastmcp.server.mixins.extensions import ExtensionsMixinfrom fastmcp.server.providers import LocalProvider, Provider+from fastmcp.server.providers.addressing import (+ parse_hashed_backend_name,+ tool_identity,+)from fastmcp.server.providers.aggregate import AggregateProvider+from fastmcp.server.providers.base import hashed_lookup_targetfrom fastmcp.server.telemetry import server_spanfrom fastmcp.server.transforms import (ToolTransform,@@ -249,20 +254,6 @@ def _get_auth_context() -> tuple[bool, Any]:return (False, get_access_token())-def _tool_identity(tool: Tool) -> str | None:- """Read a tool's stable identity hash, if it carries one."""- from fastmcp.server.providers.addressing import TOOL_HASH_META_KEY-- meta = tool.meta- if not meta:- return None- fastmcp_meta = meta.get("fastmcp")- if not isinstance(fastmcp_meta, dict):- return None- identity = fastmcp_meta.get(TOOL_HASH_META_KEY)- return identity if isinstance(identity, str) else None--@asynccontextmanagerasync def default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any]:"""Default lifespan context manager that does nothing.@@ -715,7 +706,7 @@ class FastMCP(claimed_by: dict[str, list[Tool]] = {}owners_of: dict[str, set[str | None]] = {}for tool in await self.list_tools():- identity = _tool_identity(tool)+ identity = tool_identity(tool)owners_of.setdefault(tool.name, set()).add(identity)if identity is not None:claimed_by.setdefault(identity, []).append(tool)@@ -858,6 +849,10 @@ class FastMCP(return None# Component auth - return None if unauthorized (consistent with list filtering)+ return await self._check_auth(tool)++ async def _check_auth(self, tool: Tool) -> Tool | None:+ """Return the tool if the current request may use it, else None."""skip_auth, token = _get_auth_context()if not skip_auth and tool.auth is not None:ctx = AuthContext(token=token, component=tool)@@ -869,6 +864,10 @@ class FastMCP(return tool+ async def _check_hashed_target(self, tool: Tool) -> Tool | None:+ """Check auth on the found tool, as `_get_tool()` does for a name."""+ return await self._check_auth(tool)+async def get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None:@@ -904,6 +903,12 @@ class FastMCP(return Noneall_tools = [t for t in await super().list_tools() if t.name == name]+ # During a hashed lookup, only versions of the identity being looked+ # up qualify; another tool listed under the same name does not.+ found = hashed_lookup_target(self)+ if found is not None:+ identity = tool_identity(found)+ all_tools = [t for t in all_tools if tool_identity(t) == identity]all_tools = list(await apply_session_transforms(all_tools))enabled = [t for t in all_tools if is_enabled(t)]@@ -1352,18 +1357,13 @@ class FastMCP(# For mounted servers, the parent's provider sets fn_key to the# namespaced key before delegating, ensuring correct Docket routing.- from fastmcp.server.providers.addressing import (- parse_hashed_backend_name,- )-# Two routing paths:- # 1. Hashed-name path β backend tools that opted into- # app-callable visibility. Recognized by their- # `<hash>_<local_name>` format and resolved via the- # reverse-hash map. Address is known eagerly.- # 2. Display-name path β everything else. Goes through normal- # `get_tool` aggregation/transforms. Address is determined- # after resolution by walking the registry.+ # 1. Display-name path β the name this server lists the tool+ # under, resolved through `get_tool`.+ # 2. Hashed-name path β backend tools that opted into+ # app-callable visibility, addressed as `<hash>_<local_name>`+ # and resolved through `get_tool_by_hash`. It applies the same+ # transforms, visibility, and auth as the display-name path.async with fastmcp.server.context.Context(fastmcp=self) as ctx:if run_middleware:mw_context = MiddlewareContext[CallToolRequestParams](@@ -1419,27 +1419,13 @@ class FastMCP(# Try normal display-name resolution first.tool: Tool | None = await self.get_tool(name, version=version)- # If that fails, try hashed-name dispatch. This walks- # the provider tree recursively (same pattern as the old- # get_app_tool) looking for a tool whose stored hash- # matches the parsed prefix.+ # If that fails, try hashed-name dispatch, which finds the+ # tool whose stored hash matches the parsed prefix.if tool is None:hashed = parse_hashed_backend_name(name)if hashed is not None:digest, local_name = hashedtool = await self.get_tool_by_hash(digest, local_name)- if tool is not None:- # Auth still applies on the bypass path.- skip_auth, token = _get_auth_context()- if not skip_auth and tool.auth is not None:- try:- auth_ctx = AuthContext(token=token, component=tool)- if not await run_auth_checks(tool.auth, auth_ctx):- raise NotFoundError(f"Unknown tool: {name!r}")- except AuthorizationError:- raise NotFoundError(- f"Unknown tool: {name!r}"- ) from Noneif tool is None:raise NotFoundError(f"Unknown tool: {name!r}")diff --git a/tests/cli/test_fastmcp_remote.py b/tests/cli/test_fastmcp_remote.pyindex 522bc0190..ffa67956a 100644--- a/tests/cli/test_fastmcp_remote.py+++ b/tests/cli/test_fastmcp_remote.py@@ -2,12 +2,16 @@ from pathlib import Pathimport pytest+from fastmcp import Client, FastMCP, FastMCPAppfrom fastmcp.client.auth import OAuthfrom fastmcp.client.transports import SSETransport, StreamableHttpTransport+from fastmcp.exceptions import ToolError+from fastmcp.server.providers.addressing import hashed_backend_namefrom fastmcp.tools import FunctionToolfrom fastmcp.utilities.versions import VersionSpecfrom fastmcp_remote.cli import (IgnoreTools,+ build_proxy,build_transport,parse_args,parse_header,@@ -252,3 +256,78 @@ async def test_ignore_tools_transform_filters_matching_names():assert await transform.list_tools([tool]) == []assert await transform.get_tool("delete_user", call_next) is None+++def records_remote(calls: list[str]) -> FastMCP:+ app = FastMCPApp("records")++ @app.tool()+ def delete_records(marker: str) -> str:+ calls.append(marker)+ return f"ran {marker}"++ remote = FastMCP("remote")+ remote.add_provider(app)+ return remote++[email protected]("pattern", ["delete_records", "delete*", "*"])+async def test_ignored_tool_is_unknown_by_listed_and_hashed_name(pattern: str):+ calls: list[str] = []+ proxy = build_proxy(Client(records_remote(calls)), [pattern])++ async with Client(proxy) as client:+ assert "delete_records" not in [t.name for t in await client.list_tools()]+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool("delete_records", {"marker": "by-name"})+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(+ hashed_backend_name("records", "delete_records"),+ {"marker": "by-hash"},+ )++ assert calls == []+++async def test_ignore_pattern_matches_remote_namespaced_name_for_hashed_calls():+ calls: list[str] = []+ app = FastMCPApp("contacts")++ @app.tool()+ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ remote = FastMCP("remote")+ remote.add_provider(app, namespace="crm")+ proxy = build_proxy(Client(remote), ["crm_*"])++ async with Client(proxy) as client:+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(+ hashed_backend_name("contacts", "save"), {"name": "alice"}+ )++ assert calls == []+++async def test_tool_not_ignored_is_callable_by_hashed_name():+ calls: list[str] = []+ app = FastMCPApp("contacts")++ @app.tool()+ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ remote = FastMCP("remote")+ remote.add_provider(app)+ proxy = build_proxy(Client(remote), ["delete*"])++ async with Client(proxy) as client:+ result = await client.call_tool(+ hashed_backend_name("contacts", "save"), {"name": "alice"}+ )++ assert result.data == "saved alice"+ assert calls == ["alice"]diff --git a/tests/server/test_hashed_tool_dispatch.py b/tests/server/test_hashed_tool_dispatch.pynew file mode 100644index 000000000..dbf55f2e7--- /dev/null+++ b/tests/server/test_hashed_tool_dispatch.py@@ -0,0 +1,539 @@+"""Hashed tool names follow the same lookup rules as listed names.++A FastMCPApp backend tool is also callable by its identity-addressed name,+`<hash>_<local_name>`. Calling a tool that way resolves the same tool, with+the same transforms, enabled state, auth, and version fallback, as calling it+by the name the server lists it under.+"""++from __future__ import annotations++import asyncio+from collections.abc import Callable, Sequence++import pytest++from fastmcp import Client, Context, FastMCP, FastMCPApp+from fastmcp.exceptions import ToolError+from fastmcp.server.auth import require_scopes, restrict_tag+from fastmcp.server.providers.addressing import hashed_backend_name+from fastmcp.server.providers.proxy import ProxyClient, ProxyProvider+from fastmcp.server.transforms import GetToolNext, Transform, VersionFilter+from fastmcp.server.transforms.tool_transform import ToolTransform+from fastmcp.tools.base import Tool+from fastmcp.tools.tool_transform import ToolTransformConfig+from fastmcp.utilities.versions import VersionSpec++SAVE = hashed_backend_name("contacts", "save")+++class FilterTools(Transform):+ """Drops the named tools from both listing and lookup."""++ def __init__(self, *names: str) -> None:+ self.names = set(names)++ async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:+ return [t for t in tools if t.name not in self.names]++ async def get_tool(+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None+ ) -> Tool | None:+ if name in self.names:+ return None+ return await call_next(name, version=version)+++class RefuseLookup(Transform):+ """Lists every tool but refuses to resolve the named ones."""++ def __init__(self, *names: str) -> None:+ self.names = set(names)++ async def get_tool(+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None+ ) -> Tool | None:+ if name in self.names:+ return None+ return await call_next(name, version=version)+++def contacts_app(calls: list[str]) -> FastMCPApp:+ app = FastMCPApp("contacts")++ @app.tool()+ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ return app+++def tagged_contacts_app(calls: list[str]) -> FastMCPApp:+ app = FastMCPApp("contacts")++ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ app.add_tool(Tool.from_function(save, tags={"internal"}))+ return app+++def server_with(app: FastMCPApp) -> FastMCP:+ server = FastMCP("Child")+ server.add_provider(app)+ return server+++def filtered_by_server_transform(calls: list[str]) -> FastMCP:+ server = server_with(contacts_app(calls))+ server.add_transform(FilterTools("save"))+ return server+++def filtered_by_provider_transform(calls: list[str]) -> FastMCP:+ app = contacts_app(calls)+ app.add_transform(FilterTools("save"))+ return server_with(app)+++def filtered_under_its_namespaced_name(calls: list[str]) -> FastMCP:+ server = FastMCP("Platform")+ server.add_provider(contacts_app(calls), namespace="crm")+ server.add_transform(FilterTools("crm_save"))+ return server+++def filtered_by_mounted_server_transform(calls: list[str]) -> FastMCP:+ child = server_with(contacts_app(calls))+ child.add_transform(FilterTools("save"))+ server = FastMCP("Platform")+ server.mount(child, namespace="child")+ return server+++def filtered_by_gateway_transform_over_a_proxy(calls: list[str]) -> FastMCP:+ backend = server_with(contacts_app(calls))+ gateway = FastMCP("Gateway")+ gateway.add_provider(ProxyProvider(lambda: ProxyClient(backend)))+ gateway.add_transform(FilterTools("save"))+ return gateway+++def refused_by_lookup_only_transform(calls: list[str]) -> FastMCP:+ server = server_with(contacts_app(calls))+ server.add_transform(RefuseLookup("save"))+ return server+++def disabled_by_name(calls: list[str]) -> FastMCP:+ server = server_with(contacts_app(calls))+ server.disable(names={"save"})+ return server+++def disabled_by_tag(calls: list[str]) -> FastMCP:+ server = server_with(tagged_contacts_app(calls))+ server.disable(tags={"internal"})+ return server+++def disabled_on_the_provider(calls: list[str]) -> FastMCP:+ app = contacts_app(calls)+ app.disable(names={"save"})+ return server_with(app)+++def disabled_in_a_mounted_server(calls: list[str]) -> FastMCP:+ child = server_with(contacts_app(calls))+ child.disable(names={"save"})+ server = FastMCP("Platform")+ server.mount(child, namespace="child")+ return server+++ "build",+ [+ filtered_by_server_transform,+ filtered_by_provider_transform,+ filtered_under_its_namespaced_name,+ filtered_by_mounted_server_transform,+ filtered_by_gateway_transform_over_a_proxy,+ refused_by_lookup_only_transform,+ disabled_by_name,+ disabled_by_tag,+ disabled_on_the_provider,+ disabled_in_a_mounted_server,+ ],+)+async def test_hashed_name_is_unknown_when_listed_name_is_unknown(+ build: Callable[[list[str]], FastMCP],+):+ calls: list[str] = []+ server = build(calls)++ async with Client(server) as client:+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(SAVE, {"name": "alice"})++ assert calls == []+++async def test_session_disable_applies_to_hashed_name():+ calls: list[str] = []+ server = server_with(contacts_app(calls))++ @server.tool+ async def lock(ctx: Context) -> str:+ await ctx.disable_components(names={"save"})+ return "locked"++ async with Client(server, mode="legacy") as client:+ await client.call_tool(SAVE, {"name": "before"})+ await client.call_tool("lock", {})+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(SAVE, {"name": "after"})++ assert calls == ["before"]+++def renamed_by_tool_transform(calls: list[str]) -> FastMCP:+ server = server_with(contacts_app(calls))+ server.add_transform(ToolTransform({"save": ToolTransformConfig(name="store")}))+ return server+++def renamed_by_mount(calls: list[str]) -> FastMCP:+ server = FastMCP("Platform")+ server.mount(+ server_with(contacts_app(calls)),+ namespace="child",+ tool_names={"save": "store"},+ )+ return server+++def beside_an_unrelated_filter(calls: list[str]) -> FastMCP:+ server = server_with(contacts_app(calls))+ server.add_transform(FilterTools("unrelated"))+ return server+++ "build",+ [+ renamed_by_tool_transform,+ renamed_by_mount,+ beside_an_unrelated_filter,+ ],+)+async def test_hashed_name_resolves_renamed_tools(+ build: Callable[[list[str]], FastMCP],+):+ calls: list[str] = []+ server = build(calls)++ async with Client(server) as client:+ result = await client.call_tool(SAVE, {"name": "alice"})++ assert result.data == "saved alice"+ assert calls == ["alice"]+++class SaveDisabledApp(FastMCPApp):+ """An app provider whose `get_tool` override declines `save`."""++ async def get_tool(+ self, name: str, version: VersionSpec | None = None+ ) -> Tool | None:+ if name == "save":+ return None+ return await super().get_tool(name, version)+++class MaintenanceLock(Transform):+ """Refuses `save` while a `maintenance_marker` tool exists beneath it."""++ async def get_tool(+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None+ ) -> Tool | None:+ if name == "save" and await call_next("maintenance_marker") is not None:+ return None+ return await call_next(name, version=version)+++async def test_provider_get_tool_override_applies_to_hashed_name():+ calls: list[str] = []+ app = SaveDisabledApp("contacts")++ @app.tool()+ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ async with Client(server_with(app)) as client:+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(SAVE, {"name": "alice"})++ assert calls == []++[email protected]("under_maintenance", [True, False])+async def test_transform_sees_other_tools_during_hashed_lookup(+ under_maintenance: bool,+):+ calls: list[str] = []+ server = server_with(contacts_app(calls))+ if under_maintenance:++ @server.tool+ def maintenance_marker() -> str:+ return "down"++ server.add_transform(MaintenanceLock())++ async with Client(server) as client:+ if under_maintenance:+ with pytest.raises(ToolError, match="Unknown tool"):+ await client.call_tool(SAVE, {"name": "alice"})+ else:+ await client.call_tool(SAVE, {"name": "alice"})++ assert calls == ([] if under_maintenance else ["alice"])+++def versioned_contacts_app() -> FastMCPApp:+ app = FastMCPApp("contacts")+ for version in ("1.0", "2.0"):++ def save(name: str, _version: str = version) -> str:+ return f"v{_version} saved {name}"++ app.add_tool(+ Tool.from_function(+ save,+ version=version,+ meta={"ui": {"visibility": ["app", "model"]}},+ )+ )+ return app+++async def test_hashed_name_falls_back_past_a_disabled_highest_version():+ server = server_with(versioned_contacts_app())+ server.disable(version=VersionSpec(eq="2.0"))++ async with Client(server) as client:+ by_name = await client.call_tool("save", {"name": "alice"})+ by_hash = await client.call_tool(SAVE, {"name": "alice"})++ assert by_name.data == "v1.0 saved alice"+ assert by_hash.data == "v1.0 saved alice"+++async def test_hashed_name_respects_a_version_filter():+ server = server_with(versioned_contacts_app())+ server.add_transform(VersionFilter(version_lt="2"))++ async with Client(server) as client:+ by_name = await client.call_tool("save", {"name": "alice"})+ by_hash = await client.call_tool(SAVE, {"name": "alice"})++ assert by_name.data == "v1.0 saved alice"+ assert by_hash.data == "v1.0 saved alice"+++class SpawnLaterLookup(Transform):+ """Starts a task that looks up `save` by name once released."""++ def __init__(self, server: FastMCP) -> None:+ self.server = server+ self.release = asyncio.Event()+ self.probes: list[asyncio.Task[Tool | None]] = []++ async def get_tool(+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None+ ) -> Tool | None:+ if name == "save" and not self.probes:+ self.probes.append(asyncio.create_task(self._lookup_later()))+ return await call_next(name, version=version)++ async def _lookup_later(self) -> Tool | None:+ await self.release.wait()+ return await self.server.get_tool("save")+++async def test_task_started_during_hashed_lookup_resolves_names_normally():+ server = server_with(contacts_app([]))++ @server.tool(name="save")+ def plain_save(name: str) -> str:+ """Save without an app."""+ return f"plain {name}"++ spawner = SpawnLaterLookup(server)+ server.add_transform(spawner)++ async with Client(server) as client:+ await client.call_tool(SAVE, {"name": "alice"})+ spawner.release.set()+ (probe,) = spawner.probes+ later = await probe++ assert later is not None+ assert later.description == "Save without an app."+++class StripAuth(Transform):+ """Lists and resolves every tool as a copy that has no auth checks."""++ async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:+ return [t.model_copy(update={"auth": None}) for t in tools]++ async def get_tool(+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None+ ) -> Tool | None:+ tool = await call_next(name, version=version)+ if tool is None:+ return None+ return tool.model_copy(update={"auth": None})+++def admin_contacts_app(calls: list[str], tags: set[str]) -> FastMCPApp:+ app = FastMCPApp("contacts")++ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ app.add_tool(+ Tool.from_function(+ save,+ tags=tags,+ auth=restrict_tag("admin", scopes=["admin"]),+ )+ )+ return app+++def admin_tag_removed_by_server_transform(calls: list[str]) -> FastMCP:+ server = server_with(admin_contacts_app(calls, {"admin"}))+ server.add_transform(ToolTransform({"save": ToolTransformConfig(tags={"public"})}))+ return server+++def admin_tag_added_by_server_transform(calls: list[str]) -> FastMCP:+ server = server_with(admin_contacts_app(calls, {"public"}))+ server.add_transform(ToolTransform({"save": ToolTransformConfig(tags={"admin"})}))+ return server+++def admin_tag_removed_by_provider_transform(calls: list[str]) -> FastMCP:+ app = admin_contacts_app(calls, {"admin"})+ app.add_transform(ToolTransform({"save": ToolTransformConfig(tags={"public"})}))+ return server_with(app)+++def admin_tag_added_by_provider_transform(calls: list[str]) -> FastMCP:+ app = admin_contacts_app(calls, {"public"})+ app.add_transform(ToolTransform({"save": ToolTransformConfig(tags={"admin"})}))+ return server_with(app)+++def admin_tag_removed_in_mounted_server(calls: list[str]) -> FastMCP:+ child = server_with(admin_contacts_app(calls, {"admin"}))+ child.add_transform(ToolTransform({"save": ToolTransformConfig(tags={"public"})}))+ server = FastMCP("Platform")+ server.mount(child, namespace="child")+ return server+++def admin_tag_removed_and_renamed(calls: list[str]) -> FastMCP:+ server = server_with(admin_contacts_app(calls, {"admin"}))+ server.add_transform(+ ToolTransform({"save": ToolTransformConfig(name="store", tags={"public"})})+ )+ return server+++def scoped_tool_with_auth_removed_by_server_transform(calls: list[str]) -> FastMCP:+ app = FastMCPApp("contacts")++ def save(name: str) -> str:+ calls.append(name)+ return f"saved {name}"++ app.add_tool(Tool.from_function(save, auth=require_scopes("admin")))+ server = server_with(app)+ server.add_transform(StripAuth())+ return server+++def scoped_tool_with_auth_removed_in_mounted_server(calls: list[str]) -> FastMCP:+ child = scoped_tool_with_auth_removed_by_server_transform(calls)+ server = FastMCP("Platform")+ server.mount(child, namespace="child")+ return server+++ "build, listed_name, allowed",+ [+ (admin_tag_removed_by_server_transform, "save", False),+ (admin_tag_added_by_server_transform, "save", True),+ (admin_tag_removed_by_provider_transform, "save", True),+ (admin_tag_added_by_provider_transform, "save", False),+ (admin_tag_removed_in_mounted_server, "child_save", False),+ (admin_tag_removed_and_renamed, "store", False),+ (scoped_tool_with_auth_removed_by_server_transform, "save", False),+ (scoped_tool_with_auth_removed_in_mounted_server, "child_save", False),+ ],+)+async def test_hashed_lookup_checks_authorization_of_the_same_tool_as_the_listed_name(+ build: Callable[[list[str]], FastMCP], listed_name: str, allowed: bool+):+ async def calls_made_through(name: str) -> list[str]:+ calls: list[str] = []+ server = build(calls)+ async with Client(server) as client:+ try:+ await client.call_tool(name, {"name": "alice"})+ except ToolError as exc:+ assert "Unknown tool" in str(exc)+ return calls++ expected = ["alice"] if allowed else []+ assert await calls_made_through(listed_name) == expected+ assert await calls_made_through(SAVE) == expected++[email protected]("on_provider", [False, True])+ "meta",+ [+ {"team": "crm"},+ {},+ None,+ ],+)+async def test_hashed_name_resolves_tools_renamed_with_replaced_meta(+ meta: dict[str, str] | None, on_provider: bool+):+ calls: list[str] = []+ app = contacts_app(calls)+ server = server_with(app)+ transform = ToolTransform({"save": ToolTransformConfig(name="store", meta=meta)})+ if on_provider:+ app.add_transform(transform)+ else:+ server.add_transform(transform)++ async with Client(server) as client:+ by_name = await client.call_tool("store", {"name": "alice"})+ by_hash = await client.call_tool(SAVE, {"name": "alice"})++ assert by_name.data == "saved alice"+ assert by_hash.data == "saved alice"+ assert calls == ["alice", "alice"]diff --git a/tests/test_fastmcp_app.py b/tests/test_fastmcp_app.pyindex 9737454ff..1cb3eb32d 100644--- a/tests/test_fastmcp_app.py+++ b/tests/test_fastmcp_app.py@@ -491,9 +491,9 @@ class TestCallToolAppRouting:assert result.content[0].text == "saved bob" # type: ignore[union-attr] # ty:ignore[unresolved-attribute]async def test_hashed_name_survives_namespace_mount(self):- """The hashed-name path bypasses display-layer transforms entirely.- A FastMCPApp mounted under a Namespace transform still has its- backend tools reachable via the same hash."""+ """The hash identifies a tool independently of its name. A FastMCPApp+ mounted under a Namespace transform still has its backend tools+ reachable via the same hash."""from fastmcp.server.providers.addressing import hashed_backend_nameapp = FastMCPApp("crm")