Skip to content

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

Replace UUID global keys with (app_name, tool_name) registry (#3585)

Jeremiah Lowind27c26e0ffc3
diff --git a/src/fastmcp/server/app.py b/src/fastmcp/server/app.py
index 440545e52..97ff4fcc2 100644
--- a/src/fastmcp/server/app.py
+++ b/src/fastmcp/server/app.py
@@ -1,10 +1,11 @@
"""FastMCPApp β€” a Provider that represents a composable MCP application.
FastMCPApp binds entry-point tools (model calls these) together with backend
-tools (the UI calls these via CallTool). Backend tools get global keys β€”
-UUID-suffixed stable identifiers that survive namespace transforms when
-servers are composed β€” so ``CallTool(save_contact)`` keeps working even when
-the app is mounted under a namespace.
+tools (the UI calls these via CallTool). Backend tools are registered in a
+process-level registry keyed by ``(app_name, tool_name)`` so that
+``CallTool("save_contact")`` reaches the right tool regardless of namespace
+transforms β€” the server looks up the tool directly when the request carries
+``_meta.fastmcp.app``.
Usage::
@@ -27,14 +28,12 @@ Usage::
from __future__ import annotations
import inspect
-import uuid
from collections.abc import AsyncIterator, Callable, Sequence
from contextlib import asynccontextmanager, suppress
from typing import Any, Literal, TypeVar, overload
from mcp.types import AnyFunction, Icon, ToolAnnotations
-from fastmcp.decorators import get_fastmcp_meta
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.providers.base import Provider
from fastmcp.server.providers.local_provider import LocalProvider
@@ -46,98 +45,47 @@ logger = get_logger(__name__)
F = TypeVar("F", bound=Callable[..., Any])
# ---------------------------------------------------------------------------
-# Process-level registries
+# Process-level registry
# ---------------------------------------------------------------------------
-# Global key β†’ Tool object. FastMCP.call_tool checks this before normal
-# provider resolution so that CallTool("save_contact-a1b2c3d4") reaches the
-# right tool regardless of namespace transforms.
-_APP_TOOL_REGISTRY: dict[str, Tool] = {}
+# (app_name, tool_name) β†’ Tool object. Populated by @app.tool() at
+# decoration time. The server checks this registry (via get_app_tool)
+# when a call_tool request carries _meta.fastmcp.app, bypassing the
+# normal transform chain entirely.
+_APP_TOOLS: dict[tuple[str, str], Tool] = {}
-# id(original_fn) β†’ global key. Used by the CallTool callable resolver to
-# translate ``CallTool(save_contact)`` β†’ ``"save_contact-a1b2c3d4"``.
-_FN_TO_GLOBAL_KEY: dict[int, str] = {}
-# tool name β†’ global key. Used by the CallTool resolver to translate
-# ``CallTool("save_contact")`` β†’ ``"save_contact-a1b2c3d4"``.
-_NAME_TO_GLOBAL_KEY: dict[str, str] = {}
-
-
-def get_global_tool(name: str) -> Tool | None:
- """Look up a tool by its global key, or return None."""
- return _APP_TOOL_REGISTRY.get(name)
-
-
-# ---------------------------------------------------------------------------
-# Global key helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_global_key(name: str) -> str:
- """Generate a global key: ``{name}-{8_hex_chars}``."""
- return f"{name}-{uuid.uuid4().hex[:8]}"
-
-
-def _register_global_key(tool: Tool, fn: Any, global_key: str) -> None:
- """Register a tool in all process-level registries."""
- _APP_TOOL_REGISTRY[global_key] = tool
- _FN_TO_GLOBAL_KEY[id(fn)] = global_key
- _NAME_TO_GLOBAL_KEY[tool.name] = global_key
-
-
-def _stamp_global_key(tool: Tool, global_key: str) -> None:
- """Write the global key into the tool's ``meta["ui"]["globalKey"]``."""
- meta = dict(tool.meta) if tool.meta else {}
- ui = dict(meta.get("ui", {})) if isinstance(meta.get("ui"), dict) else {}
- ui["globalKey"] = global_key
- meta["ui"] = ui
- tool.meta = meta
+def get_app_tool(app_name: str, tool_name: str) -> Tool | None:
+ """Look up an app tool by (app_name, tool_name), or return None."""
+ return _APP_TOOLS.get((app_name, tool_name))
# ---------------------------------------------------------------------------
-# CallTool callable resolver
+# CallTool resolver
# ---------------------------------------------------------------------------
def _resolve_tool_ref(fn: Any) -> Any:
"""Resolve a callable or string to a ``ResolvedTool`` for CallTool serialization.
- Always returns a ``ResolvedTool`` with the resolved name and any
- metadata the renderer needs (e.g. ``unwrap_result``).
-
- Resolution order for callables:
- 1. Global key registry (FastMCPApp tools) β€” includes metadata
- 2. ``__fastmcp__`` metadata (decorated but not on a FastMCPApp)
- 3. ``fn.__name__`` (bare function β€” works for standalone servers)
+ For strings, passes them through as-is β€” the server resolves them at
+ call time using ``_meta.fastmcp.app``.
- Resolution for strings:
- 1. Name registry (FastMCPApp tools registered by name)
- 2. Pass through as-is (plain tool name)
+ For callables, extracts the tool name from ``__fastmcp__`` metadata
+ or ``__name__``.
"""
from prefab_ui.app import ResolvedTool
if isinstance(fn, str):
- global_key = _NAME_TO_GLOBAL_KEY.get(fn)
- if global_key is not None:
- tool = _APP_TOOL_REGISTRY.get(global_key)
- unwrap = bool(
- tool is not None
- and tool.output_schema
- and tool.output_schema.get("x-fastmcp-wrap-result")
- )
- return ResolvedTool(name=global_key, unwrap_result=unwrap)
return ResolvedTool(name=fn)
- global_key = _FN_TO_GLOBAL_KEY.get(id(fn))
- if global_key is not None:
- tool = _APP_TOOL_REGISTRY.get(global_key)
- unwrap = bool(
- tool is not None
- and tool.output_schema
- and tool.output_schema.get("x-fastmcp-wrap-result")
- )
- return ResolvedTool(name=global_key, unwrap_result=unwrap)
+ fmeta: Any = None
+ try:
+ from fastmcp.decorators import get_fastmcp_meta
+
+ fmeta = get_fastmcp_meta(fn)
+ except Exception:
+ pass
- fmeta = get_fastmcp_meta(fn)
if fmeta is not None:
name: str | None = getattr(fmeta, "name", None)
if name is not None:
@@ -189,9 +137,10 @@ class FastMCPApp(Provider):
"""A Provider that represents an MCP application.
Binds together entry-point tools (``@app.ui``), backend tools
- (``@app.tool``), the Prefab renderer resource, and global-key
- infrastructure so that composed/namespaced servers can still reach
- backend tools by stable identifiers.
+ (``@app.tool``), and the Prefab renderer resource. Backend tools
+ are registered in a process-level registry keyed by
+ ``(app_name, tool_name)`` so the server can route app-originated
+ calls directly, bypassing transforms.
"""
def __init__(self, name: str) -> None:
@@ -242,9 +191,8 @@ class FastMCPApp(Provider):
) -> Any:
"""Register a backend tool that the UI calls via CallTool.
- Backend tools get a global key for composition safety and default
- to ``visibility=["app"]``. Pass ``model=True`` to also expose the
- tool to the model (``visibility=["app", "model"]``).
+ Backend tools default to ``visibility=["app"]``. Pass ``model=True``
+ to also expose the tool to the model (``visibility=["app", "model"]``).
Supports multiple calling patterns::
@@ -268,10 +216,8 @@ class FastMCPApp(Provider):
from fastmcp.server.apps import AppConfig, app_config_to_meta_dict
- global_key = _make_global_key(resolved_name)
app_config = AppConfig(visibility=visibility)
meta: dict[str, Any] = {"ui": app_config_to_meta_dict(app_config)}
- meta["ui"]["globalKey"] = global_key
tool_obj = Tool.from_function(
fn,
@@ -282,7 +228,7 @@ class FastMCPApp(Provider):
auth=auth,
)
self._local._add_component(tool_obj)
- _register_global_key(tool_obj, fn, global_key)
+ _APP_TOOLS[(self.name, resolved_name)] = tool_obj
return fn
return _dispatch_decorator(name_or_fn, name, _register, "tool")
@@ -337,8 +283,9 @@ class FastMCPApp(Provider):
"""Register a UI entry-point tool that the model calls.
Entry-point tools default to ``visibility=["model"]`` and auto-wire
- the Prefab renderer resource and CSP. They do NOT get a global key β€”
- the model resolves them through the normal transform chain.
+ the Prefab renderer resource and CSP. They do NOT get registered in
+ the app tool registry β€” the model resolves them through the normal
+ transform chain.
Supports multiple calling patterns::
@@ -379,7 +326,10 @@ class FastMCPApp(Provider):
visibility=["model"],
)
- meta: dict[str, Any] = {"ui": app_config_to_meta_dict(app_config)}
+ meta: dict[str, Any] = {
+ "ui": app_config_to_meta_dict(app_config),
+ "fastmcp": {"app": self.name},
+ }
tool_obj = Tool.from_function(
fn,
@@ -410,37 +360,16 @@ class FastMCPApp(Provider):
def add_tool(
self,
tool: Tool | Callable[..., Any],
- *,
- fn: Any | None = None,
) -> Tool:
"""Add a tool to this app programmatically.
- If the tool has ``meta["ui"]["globalKey"]``, it is assumed to already
- be configured (but still registered for lookup). Otherwise it is
- treated as a backend tool and gets a global key assigned automatically.
-
- Pass ``fn`` to register the original callable in the resolver so that
- ``CallTool(fn)`` can resolve to the global key.
+ The tool is registered as a backend tool in the app's registry.
"""
if not isinstance(tool, Tool):
- fn = fn or tool
tool = Tool._ensure_tool(tool)
- meta = tool.meta or {}
- ui = meta.get("ui", {})
- if isinstance(ui, dict) and "globalKey" in ui:
- global_key = ui["globalKey"]
- else:
- global_key = _make_global_key(tool.name)
- _stamp_global_key(tool, global_key)
-
self._local._add_component(tool)
-
- _APP_TOOL_REGISTRY[global_key] = tool
- _NAME_TO_GLOBAL_KEY[tool.name] = global_key
- if fn is not None:
- _FN_TO_GLOBAL_KEY[id(fn)] = global_key
-
+ _APP_TOOLS[(self.name, tool.name)] = tool
return tool
# ------------------------------------------------------------------
diff --git a/src/fastmcp/server/mixins/mcp_operations.py b/src/fastmcp/server/mixins/mcp_operations.py
index 77cb4c171..df001376a 100644
--- a/src/fastmcp/server/mixins/mcp_operations.py
+++ b/src/fastmcp/server/mixins/mcp_operations.py
@@ -217,12 +217,15 @@ class MCPOperationsMixin:
# fn_key is set by call_tool() after finding the tool.
version_str: str | None = None
task_meta: TaskMeta | None = None
+ app_name: str | None = None
try:
ctx = server._mcp_server.request_context
- # Extract version from request-level _meta.fastmcp.version
+ # Extract version and app name from _meta.fastmcp
if ctx.meta:
meta_dict = ctx.meta.model_dump(exclude_none=True)
- version_str = meta_dict.get("fastmcp", {}).get("version")
+ fastmcp_meta = meta_dict.get("fastmcp", {})
+ version_str = fastmcp_meta.get("version")
+ app_name = fastmcp_meta.get("app")
# Extract SEP-1686 task metadata
if ctx.experimental.is_task:
mcp_task_meta = ctx.experimental.task_metadata
@@ -233,7 +236,7 @@ class MCPOperationsMixin:
version = VersionSpec(eq=version_str) if version_str else None
result = await server.call_tool(
- key, arguments, version=version, task_meta=task_meta
+ key, arguments, version=version, task_meta=task_meta, app_name=app_name
)
if isinstance(result, mcp.types.CreateTaskResult):
diff --git a/src/fastmcp/server/providers/base.py b/src/fastmcp/server/providers/base.py
index b538cb961..49d278f6d 100644
--- a/src/fastmcp/server/providers/base.py
+++ b/src/fastmcp/server/providers/base.py
@@ -158,6 +158,11 @@ class Provider:
(FastMCP) performs enabled filtering after all transforms complete,
allowing session-level transforms to override provider-level disables.
+ If the transform chain returns None, a fallback checks for
+ app-visible tools by their original (untransformed) name. This
+ lets ``CallTool("save_contact")`` reach backend tools even when
+ namespace or other transforms have been applied to the provider.
+
Args:
name: The transformed tool name to look up.
version: Optional version filter. If None, returns highest version.
diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py
index a8444c821..8c997c719 100644
--- a/src/fastmcp/server/server.py
+++ b/src/fastmcp/server/server.py
@@ -1017,6 +1017,7 @@ class FastMCP(
version: VersionSpec | None = None,
run_middleware: bool = True,
task_meta: None = None,
+ app_name: str | None = None,
) -> ToolResult: ...
@overload
@@ -1028,6 +1029,7 @@ class FastMCP(
version: VersionSpec | None = None,
run_middleware: bool = True,
task_meta: TaskMeta,
+ app_name: str | None = None,
) -> mcp.types.CreateTaskResult: ...
async def call_tool(
@@ -1038,6 +1040,7 @@ class FastMCP(
version: VersionSpec | None = None,
run_middleware: bool = True,
task_meta: TaskMeta | None = None,
+ app_name: str | None = None,
) -> ToolResult | mcp.types.CreateTaskResult:
"""Call a tool by name.
@@ -1052,6 +1055,9 @@ class FastMCP(
task_meta: If provided, execute as a background task and return
CreateTaskResult. If None (default), execute synchronously and
return ToolResult.
+ app_name: If set (from ``_meta.fastmcp.app``), the call originated
+ from an app UI and should be routed directly to the named app's
+ tool registry, bypassing transforms.
Returns:
ToolResult when task_meta is None.
@@ -1085,6 +1091,7 @@ class FastMCP(
version=version,
run_middleware=False,
task_meta=task_meta,
+ app_name=app_name,
),
)
@@ -1093,18 +1100,16 @@ class FastMCP(
with server_span(
f"tools/call {name}", "tools/call", self.name, "tool", name
) as span:
- # Try normal provider resolution first (applies transforms,
- # visibility, auth). Fall back to the global key registry
- # so that FastMCPApp CallTool references survive namespace
- # transforms. Global keys contain a UUID suffix, so they
- # won't collide with human-written tool names.
- tool = await self.get_tool(name, version=version)
- if tool is None:
- from fastmcp.server.app import get_global_tool
-
- tool = get_global_tool(name)
+ # If the call came from an app UI (_meta.fastmcp.app is set),
+ # look up the tool directly in the app registry, bypassing
+ # transforms. Otherwise use normal provider resolution.
+ tool: Tool | None = None
+ if app_name is not None:
+ from fastmcp.server.app import get_app_tool
+
+ tool = get_app_tool(app_name, name)
if tool is not None:
- # Auth still applies to global-key tools
+ # Auth still applies to app tools
skip_auth, token = _get_auth_context()
if not skip_auth and tool.auth is not None:
try:
@@ -1113,6 +1118,8 @@ class FastMCP(
raise NotFoundError(f"Unknown tool: {name!r}")
except AuthorizationError:
raise NotFoundError(f"Unknown tool: {name!r}") from None
+ if tool is None:
+ tool = await self.get_tool(name, version=version)
if tool is None:
raise NotFoundError(f"Unknown tool: {name!r}")
span.set_attributes(tool.get_span_attributes())
diff --git a/src/fastmcp/tools/base.py b/src/fastmcp/tools/base.py
index 36c3e49a9..89830bd2d 100644
--- a/src/fastmcp/tools/base.py
+++ b/src/fastmcp/tools/base.py
@@ -268,9 +268,15 @@ class Tool(FastMCPComponent):
if _HAS_PREFAB:
if isinstance(raw_value, _PrefabApp):
- return _prefab_to_tool_result(raw_value)
+ return _prefab_to_tool_result(
+ raw_value,
+ fastmcp_app_name=_get_fastmcp_app_name(self),
+ )
if isinstance(raw_value, _PrefabComponent):
- return _prefab_to_tool_result(_PrefabApp(view=raw_value))
+ return _prefab_to_tool_result(
+ _PrefabApp(view=raw_value),
+ fastmcp_app_name=_get_fastmcp_app_name(self),
+ )
content = _convert_to_content(raw_value, serializer=self.serializer)
@@ -492,16 +498,38 @@ def _get_tool_resolver() -> Callable[..., str] | None:
return None
-def _prefab_to_json(app: Any) -> dict[str, Any]:
- """Call PrefabApp.to_json() with the FastMCPApp callable resolver."""
- return app.to_json(tool_resolver=_get_tool_resolver())
+def _prefab_to_json(app: Any, fastmcp_app_name: str | None = None) -> dict[str, Any]:
+ """Call PrefabApp.to_json() with the FastMCPApp callable resolver.
+
+ If ``fastmcp_app_name`` is set, injects ``_meta.fastmcp.app`` into the
+ serialized output so the renderer can tag subsequent tool calls with the
+ app identity for direct routing.
+ """
+ data = app.to_json(tool_resolver=_get_tool_resolver())
+ if fastmcp_app_name is not None:
+ meta = data.setdefault("_meta", {})
+ meta.setdefault("fastmcp", {})["app"] = fastmcp_app_name
+ return data
+
+
+def _get_fastmcp_app_name(tool: Tool) -> str | None:
+ """Read the FastMCPApp name from a tool's metadata, if present."""
+ meta = tool.meta
+ if not meta:
+ return None
+ fastmcp_meta = meta.get("fastmcp")
+ if isinstance(fastmcp_meta, dict):
+ app = fastmcp_meta.get("app")
+ if isinstance(app, str):
+ return app
+ return None
-def _prefab_to_tool_result(app: Any) -> ToolResult:
+def _prefab_to_tool_result(app: Any, fastmcp_app_name: str | None = None) -> ToolResult:
"""Convert a PrefabApp to a FastMCP ToolResult."""
return ToolResult(
content=[TextContent(type="text", text=_PREFAB_TEXT_FALLBACK)],
- structured_content=_prefab_to_json(app),
+ structured_content=_prefab_to_json(app, fastmcp_app_name=fastmcp_app_name),
)
diff --git a/tests/test_fastmcp_app.py b/tests/test_fastmcp_app.py
index 4b4cd865c..1e0b65cb5 100644
--- a/tests/test_fastmcp_app.py
+++ b/tests/test_fastmcp_app.py
@@ -1,9 +1,9 @@
"""Tests for FastMCPApp β€” the composable application provider.
Covers:
-- @app.tool() decorator (global keys, visibility, calling patterns)
+- @app.tool() decorator (visibility, calling patterns)
- @app.ui() decorator (model visibility, CSP auto-wiring)
-- Global key registry and call_tool routing
+- App tool registry and call_tool routing
- Callable resolver (_resolve_tool_ref)
- Composition with namespaced servers
- Provider interface delegation
@@ -11,7 +11,6 @@ Covers:
from __future__ import annotations
-import re
from unittest.mock import AsyncMock
import pytest
@@ -19,12 +18,10 @@ from prefab_ui.app import ResolvedTool
from fastmcp import Client, FastMCP
from fastmcp.server.app import (
- _APP_TOOL_REGISTRY,
- _FN_TO_GLOBAL_KEY,
- _NAME_TO_GLOBAL_KEY,
+ _APP_TOOLS,
FastMCPApp,
- _make_global_key,
_resolve_tool_ref,
+ get_app_tool,
)
from fastmcp.tools.base import Tool
@@ -32,30 +29,10 @@ from fastmcp.tools.base import Tool
# Fixtures / helpers
# ---------------------------------------------------------------------------
-GLOBAL_KEY_PATTERN = re.compile(r"^.+-[0-9a-f]{8}$")
-
def _clear_registries() -> None:
"""Clear process-level registries between tests."""
- _APP_TOOL_REGISTRY.clear()
- _FN_TO_GLOBAL_KEY.clear()
- _NAME_TO_GLOBAL_KEY.clear()
-
-
-# ---------------------------------------------------------------------------
-# Global key generation
-# ---------------------------------------------------------------------------
-
-
-class TestGlobalKeyGeneration:
- def test_make_global_key_format(self):
- key = _make_global_key("save_contact")
- assert GLOBAL_KEY_PATTERN.match(key)
- assert key.startswith("save_contact-")
-
- def test_make_global_key_uniqueness(self):
- keys = {_make_global_key("my_tool") for _ in range(100)}
- assert len(keys) == 100
+ _APP_TOOLS.clear()
# ---------------------------------------------------------------------------
@@ -74,7 +51,6 @@ class TestAppTool:
def save(name: str) -> str:
return name
- # Function is returned unchanged
assert save("alice") == "alice"
def test_tool_empty_parens(self):
@@ -135,33 +111,24 @@ class TestAppTool:
assert len(tools) == 1
assert tools[0].name == "custom_save"
- def test_tool_gets_global_key(self):
+ def test_tool_registered_in_app_tools(self):
app = FastMCPApp("test")
@app.tool()
def save(name: str) -> str:
return name
- # Check the function is registered in the global key registry
- assert id(save) in _FN_TO_GLOBAL_KEY
- global_key = _FN_TO_GLOBAL_KEY[id(save)]
- assert GLOBAL_KEY_PATTERN.match(global_key)
- assert global_key.startswith("save-")
- assert global_key in _APP_TOOL_REGISTRY
+ assert ("test", "save") in _APP_TOOLS
+ assert _APP_TOOLS[("test", "save")].name == "save"
- async def test_tool_global_key_in_meta(self):
- app = FastMCPApp("test")
+ def test_tool_custom_name_registered_correctly(self):
+ app = FastMCPApp("myapp")
- @app.tool()
+ @app.tool("custom_save")
def save(name: str) -> str:
return name
- tools = await app._list_tools()
- tool = tools[0]
- assert tool.meta is not None
- assert "ui" in tool.meta
- assert "globalKey" in tool.meta["ui"]
- assert GLOBAL_KEY_PATTERN.match(tool.meta["ui"]["globalKey"])
+ assert ("myapp", "custom_save") in _APP_TOOLS
async def test_tool_default_visibility_app_only(self):
app = FastMCPApp("test")
@@ -187,6 +154,19 @@ class TestAppTool:
assert meta is not None
assert meta["ui"]["visibility"] == ["app", "model"]
+ async def test_tool_no_global_key_in_meta(self):
+ """Tools should NOT have globalKey in meta (removed in refactor)."""
+ app = FastMCPApp("test")
+
+ @app.tool()
+ def save(name: str) -> str:
+ return name
+
+ tools = await app._list_tools()
+ meta = tools[0].meta
+ assert meta is not None
+ assert "globalKey" not in meta.get("ui", {})
+
def test_tool_with_description(self):
app = FastMCPApp("test")
@@ -269,15 +249,15 @@ class TestAppUI:
assert meta is not None
assert meta["ui"]["visibility"] == ["model"]
- def test_ui_no_global_key(self):
- """UI entry points should NOT get global keys."""
+ def test_ui_not_in_app_tools(self):
+ """UI entry points should NOT be in the app tool registry."""
app = FastMCPApp("test")
@app.ui()
def dashboard() -> str:
return "dashboard"
- assert id(dashboard) not in _FN_TO_GLOBAL_KEY
+ assert ("test", "dashboard") not in _APP_TOOLS
async def test_ui_has_resource_uri(self):
app = FastMCPApp("test")
@@ -335,38 +315,21 @@ class TestResolveToolRef:
def setup_method(self) -> None:
_clear_registries()
- def test_resolve_global_key(self):
- app = FastMCPApp("test")
-
- @app.tool()
- def save(name: str) -> str:
- return name
-
- result = _resolve_tool_ref(save)
- # str return β†’ wrapped tool β†’ ResolvedTool with unwrap_result
+ def test_resolve_string_passes_through(self):
+ """Strings pass through as-is β€” server resolves at call time."""
+ result = _resolve_tool_ref("save_contact")
assert isinstance(result, ResolvedTool)
- assert GLOBAL_KEY_PATTERN.match(result.name)
- assert result.name.startswith("save-")
- assert result.unwrap_result is True
-
- def test_resolve_global_key_object_return(self):
- """Tools returning dicts don't need unwrapping."""
+ assert result.name == "save_contact"
- app = FastMCPApp("test")
-
- @app.tool()
- def save(name: str) -> dict:
- return {"name": name}
+ def test_resolve_callable_uses_name(self):
+ def my_tool():
+ pass
- result = _resolve_tool_ref(save)
+ result = _resolve_tool_ref(my_tool)
assert isinstance(result, ResolvedTool)
- assert GLOBAL_KEY_PATTERN.match(result.name)
- assert result.name.startswith("save-")
- assert result.unwrap_result is False
+ assert result.name == "my_tool"
def test_resolve_fastmcp_metadata(self):
- """Functions with __fastmcp__ metadata but no global key."""
-
from fastmcp.tools.function_tool import ToolMeta
def my_tool():
@@ -378,50 +341,66 @@ class TestResolveToolRef:
assert isinstance(result, ResolvedTool)
assert result.name == "custom_name"
- def test_resolve_bare_function(self):
- def my_tool():
- pass
+ def test_resolve_unresolvable_raises(self):
+ with pytest.raises(ValueError):
+ _resolve_tool_ref(42)
- result = _resolve_tool_ref(my_tool)
- assert isinstance(result, ResolvedTool)
- assert result.name == "my_tool"
- def test_resolve_string_name(self):
- """CallTool("save") resolves to the global key."""
- app = FastMCPApp("test")
+# ---------------------------------------------------------------------------
+# get_app_tool registry
+# ---------------------------------------------------------------------------
+
+
+class TestGetAppTool:
+ def setup_method(self) -> None:
+ _clear_registries()
+
+ def test_lookup_by_app_and_tool_name(self):
+ app = FastMCPApp("contacts")
@app.tool()
def save(name: str) -> str:
return name
- result = _resolve_tool_ref("save")
- assert isinstance(result, ResolvedTool)
- assert GLOBAL_KEY_PATTERN.match(result.name)
- assert result.name.startswith("save-")
- assert result.unwrap_result is True
+ tool = get_app_tool("contacts", "save")
+ assert tool is not None
+ assert tool.name == "save"
- def test_resolve_string_name_object_return(self):
- """String resolution also sets unwrap_result correctly."""
- app = FastMCPApp("test")
+ def test_lookup_wrong_app_returns_none(self):
+ app = FastMCPApp("contacts")
@app.tool()
- def save(name: str) -> dict:
- return {"name": name}
+ def save(name: str) -> str:
+ return name
- result = _resolve_tool_ref("save")
- assert isinstance(result, ResolvedTool)
- assert result.name.startswith("save-")
- assert result.unwrap_result is False
+ assert get_app_tool("billing", "save") is None
- def test_resolve_string_unknown_passes_through(self):
- """Unknown string names pass through as-is."""
- result = _resolve_tool_ref("unknown_tool")
- assert isinstance(result, ResolvedTool)
- assert result.name == "unknown_tool"
+ def test_lookup_wrong_tool_returns_none(self):
+ app = FastMCPApp("contacts")
- def test_resolve_unresolvable_raises(self):
- with pytest.raises(ValueError):
- _resolve_tool_ref(42)
+ @app.tool()
+ def save(name: str) -> str:
+ return name
+
+ assert get_app_tool("contacts", "missing") is None
+
+ def test_two_apps_same_tool_name_no_collision(self):
+ app1 = FastMCPApp("contacts")
+ app2 = FastMCPApp("billing")
+
+ @app1.tool()
+ def save(name: str) -> str:
+ return f"contact: {name}"
+
+ @app2.tool("save")
+ def save_billing(amount: int) -> str:
+ return f"invoice: {amount}"
+
+ t1 = get_app_tool("contacts", "save")
+ t2 = get_app_tool("billing", "save")
+ assert t1 is not None
+ assert t2 is not None
+ assert t1 is not t2
# ---------------------------------------------------------------------------
@@ -458,17 +437,17 @@ class TestProviderInterface:
# ---------------------------------------------------------------------------
-# call_tool with global key routing
+# call_tool with app_name routing
# ---------------------------------------------------------------------------
-class TestCallToolGlobalKeyRouting:
+class TestCallToolAppRouting:
def setup_method(self) -> None:
_clear_registries()
- async def test_call_tool_by_global_key(self):
- """Server.call_tool can find a FastMCPApp tool by its global key."""
- app = FastMCPApp("test")
+ async def test_call_tool_with_app_name(self):
+ """Server.call_tool routes directly when app_name is provided."""
+ app = FastMCPApp("contacts")
@app.tool()
def save(name: str) -> str:
@@ -477,12 +456,10 @@ class TestCallToolGlobalKeyRouting:
server = FastMCP("Platform")
server.add_provider(app)
- global_key = _FN_TO_GLOBAL_KEY[id(save)]
-
- result = await server.call_tool(global_key, {"name": "alice"})
+ result = await server.call_tool("save", {"name": "alice"}, app_name="contacts")
assert result.content[0].text == "saved alice" # type: ignore[union-attr]
- async def test_call_tool_by_name(self):
+ async def test_call_tool_by_name_without_app_name(self):
"""Regular name-based resolution still works."""
app = FastMCPApp("test")
@@ -496,8 +473,8 @@ class TestCallToolGlobalKeyRouting:
result = await server.call_tool("save", {"name": "bob"})
assert result.content[0].text == "saved bob" # type: ignore[union-attr]
- async def test_global_key_survives_namespace(self):
- """Global key works even when the app is mounted under a namespace."""
+ async def test_app_name_survives_namespace(self):
+ """app_name routing works even when the app is namespaced."""
app = FastMCPApp("crm")
@app.tool()
@@ -507,10 +484,10 @@ class TestCallToolGlobalKeyRouting:
server = FastMCP("Platform")
server.add_provider(app, namespace="crm")
- global_key = _FN_TO_GLOBAL_KEY[id(save_contact)]
-
- # Global key should still work
- result = await server.call_tool(global_key, {"name": "alice"})
+ # app_name routes directly, bypassing namespace
+ result = await server.call_tool(
+ "save_contact", {"name": "alice"}, app_name="crm"
+ )
assert result.content[0].text == "saved alice" # type: ignore[union-attr]
async def test_namespaced_name_also_works(self):
@@ -527,8 +504,8 @@ class TestCallToolGlobalKeyRouting:
result = await server.call_tool("crm_save_contact", {"name": "bob"})
assert result.content[0].text == "saved bob" # type: ignore[union-attr]
- async def test_global_key_auth_blocks_unauthorized(self):
- """Auth checks run even when resolving via global key."""
+ async def test_app_name_auth_blocks_unauthorized(self):
+ """Auth checks run even when routing via app_name."""
from fastmcp.exceptions import NotFoundError
from fastmcp.server.context import _current_transport
@@ -542,16 +519,36 @@ class TestCallToolGlobalKeyRouting:
server = FastMCP("Platform")
server.add_provider(app)
- global_key = _FN_TO_GLOBAL_KEY[id(secret)]
-
- # Simulate non-stdio transport so auth is not skipped
token = _current_transport.set("streamable-http")
try:
with pytest.raises(NotFoundError):
- await server.call_tool(global_key, {})
+ await server.call_tool("secret", {}, app_name="test")
finally:
_current_transport.reset(token)
+ async def test_two_apps_same_tool_name_routed_correctly(self):
+ """Two apps with same tool name are disambiguated by app_name."""
+ contacts = FastMCPApp("contacts")
+ billing = FastMCPApp("billing")
+
+ @contacts.tool()
+ def save(name: str) -> str:
+ return f"contact: {name}"
+
+ @billing.tool("save")
+ def save_billing(amount: str) -> str:
+ return f"invoice: {amount}"
+
+ server = FastMCP("Platform")
+ server.add_provider(contacts)
+ server.add_provider(billing)
+
+ r1 = await server.call_tool("save", {"name": "alice"}, app_name="contacts")
+ r2 = await server.call_tool("save", {"amount": "100"}, app_name="billing")
+
+ assert r1.content[0].text == "contact: alice" # type: ignore[union-attr]
+ assert r2.content[0].text == "invoice: 100" # type: ignore[union-attr]
+
# ---------------------------------------------------------------------------
# End-to-end via Client
@@ -563,7 +560,6 @@ class TestEndToEnd:
_clear_registries()
async def test_ui_tool_visible_to_client(self):
- """UI entry-point tools show up in list_tools via Client."""
app = FastMCPApp("test")
@app.ui()
@@ -579,7 +575,6 @@ class TestEndToEnd:
assert "dashboard" in names
async def test_app_tool_model_true_visible(self):
- """App tools with model=True are visible via Client."""
app = FastMCPApp("test")
@app.tool(model=True)
@@ -594,23 +589,6 @@ class TestEndToEnd:
names = [t.name for t in tools]
assert "query" in names
- async def test_call_tool_via_global_key_through_client(self):
- """Client can call a tool using its global key."""
- app = FastMCPApp("test")
-
- @app.tool()
- def save(name: str) -> str:
- return f"saved {name}"
-
- server = FastMCP("Platform")
- server.add_provider(app)
-
- global_key = _FN_TO_GLOBAL_KEY[id(save)]
-
- async with Client(server) as client:
- result = await client.call_tool(global_key, {"name": "test"})
- assert "saved test" in result.content[0].text
-
# ---------------------------------------------------------------------------
# .run() convenience
@@ -644,15 +622,14 @@ class TestAddTool:
tools = await app._list_tools()
assert len(tools) == 1
- async def test_add_tool_gets_global_key(self):
+ async def test_add_tool_registered_in_app_tools(self):
app = FastMCPApp("test")
def save(name: str) -> str:
return name
- tool = app.add_tool(save)
- assert tool.meta is not None
- assert "globalKey" in tool.meta.get("ui", {})
+ app.add_tool(save)
+ assert ("test", "save") in _APP_TOOLS
async def test_add_tool_object(self):
app = FastMCPApp("test")
@@ -689,12 +666,10 @@ class TestComposition:
server.add_provider(crm, namespace="crm")
server.add_provider(billing, namespace="billing")
- # Both tools reachable by global key
- crm_key = _FN_TO_GLOBAL_KEY[id(save_contact)]
- billing_key = _FN_TO_GLOBAL_KEY[id(create_invoice)]
-
- r1 = await server.call_tool(crm_key, {"name": "alice"})
- r2 = await server.call_tool(billing_key, {"amount": 100})
+ r1 = await server.call_tool("save_contact", {"name": "alice"}, app_name="CRM")
+ r2 = await server.call_tool(
+ "create_invoice", {"amount": 100}, app_name="Billing"
+ )
assert r1.content[0].text == "alice" # type: ignore[union-attr]
assert r2.content[0].text == "100" # type: ignore[union-attr]