π The fast, Pythonic way to build MCP servers and clients.
Roll back the tool stamp when a tool registration is rejected (#5798)
Winorend6566c515022
diff --git a/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py b/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.pyindex 9779801b5..796a705c8 100644--- a/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py+++ b/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py@@ -41,6 +41,10 @@ DuplicateBehavior = Literal["error", "warn", "replace", "ignore"]PREFAB_RENDERER_URI = "ui://prefab/renderer.html"+# Sentinel distinguishing "no metadata was stamped" from "stamped as None", so a+# rejected registration can restore the function to exactly its prior state.+_MISSING = object()+def _is_prefab_type(tp: Any) -> bool:"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""@@ -319,8 +323,22 @@ class ToolDecoratorMixin:run_in_thread=run_in_thread,)target = fn.__func__ if hasattr(fn, "__func__") else fn+ previous = getattr(target, "__fastmcp__", _MISSING)target.__fastmcp__ = metadata # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]- self.add_tool(fn)+ try:+ self.add_tool(fn)+ except Exception:+ # Registration is what validates the function (a sync body with+ # task execution enabled raises there). The stamp above is only+ # meaningful for a tool that was actually registered, so a+ # rejected call must not leave metadata behind: the caller's+ # function is then free to register on another server, whose+ # own task settings apply instead of this one's.+ if previous is _MISSING:+ del target.__fastmcp__ # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+ else:+ target.__fastmcp__ = previous # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+ raisereturn fnif inspect.isroutine(name_or_fn):diff --git a/tests/server/providers/local_provider_tools/test_decorator.py b/tests/server/providers/local_provider_tools/test_decorator.pyindex 3bf490d4f..5a5f1bd17 100644--- a/tests/server/providers/local_provider_tools/test_decorator.py+++ b/tests/server/providers/local_provider_tools/test_decorator.py@@ -10,6 +10,7 @@ from typing_extensions import TypedDictfrom fastmcp import FastMCPfrom fastmcp.exceptions import NotFoundErrorfrom fastmcp.tools.base import Tool+from fastmcp.tools.function_tool import ToolMetadef _normalize_anyof_order(schema):@@ -339,3 +340,66 @@ class TestToolDecorator:tool = next(t for t in tools if t.name == "multiply")assert tool.meta == meta_data+++class TestDecoratorMetadataNotLeftBehind:+ """A rejected registration must not stamp the caller's function.++ ``decorate_and_register`` writes ``__fastmcp__`` metadata onto the function+ before ``add_tool`` validates it. Validation is where a sync body with+ ``task=True`` is rejected, so without a rollback the rejected call+ leaves ``task=True`` behind and the same function can no longer be+ registered anywhere β including on a server that has no tasks at all.+ """++ async def test_rejected_registration_removes_the_stamp(self):+ mcp = FastMCP("tasks_on")++ def sync_tool(x: int = 1) -> str:+ return f"ok{x}"++ with pytest.raises(ValueError, match="Background tasks require async"):+ mcp.tool(sync_tool, task=True)++ assert not hasattr(sync_tool, "__fastmcp__")++ async def test_function_is_registerable_on_another_server_after_rejection(self):+ mcp = FastMCP("tasks_on")++ def sync_tool(x: int = 1) -> str:+ return f"ok{x}"++ with pytest.raises(ValueError, match="Background tasks require async"):+ mcp.tool(sync_tool, task=True)++ other = FastMCP("no_tasks")+ added = other.add_tool(sync_tool)++ assert added.task_config.mode == "forbidden"++ async def test_successful_registration_keeps_the_stamp(self):+ mcp = FastMCP("tasks_on")++ async def async_tool(x: int = 1) -> str:+ return f"ok{x}"++ mcp.tool(async_tool, task=True)++ assert hasattr(async_tool, "__fastmcp__")+ tool = await mcp.get_tool("async_tool")+ assert tool is not None+ assert tool.task_config.mode == "optional"++ async def test_pre_existing_stamp_survives_a_rejection(self):+ mcp = FastMCP("tasks_on")++ def sync_tool(x: int = 1) -> str:+ return f"ok{x}"++ sentinel = ToolMeta(task=True, name="pre-existing")+ sync_tool.__fastmcp__ = sentinel # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]++ with pytest.raises(ValueError, match="Background tasks require async"):+ mcp.tool(sync_tool, task=True)++ assert sync_tool.__fastmcp__ is sentinel # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]