π The fast, Pythonic way to build MCP servers and clients.
Stop FastMCP callable caches from retaining dropped tools (#6147)
ppy713f24791aa3
diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.pyindex e32686714..f10e9c018 100644--- a/fastmcp_slim/fastmcp/server/dependencies.py+++ b/fastmcp_slim/fastmcp/server/dependencies.py@@ -15,7 +15,6 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mappfrom contextlib import AsyncExitStack, asynccontextmanager, contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass-from functools import lru_cachefrom types import TracebackTypefrom typing import TYPE_CHECKING, Any, Protocol, cast, get_type_hints, runtime_checkable@@ -42,6 +41,7 @@ from uncalled_for.resolution import _Dependsfrom fastmcp.exceptions import FastMCPErrorfrom fastmcp.server.auth import AccessTokenfrom fastmcp.server.http import _current_http_request+from fastmcp.utilities._callable_cache import cache_on_callablefrom fastmcp.utilities.async_utils import (call_sync_fn_in_threadpool,is_coroutine_function,@@ -728,7 +728,7 @@ def get_access_token() -> AccessToken | None:# --- Schema generation helper ----@lru_cache(maxsize=5000)+@cache_on_callabledef without_injected_parameters(fn: Callable[..., Any], *, run_in_thread: bool = True) -> Callable[..., Any]:diff --git a/fastmcp_slim/fastmcp/server/sessions.py b/fastmcp_slim/fastmcp/server/sessions.pyindex 82ef061a2..17298b28d 100644--- a/fastmcp_slim/fastmcp/server/sessions.py+++ b/fastmcp_slim/fastmcp/server/sessions.py@@ -41,7 +41,6 @@ import inspectimport jsonimport timefrom collections.abc import Callable, Sequence-from functools import lru_cachefrom types import TracebackTypefrom typing import (TYPE_CHECKING,@@ -61,6 +60,7 @@ from uncalled_for import Provider as DependencyProviderfrom fastmcp.exceptions import FastMCPErrorfrom fastmcp.server.dependencies import get_access_token, get_server, get_sessionfrom fastmcp.server.providers.base import Provider+from fastmcp.utilities._callable_cache import cache_on_callablefrom fastmcp.utilities.logging import get_loggerif TYPE_CHECKING:@@ -339,7 +339,7 @@ class _SessionIdMarker:SessionId = Annotated[str, _SessionIdMarker()]-@lru_cache(maxsize=5000)+@cache_on_callabledef session_id_parameter_names(fn: Callable[..., object]) -> tuple[str, ...]:"""Names of a function's parameters annotated with `SessionId`.diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.pyindex 872d31310..0706dd409 100644--- a/fastmcp_slim/fastmcp/tools/function_tool.py+++ b/fastmcp_slim/fastmcp/tools/function_tool.py@@ -7,7 +7,6 @@ import inspectimport loggingfrom collections.abc import Callablefrom dataclasses import dataclass, field-from functools import lru_cachefrom types import MethodTypefrom typing import (Annotated,@@ -38,6 +37,7 @@ from fastmcp.tools.base import (ToolResult,)from fastmcp.tools.function_parsing import ParsedFunction, _is_object_schema+from fastmcp.utilities._callable_cache import cache_on_callablefrom fastmcp.utilities.async_utils import (call_sync_fn_in_threadpool,is_coroutine_function,@@ -80,7 +80,7 @@ def _materialize_sync_generator(result: Any) -> Any:return result-@lru_cache(maxsize=5000)+@cache_on_callabledef _wrap_body_errors(fn: Callable[..., Any], *, materialize_generators: bool = False) -> Callable[..., Any]:diff --git a/fastmcp_slim/fastmcp/utilities/_callable_cache.py b/fastmcp_slim/fastmcp/utilities/_callable_cache.pynew file mode 100644index 000000000..dfeb35dee--- /dev/null+++ b/fastmcp_slim/fastmcp/utilities/_callable_cache.py@@ -0,0 +1,82 @@+"""Memoize callable metadata without making the callable process-owned."""++import inspect+import weakref+from collections.abc import Callable+from dataclasses import dataclass, field+from functools import wraps+from threading import RLock+from typing import Any, ParamSpec, TypeVar++P = ParamSpec("P")+R = TypeVar("R")+_CACHE_ATTRIBUTE = "__fastmcp_callable_cache__"+++@dataclass+class _CallableCache:+ owner: weakref.ReferenceType[Any] | None+ values: dict[tuple[Any, ...], Any] = field(default_factory=dict)++ def __reduce__(self) -> tuple[type, tuple[None]]:+ # Tasks can pickle user functions. Metadata is process-local and may+ # contain weakrefs or adapters; a restored callable builds it afresh.+ return type(self), (None,)+++def cache_on_callable(build: Callable[P, R]) -> Callable[P, R]:+ """Cache on the first argument, or its instance for a bound method.++ Wrapper and TypeAdapter values can refer back to their callable, so a weak+ key alone cannot prevent retention. Owning the values on the callable makes+ the whole cycle collectable. Callables without a writable namespace or weak+ reference support are evaluated uncached instead of retained globally.+ """+ first_parameter = next(iter(inspect.signature(build).parameters))+ lock = RLock()++ @wraps(build)+ def cached(*args: P.args, **kwargs: P.kwargs) -> R:+ try:+ target = args[0]+ except IndexError:+ if first_parameter not in kwargs:+ return build(*args, **kwargs)+ target = kwargs[first_parameter]+ if inspect.ismethod(target):+ method = target.__func__+ owner = target.__self__+ else:+ method = None+ owner = target+ options = tuple((k, v) for k, v in kwargs.items() if k != first_parameter)+ key = (build, method, args[1:], options)+ try:+ namespace = vars(owner)+ owner_ref = weakref.ref(owner)+ except TypeError:+ return build(*args, **kwargs)++ with lock:+ cache = namespace.get(_CACHE_ATTRIBUTE)+ # Function wrappers often copy __dict__. Never reuse the source+ # function's metadata on a distinct wrapper with a different schema.+ if (+ not isinstance(cache, _CallableCache)+ or cache.owner is None+ or cache.owner() is not owner+ ):+ cache = _CallableCache(owner_ref)+ try:+ namespace[_CACHE_ATTRIBUTE] = cache+ except TypeError:+ return build(*args, **kwargs)+ if key in cache.values:+ return cache.values[key]++ value = build(*args, **kwargs)+ with lock:+ cache.values[key] = value+ return value++ return cacheddiff --git a/fastmcp_slim/fastmcp/utilities/types.py b/fastmcp_slim/fastmcp/utilities/types.pyindex 56d77e59c..ce2718a71 100644--- a/fastmcp_slim/fastmcp/utilities/types.py+++ b/fastmcp_slim/fastmcp/utilities/types.py@@ -5,7 +5,7 @@ import inspectimport mimetypesimport osfrom collections.abc import Callable-from functools import lru_cache+from functools import lru_cache, partialfrom pathlib import Pathfrom types import EllipsisType, UnionTypefrom typing import (@@ -17,6 +17,7 @@ from typing import (get_args,get_origin,get_type_hints,+ overload,)from urllib.parse import quote@@ -25,6 +26,8 @@ from mcp_types import Annotations, ContentBlock, ModelPreferences, SamplingMessafrom pydantic import AnyUrl, BaseModel, ConfigDict, Field, TypeAdapter, UrlConstraintsfrom typing_extensions import TypeVar+from fastmcp.utilities._callable_cache import cache_on_callable+T = TypeVar("T", default=Any)# TODO(sdkv2): the SDK's `mcp.types.AnyFunction` alias was removed with the@@ -52,14 +55,37 @@ def get_function_type_hints(fn: Callable[..., Any]) -> dict[str, Any]:return get_type_hints(fn, include_extras=True)-@lru_cache(maxsize=5000)-def get_cached_typeadapter(cls: T) -> TypeAdapter[T]:+@overload+def get_cached_typeadapter(cls: type[T]) -> TypeAdapter[T]: ...+++@overload+def get_cached_typeadapter(cls: Any) -> TypeAdapter[Any]: ...+++def get_cached_typeadapter(cls: Any) -> TypeAdapter[Any]:"""TypeAdapters are heavy objects, and in an application context we'd typicallycreate them once in a global scope and reuse them as often as possible.However, this isn't feasible for user-generated functions. Instead, we use acache to minimize the cost of creating them as much as possible."""+ if inspect.isfunction(cls) or inspect.ismethod(cls) or isinstance(cls, partial):+ return _get_callable_typeadapter(cls)+ return _get_type_typeadapter(cls)+++@cache_on_callable+def _get_callable_typeadapter(cls: T) -> TypeAdapter[T]:+ return _create_typeadapter(cls)+++@lru_cache(maxsize=5000)+def _get_type_typeadapter(cls: T) -> TypeAdapter[T]:+ return _create_typeadapter(cls)+++def _create_typeadapter(cls: T) -> TypeAdapter[T]:# For functions, process annotations to handle forward references and convert# Annotated[Type, "string"] to Annotated[Type, Field(description="string")]if inspect.isfunction(cls) or inspect.ismethod(cls):diff --git a/tests/server/test_callable_cache_lifetime.py b/tests/server/test_callable_cache_lifetime.pynew file mode 100644index 000000000..8592e6c49--- /dev/null+++ b/tests/server/test_callable_cache_lifetime.py@@ -0,0 +1,219 @@+"""Callable caches must not outlive the user functions they accelerate."""++import gc+import weakref+from collections.abc import Callable+from functools import partial, wraps++import cloudpickle+import pytest+from uncalled_for import annotations, introspection++from fastmcp import Client, FastMCP+from fastmcp.server.context import Context+from fastmcp.server.dependencies import without_injected_parameters+from fastmcp.server.sessions import session_id_parameter_names+from fastmcp.tools.function_tool import _wrap_body_errors+from fastmcp.utilities.types import get_cached_typeadapter+++class Payload:+ def __init__(self) -> None:+ self.items = list(range(100))+++def external_introspection_caches(monkeypatch: pytest.MonkeyPatch) -> None:+ # uncalled-for #21 independently retains callables in its introspection+ # (signature, parameter) and annotations (metadata, annotation) caches.+ # Isolate them so these regressions can verify FastMCP's ownership without+ # changing the dependency's process-wide cache objects in production.+ monkeypatch.setattr(introspection, "_signature_cache", {})+ monkeypatch.setattr(introspection, "_parameter_cache", {})+ monkeypatch.setattr(annotations, "_metadata_cache", {})+ monkeypatch.setattr(annotations, "_annotation_cache", {})+++def release_external_introspection() -> None:+ introspection._signature_cache.clear()+ introspection._parameter_cache.clear()+ annotations._metadata_cache.clear()+ annotations._annotation_cache.clear()++[email protected]("external_introspection_caches")+ "build",+ [+ get_cached_typeadapter,+ without_injected_parameters,+ _wrap_body_errors,+ session_id_parameter_names,+ ],+ ids=["type-adapter", "dependencies", "body-errors", "session-id"],+)+def test_callable_cache_does_not_retain_a_dropped_closure(+ build: Callable[..., object],+) -> None:+ def populate() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:+ payload = Payload()++ def tool(query: str) -> int:+ return len(payload.items)++ build(tool)+ return weakref.ref(tool), weakref.ref(payload)++ tool_ref, payload_ref = populate()+ release_external_introspection()+ gc.collect()++ assert tool_ref() is None+ assert payload_ref() is None++[email protected]("external_introspection_caches")+async def test_dropped_servers_leave_no_fastmcp_owned_tool_closures() -> None:+ async def build_and_call() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:+ server = FastMCP("temporary")+ payload = Payload()++ def search(query: str) -> int:+ return len(payload.items)++ server.tool(search)+ async with Client(server) as client:+ result = await client.call_tool("search", {"query": "q"})+ assert result.data == 100+ return weakref.ref(search), weakref.ref(payload)++ refs = [await build_and_call() for _ in range(3)]+ release_external_introspection()+ gc.collect()++ assert all(tool() is None and payload() is None for tool, payload in refs)++[email protected]("external_introspection_caches")+def test_live_callable_keeps_its_cached_adapter() -> None:+ def tool(value: int) -> int:+ return value + 1++ adapter = get_cached_typeadapter(tool)+ assert get_cached_typeadapter(tool) is adapter+ assert adapter.validate_python({"value": 2}) == 3+ gc.collect()+ assert get_cached_typeadapter(tool) is adapter+ assert get_cached_typeadapter(int) is get_cached_typeadapter(int)+++def test_wrapped_function_does_not_reuse_the_source_functions_cache() -> None:+ def source() -> int:+ return 1++ original = _wrap_body_errors(source)++ @wraps(source)+ def wrapped() -> int:+ return 2++ distinct = _wrap_body_errors(wrapped)+ assert distinct is not original+ assert original() == 1+ assert distinct() == 2+ assert _wrap_body_errors(wrapped) is distinct++[email protected]("external_introspection_caches")+def test_dependency_wrapper_caches_each_thread_option_separately() -> None:+ def tool(value: int, ctx: Context) -> int:+ return value++ threaded = without_injected_parameters(tool, run_in_thread=True)+ inline = without_injected_parameters(tool, run_in_thread=False)+ assert threaded is not inline+ assert without_injected_parameters(tool, run_in_thread=True) is threaded+ assert without_injected_parameters(fn=tool, run_in_thread=False) is inline++[email protected]("external_introspection_caches")+def test_bound_method_cache_is_owned_by_its_instance() -> None:+ class Receiver:+ def __init__(self, value: int) -> None:+ self.value = value++ def tool(self, offset: int) -> int:+ return self.value + offset++ live = Receiver(10)+ adapter = get_cached_typeadapter(live.tool)+ assert get_cached_typeadapter(live.tool) is adapter++ def populate() -> weakref.ReferenceType:+ dropped = Receiver(20)+ other = get_cached_typeadapter(dropped.tool)+ assert other is not adapter+ assert other.validate_python({"offset": 1}) == 21+ _wrap_body_errors(dropped.tool)+ without_injected_parameters(dropped.tool)+ session_id_parameter_names(dropped.tool)+ return weakref.ref(dropped)++ dropped_ref = populate()+ release_external_introspection()+ gc.collect()+ assert dropped_ref() is None+ assert get_cached_typeadapter(live.tool) is adapter+ assert adapter.validate_python({"offset": 1}) == 11++[email protected]("external_introspection_caches")+def test_method_without_instance_namespace_is_not_retained() -> None:+ class Receiver:+ __slots__ = ("__weakref__",)++ def tool(self, offset: int) -> int:+ return offset++ def populate() -> weakref.ReferenceType:+ receiver = Receiver()+ adapter = get_cached_typeadapter(receiver.tool)+ assert adapter.validate_python({"offset": 2}) == 2+ _wrap_body_errors(receiver.tool)+ without_injected_parameters(receiver.tool)+ session_id_parameter_names(receiver.tool)+ return weakref.ref(receiver)++ receiver_ref = populate()+ release_external_introspection()+ gc.collect()+ assert receiver_ref() is None+++def test_partial_adapter_is_reused_without_retaining_its_bound_payload() -> None:+ def tool(payload: Payload, offset: int) -> int:+ return len(payload.items) + offset++ def populate() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:+ payload = Payload()+ bound = partial(tool, payload)+ adapter = get_cached_typeadapter(bound)+ assert get_cached_typeadapter(bound) is adapter+ assert adapter.validate_python({"offset": 2}) == 102+ return weakref.ref(bound), weakref.ref(payload)++ bound_ref, payload_ref = populate()+ gc.collect()+ assert bound_ref() is None+ assert payload_ref() is None+++def test_callable_cache_is_not_serialized_with_a_task_function() -> None:+ def tool(value: int) -> int:+ return value + 1++ get_cached_typeadapter(tool)+ restored = cloudpickle.loads(cloudpickle.dumps(tool))+ assert restored(2) == 3+ assert get_cached_typeadapter(restored).validate_python({"value": 2}) == 3+ assert get_cached_typeadapter(restored) is not get_cached_typeadapter(tool)