Skip to content

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

Resolve injected tools through the server's tool lookup (#5431)

Jeremiah Lowin635db7bde13f
diff --git a/fastmcp_slim/fastmcp/server/middleware/tool_injection.py b/fastmcp_slim/fastmcp/server/middleware/tool_injection.py
index ef88dfc0f..65fbf85a0 100644
--- a/fastmcp_slim/fastmcp/server/middleware/tool_injection.py
+++ b/fastmcp_slim/fastmcp/server/middleware/tool_injection.py
@@ -3,18 +3,29 @@
from collections.abc import Sequence
from logging import Logger
-import mcp_types
-from typing_extensions import override
-
-from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext
-from fastmcp.tools.base import Tool, ToolResult
+from fastmcp.server.middleware.middleware import Middleware
+from fastmcp.tools.base import Tool
from fastmcp.utilities.logging import get_logger
logger: Logger = get_logger(name=__name__)
class ToolInjectionMiddleware(Middleware):
- """A middleware for injecting tools into the context."""
+ """A middleware for injecting tools into the context.
+
+ The server this middleware is added to lists and calls the injected tools
+ alongside its own. They are resolved by the server's tool lookup, so a
+ tool's `auth` check and every middleware in the chain, including
+ `AuthMiddleware`, apply to them as they do to registered tools, wherever
+ this middleware sits in the chain. Server and session visibility settings
+ do not apply to injected tools.
+
+ Injected tools are matched by name alone; a requested version is ignored.
+ An injected tool takes precedence over a registered tool with the same
+ name, and the registered tool is no longer listed. When several injection
+ middleware provide the same name, the one added first takes precedence.
+ Injected tools follow their task configuration as registered tools do.
+ """
def __init__(self, tools: Sequence[Tool]):
"""Initialize the tool injection middleware."""
@@ -23,24 +34,15 @@ class ToolInjectionMiddleware(Middleware):
tool.name: tool for tool in tools
}
- @override
- async def on_list_tools(
- self,
- context: MiddlewareContext[mcp_types.ListToolsRequest],
- call_next: CallNext[mcp_types.ListToolsRequest, Sequence[Tool]],
- ) -> Sequence[Tool]:
- """Inject tools into the response."""
- return [*self._tools_to_inject, *await call_next(context)]
-
- @override
- async def on_call_tool(
- self,
- context: MiddlewareContext[mcp_types.CallToolRequestParams],
- call_next: CallNext[mcp_types.CallToolRequestParams, ToolResult],
- ) -> ToolResult:
- """Intercept tool calls to injected tools."""
- if context.message.name in self._tools_to_inject_by_name:
- tool = self._tools_to_inject_by_name[context.message.name]
- return await tool.run(arguments=context.message.arguments or {})
-
- return await call_next(context)
+ @property
+ def injected_tools(self) -> Sequence[Tool]:
+ """The tools this middleware injects, one per name.
+
+ If several given tools share a name, the last one is kept, matching
+ `get_injected_tool()`.
+ """
+ return list(self._tools_to_inject_by_name.values())
+
+ def get_injected_tool(self, name: str) -> Tool | None:
+ """Return the injected tool with this name, if there is one."""
+ return self._tools_to_inject_by_name.get(name)
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index 24aba653a..ba4ce6965 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -86,6 +86,7 @@ from fastmcp.server.middleware.middleware import (
_dispatch_phase,
mark_interior_dispatched,
)
+from fastmcp.server.middleware.tool_injection import ToolInjectionMiddleware
from fastmcp.server.mixins import LifespanMixin, MCPOperationsMixin, TransportMixin
from fastmcp.server.mixins.extensions import ExtensionsMixin
from fastmcp.server.providers import LocalProvider, Provider
@@ -233,6 +234,18 @@ LifespanCallable = Callable[
]
+async def _tool_auth_allows(tool: Tool) -> bool:
+ """Whether the tool's own `auth` check admits the current request."""
+ skip_auth, token = _get_auth_context()
+ if skip_auth or tool.auth is None:
+ return True
+ ctx = AuthContext(token=token, component=tool)
+ try:
+ return await run_auth_checks(tool.auth, ctx)
+ except AuthorizationError:
+ return False
+
+
def _get_auth_context() -> tuple[bool, Any]:
"""Get auth context for the current request.
@@ -624,6 +637,28 @@ class FastMCP(
def add_middleware(self, middleware: Middleware) -> None:
self.middleware.append(middleware)
+ def _injected_tools(self) -> list[Tool]:
+ """Tools added by `ToolInjectionMiddleware`, one per name.
+
+ Each name maps to the tool `_get_injected_tool()` resolves for it: the
+ one from the outermost middleware that injects that name.
+ """
+ by_name: dict[str, Tool] = {}
+ for middleware in self.middleware:
+ if isinstance(middleware, ToolInjectionMiddleware):
+ for tool in middleware.injected_tools:
+ by_name.setdefault(tool.name, tool)
+ return list(by_name.values())
+
+ def _get_injected_tool(self, name: str) -> Tool | None:
+ """The injected tool with this name from the outermost middleware that has one."""
+ for middleware in self.middleware:
+ if isinstance(middleware, ToolInjectionMiddleware):
+ tool = middleware.get_injected_tool(name)
+ if tool is not None:
+ return tool
+ return None
+
def required_extensions(self) -> Sequence[ServerExtension]:
"""Bundled extensions and auto-registerable registrations for composition."""
return self._required_extensions()
@@ -751,10 +786,20 @@ class FastMCP(
# Get tasks from AggregateProvider (handles aggregation and namespacing)
components = list(await super().get_tasks())
+ # An injected tool owns its name, as in `list_tools()` and
+ # `get_tool()`: tools with that name are not registered, so the
+ # injected tool is the only one that runs as a background task.
+ injected = self._injected_tools()
+ claimed = {tool.name for tool in injected}
+
return [
- c
- for c in await self._apply_task_transforms(components)
- if c.task_config.supports_tasks()
+ *[t for t in injected if t.task_config.supports_tasks()],
+ *[
+ c
+ for c in await self._apply_task_transforms(components)
+ if c.task_config.supports_tasks()
+ and not (isinstance(c, Tool) and c.name in claimed)
+ ],
]
def add_transform(self, transform: Transform) -> None:
@@ -816,18 +861,15 @@ class FastMCP(
# Tool objects are not mutated.
tools = self._rewrite_prefab_uris(tools)
- skip_auth, token = _get_auth_context()
- authorized: list[Tool] = []
- for tool in tools:
- if not skip_auth and tool.auth is not None:
- ctx = AuthContext(token=token, component=tool)
- try:
- if not await run_auth_checks(tool.auth, ctx):
- continue
- except AuthorizationError:
- continue
- authorized.append(tool)
- return authorized
+ # Tools from ToolInjectionMiddleware are listed ahead of the
+ # providers' tools and authorized the same way. An injected
+ # tool owns its name, so provider tools with that name are not
+ # listed, matching what `get_tool()` resolves.
+ injected = self._injected_tools()
+ claimed = {tool.name for tool in injected}
+ tools = [*injected, *(t for t in tools if t.name not in claimed)]
+
+ return [tool for tool in tools if await _tool_auth_allows(tool)]
async def _get_tool(
self, name: str, version: VersionSpec | None = None
@@ -849,24 +891,11 @@ 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)
- try:
- if not await run_auth_checks(tool.auth, ctx):
- return None
- except AuthorizationError:
- return None
-
- return tool
+ return tool if await _tool_auth_allows(tool) else None
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)
+ return tool if await _tool_auth_allows(tool) else None
async def get_tool(
self, name: str, version: VersionSpec | None = None
@@ -880,13 +909,27 @@ class FastMCP(
When the highest version is disabled and no explicit version was
requested, falls back to the next-highest enabled version.
+ A tool from `ToolInjectionMiddleware` takes precedence over a provider
+ tool with the same name. It is matched by name alone, so a requested
+ version is ignored, and it is subject to its own `auth` check but not
+ to transforms or visibility.
+
Args:
name: The tool name.
version: Version filter (None returns highest version).
Returns:
- The tool if found and enabled, None otherwise.
+ The tool if found, enabled, and authorized, None otherwise.
"""
+ # A hashed lookup resolves one identity; injected tools have none.
+ injected = (
+ self._get_injected_tool(name)
+ if hashed_lookup_target(self) is None
+ else None
+ )
+ if injected is not None:
+ return injected if await _tool_auth_allows(injected) else None
+
tool = await super().get_tool(name, version)
if tool is None:
return None
@@ -912,17 +955,7 @@ class FastMCP(
all_tools = list(await apply_session_transforms(all_tools))
enabled = [t for t in all_tools if is_enabled(t)]
- skip_auth, token = _get_auth_context()
- authorized: list[Tool] = []
- for t in enabled:
- if not skip_auth and t.auth is not None:
- ctx = AuthContext(token=token, component=t)
- try:
- if not await run_auth_checks(t.auth, ctx):
- continue
- except AuthorizationError:
- continue
- authorized.append(t)
+ authorized = [t for t in enabled if await _tool_auth_allows(t)]
if not authorized:
return None
diff --git a/tests/server/middleware/test_tool_injection.py b/tests/server/middleware/test_tool_injection.py
index dcbccf5a8..abd56d7b9 100644
--- a/tests/server/middleware/test_tool_injection.py
+++ b/tests/server/middleware/test_tool_injection.py
@@ -1,20 +1,27 @@
"""Tests for tool injection middleware."""
import math
+from collections.abc import Callable
import pytest
from inline_snapshot import snapshot
from mcp_types import Tool as SDKTool
-from fastmcp import FastMCP
+from fastmcp import FastMCP, FastMCPApp
from fastmcp.client import Client
from fastmcp.client.client import CallToolResult
from fastmcp.client.transports import FastMCPTransport
+from fastmcp.exceptions import ToolError
+from fastmcp.server.auth import require_scopes
+from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
+from fastmcp.server.middleware import AuthMiddleware, Middleware
from fastmcp.server.middleware.tool_injection import (
ToolInjectionMiddleware,
)
+from fastmcp.server.providers.addressing import hashed_backend_name
from fastmcp.tools.base import Tool
from fastmcp.tools.function_tool import FunctionTool
+from fastmcp.utilities.tests import asgi_client
def multiply_fn(a: int, b: int) -> int:
@@ -277,3 +284,203 @@ class TestToolInjectionMiddleware:
assert result.structured_content is not None
assert isinstance(result.structured_content, dict)
assert result.structured_content["result"] == 7
+
+
+TOKENS = {
+ "read-token": {"client_id": "reader", "scopes": ["read"]},
+ "admin-token": {"client_id": "administrator", "scopes": ["read", "admin"]},
+}
+
+
+def admin_report() -> str:
+ """Return the admin report."""
+ return "Quarterly totals"
+
+
+def public_report() -> str:
+ """Return the public report."""
+ return "Public summary"
+
+
+def make_auth_server(*middleware: Middleware) -> FastMCP:
+ return FastMCP(
+ "AuthServer",
+ auth=StaticTokenVerifier(TOKENS),
+ middleware=list(middleware),
+ )
+
+
+def scoped_admin_tool() -> Tool:
+ return Tool.from_function(
+ admin_report,
+ name="admin_report",
+ auth=require_scopes("admin"),
+ )
+
+
+def unscoped_tool(fn: Callable[[], str], name: str) -> Tool:
+ return Tool.from_function(fn, name=name)
+
+
+class TestInjectedToolAuthorization:
+ """Injected tools follow the same authorization as registered tools."""
+
+ async def test_tool_auth_hides_injected_tool_without_scope(self):
+ server = make_auth_server(ToolInjectionMiddleware([scoped_admin_tool()]))
+
+ async with asgi_client(server, auth="read-token") as client:
+ tools = await client.list_tools()
+
+ assert "admin_report" not in [tool.name for tool in tools]
+
+ async def test_tool_auth_denies_injected_tool_call_without_scope(self):
+ server = make_auth_server(ToolInjectionMiddleware([scoped_admin_tool()]))
+
+ async with asgi_client(server, auth="read-token") as client:
+ with pytest.raises(ToolError, match="Unknown tool"):
+ await client.call_tool("admin_report", {})
+
+ async def test_tool_auth_allows_injected_tool_with_scope(self):
+ server = make_auth_server(ToolInjectionMiddleware([scoped_admin_tool()]))
+
+ async with asgi_client(server, auth="admin-token") as client:
+ tools = await client.list_tools()
+ result = await client.call_tool("admin_report", {})
+
+ assert "admin_report" in [tool.name for tool in tools]
+ assert result.data == "Quarterly totals"
+
+ async def test_tool_auth_on_injected_tool_matches_registered_tool(self):
+ """An injected tool and a registered tool with the same auth agree."""
+ registered = make_auth_server()
+ registered.add_tool(scoped_admin_tool())
+ injected = make_auth_server(ToolInjectionMiddleware([scoped_admin_tool()]))
+
+ outcomes: list[tuple[list[str], bool]] = []
+ for server in (registered, injected):
+ async with asgi_client(server, auth="read-token") as client:
+ names = [tool.name for tool in await client.list_tools()]
+ result = await client.call_tool(
+ "admin_report", {}, raise_on_error=False
+ )
+ outcomes.append((names, result.is_error))
+
+ assert outcomes[0] == outcomes[1] == ([], True)
+
+ async def test_injected_tool_without_auth_is_available_to_any_token(self):
+ server = make_auth_server(
+ ToolInjectionMiddleware([unscoped_tool(public_report, "public_report")])
+ )
+
+ async with asgi_client(server, auth="read-token") as client:
+ tools = await client.list_tools()
+ result = await client.call_tool("public_report", {})
+
+ assert [tool.name for tool in tools] == ["public_report"]
+ assert result.data == "Public summary"
+
+ @pytest.mark.parametrize("injection_first", [True, False])
+ async def test_auth_middleware_denies_injected_tool(self, injection_first: bool):
+ injection = ToolInjectionMiddleware(
+ [unscoped_tool(admin_report, "admin_report")]
+ )
+ auth = AuthMiddleware(auth=require_scopes("admin"))
+ order = [injection, auth] if injection_first else [auth, injection]
+ server = make_auth_server(*order)
+
+ async with asgi_client(server, auth="read-token") as client:
+ tools = await client.list_tools()
+ result = await client.call_tool("admin_report", {}, raise_on_error=False)
+
+ assert tools == []
+ assert result.is_error
+ assert "Quarterly totals" not in str(result.content)
+
+ @pytest.mark.parametrize("injection_first", [True, False])
+ async def test_auth_middleware_allows_injected_tool(self, injection_first: bool):
+ injection = ToolInjectionMiddleware(
+ [unscoped_tool(admin_report, "admin_report")]
+ )
+ auth = AuthMiddleware(auth=require_scopes("admin"))
+ order = [injection, auth] if injection_first else [auth, injection]
+ server = make_auth_server(*order)
+
+ async with asgi_client(server, auth="admin-token") as client:
+ tools = await client.list_tools()
+ result = await client.call_tool("admin_report", {})
+
+ assert [tool.name for tool in tools] == ["admin_report"]
+ assert result.data == "Quarterly totals"
+
+ async def test_injected_tool_on_mounted_server_follows_tool_auth(self):
+ child = FastMCP(
+ "Child",
+ middleware=[ToolInjectionMiddleware([scoped_admin_tool()])],
+ )
+ parent = make_auth_server()
+ parent.mount(child, namespace="child")
+
+ async with asgi_client(parent, auth="read-token") as client:
+ read_tools = await client.list_tools()
+ read_result = await client.call_tool(
+ "child_admin_report", {}, raise_on_error=False
+ )
+ async with asgi_client(parent, auth="admin-token") as client:
+ admin_tools = await client.list_tools()
+ admin_result = await client.call_tool("child_admin_report", {})
+
+ assert read_tools == []
+ assert read_result.is_error
+ assert [tool.name for tool in admin_tools] == ["child_admin_report"]
+ assert admin_result.data == "Quarterly totals"
+
+ async def test_shadowed_registered_tool_is_not_listed(self):
+ """Listing and calling agree when an injected tool shadows a registered one."""
+ server = make_auth_server(
+ ToolInjectionMiddleware(
+ [
+ Tool.from_function(
+ admin_report, name="report", auth=require_scopes("admin")
+ )
+ ]
+ )
+ )
+ server.add_tool(unscoped_tool(public_report, "report"))
+
+ async with asgi_client(server, auth="read-token") as client:
+ read_tools = await client.list_tools()
+ read_result = await client.call_tool("report", {}, raise_on_error=False)
+ async with asgi_client(server, auth="admin-token") as client:
+ admin_tools = await client.list_tools()
+ admin_result = await client.call_tool("report", {})
+
+ assert read_tools == []
+ assert read_result.is_error
+ assert [tool.name for tool in admin_tools] == ["report"]
+ assert admin_result.data == "Quarterly totals"
+
+ async def test_hashed_call_reaches_app_tool_sharing_injected_name(self):
+ """An injected tool owns its display name, not an app tool's hashed name."""
+ app = FastMCPApp("contacts")
+
+ @app.tool()
+ def save(name: str) -> str:
+ return f"app saved {name}"
+
+ def injected_save(name: str) -> str:
+ return f"injected saved {name}"
+
+ server = FastMCP("Platform")
+ server.add_provider(app)
+ server.add_middleware(
+ ToolInjectionMiddleware([Tool.from_function(injected_save, name="save")])
+ )
+
+ async with Client(server) as client:
+ by_name = await client.call_tool("save", {"name": "alice"})
+ by_hash = await client.call_tool(
+ hashed_backend_name("contacts", "save"), {"name": "alice"}
+ )
+
+ assert by_name.data == "injected saved alice"
+ assert by_hash.data == "app saved alice"
diff --git a/tests/tasks/server/test_task_middleware.py b/tests/tasks/server/test_task_middleware.py
index c9324fc2a..9a3058e5b 100644
--- a/tests/tasks/server/test_task_middleware.py
+++ b/tests/tasks/server/test_task_middleware.py
@@ -13,6 +13,8 @@ from fastmcp_tasks.models import CreateTaskResult
from fastmcp import FastMCP
from fastmcp.server.middleware.caching import ResponseCachingMiddleware
from fastmcp.server.middleware.response_limiting import ResponseLimitingMiddleware
+from fastmcp.server.middleware.tool_injection import ToolInjectionMiddleware
+from fastmcp.tools.base import Tool
from fastmcp_tasks import TasksExtension
from tests.tasks.task_helpers import running_task_server, submit_task, wait_for_task
@@ -35,3 +37,205 @@ async def test_tasked_call_survives_result_inspecting_middleware():
assert final.status == "completed"
assert final.result is not None
assert final.result["structuredContent"] == {"result": 81}
+
+
+async def square(n: int) -> int:
+ return n * n
+
+
+async def test_injected_task_tool_runs_as_task():
+ mcp = FastMCP("tasks-injected")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(ToolInjectionMiddleware([Tool.from_function(square, task=True)]))
+
+ async with running_task_server(mcp):
+ created = await submit_task(mcp, "square", {"n": 7})
+ assert isinstance(created, CreateTaskResult)
+ final = await wait_for_task(mcp, created.task_id)
+
+ assert final.status == "completed"
+ assert final.result is not None
+ assert final.result["structuredContent"] == {"result": 49}
+
+
+async def test_background_task_runs_the_injected_tool_when_its_name_is_shared():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-shared-name")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(
+ ToolInjectionMiddleware(
+ [Tool.from_function(injected_report, name="report", task=True)]
+ )
+ )
+
+ @mcp.tool(task=True)
+ async def report(n: int) -> str:
+ return f"registered {n}"
+
+ async with running_task_server(mcp):
+ created = await submit_task(mcp, "report", {"n": 3})
+ final = await wait_for_task(mcp, created.task_id)
+
+ assert final.status == "completed"
+ assert final.result is not None
+ assert final.result["structuredContent"] == {"result": "injected 3"}
+
+
+async def test_background_task_runs_the_injected_tool_when_signatures_differ():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-shared-name-signatures")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(
+ ToolInjectionMiddleware(
+ [Tool.from_function(injected_report, name="report", task=True)]
+ )
+ )
+
+ @mcp.tool(task=True)
+ async def report(label: str, flag: bool) -> str:
+ return f"registered {label} {flag}"
+
+ async with running_task_server(mcp):
+ created = await submit_task(mcp, "report", {"n": 5})
+ final = await wait_for_task(mcp, created.task_id)
+
+ assert final.status == "completed"
+ assert final.result is not None
+ assert final.result["structuredContent"] == {"result": "injected 5"}
+
+
+async def test_background_task_runs_the_injected_tool_when_registered_tool_is_not_task_capable():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-shared-name-forbidden")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(
+ ToolInjectionMiddleware(
+ [Tool.from_function(injected_report, name="report", task=True)]
+ )
+ )
+
+ @mcp.tool(task=False)
+ async def report(n: int) -> str:
+ return f"registered {n}"
+
+ async with running_task_server(mcp):
+ created = await submit_task(mcp, "report", {"n": 2})
+ final = await wait_for_task(mcp, created.task_id)
+
+ assert final.result is not None
+ assert final.result["structuredContent"] == {"result": "injected 2"}
+
+
+async def test_task_discovery_lists_one_tool_for_a_shared_name():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-shared-name-discovery")
+ mcp.add_extension(TasksExtension())
+ injected = Tool.from_function(injected_report, name="report", task=True)
+ mcp.add_middleware(ToolInjectionMiddleware([injected]))
+
+ @mcp.tool(task=True)
+ async def report(n: int) -> str:
+ return f"registered {n}"
+
+ @mcp.tool(task=True)
+ async def other(n: int) -> str:
+ return f"other {n}"
+
+ components = await mcp.get_tasks()
+ reports = [c for c in components if c.name == "report"]
+
+ assert reports == [injected]
+ assert {c.name for c in components} == {"report", "other"}
+
+
+async def test_mounted_tool_shadowed_by_an_injected_tool_is_not_registered_as_a_task():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ child = FastMCP("child")
+
+ @child.tool(task=True)
+ async def report(n: int) -> str:
+ return f"mounted {n}"
+
+ @child.tool(task=True)
+ async def summary(n: int) -> str:
+ return f"summary {n}"
+
+ mcp = FastMCP("tasks-shared-name-mounted")
+ mcp.add_extension(TasksExtension())
+ mcp.mount(child, namespace="child")
+ injected = Tool.from_function(injected_report, name="child_report", task=True)
+ mcp.add_middleware(ToolInjectionMiddleware([injected]))
+
+ components = await mcp.get_tasks()
+ assert [c for c in components if c.name == "child_report"] == [injected]
+ assert "child_summary" in {c.name for c in components}
+
+ async with running_task_server(mcp):
+ shadowed = await submit_task(mcp, "child_report", {"n": 4})
+ unshadowed = await submit_task(mcp, "child_summary", {"n": 4})
+ shadowed_final = await wait_for_task(mcp, shadowed.task_id)
+ unshadowed_final = await wait_for_task(mcp, unshadowed.task_id)
+
+ assert shadowed_final.result is not None
+ assert shadowed_final.result["structuredContent"] == {"result": "injected 4"}
+ assert unshadowed_final.result is not None
+ assert unshadowed_final.result["structuredContent"] == {"result": "summary 4"}
+
+
+async def test_task_tools_with_distinct_names_all_run_as_background_tasks():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-distinct-names")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(
+ ToolInjectionMiddleware(
+ [Tool.from_function(injected_report, name="injected_only", task=True)]
+ )
+ )
+
+ @mcp.tool(task=True)
+ async def registered_only(n: int) -> str:
+ return f"registered {n}"
+
+ async with running_task_server(mcp):
+ first = await submit_task(mcp, "injected_only", {"n": 1})
+ second = await submit_task(mcp, "registered_only", {"n": 2})
+ first_final = await wait_for_task(mcp, first.task_id)
+ second_final = await wait_for_task(mcp, second.task_id)
+
+ assert first_final.result is not None
+ assert first_final.result["structuredContent"] == {"result": "injected 1"}
+ assert second_final.result is not None
+ assert second_final.result["structuredContent"] == {"result": "registered 2"}
+
+
+async def test_task_discovery_skips_a_registered_tool_shadowed_by_a_synchronous_injected_tool():
+ async def injected_report(n: int) -> str:
+ return f"injected {n}"
+
+ mcp = FastMCP("tasks-shared-name-synchronous")
+ mcp.add_extension(TasksExtension())
+ mcp.add_middleware(
+ ToolInjectionMiddleware(
+ [Tool.from_function(injected_report, name="report", task=False)]
+ )
+ )
+
+ @mcp.tool(task=True)
+ async def report(n: int) -> str:
+ return f"registered {n}"
+
+ components = await mcp.get_tasks()
+
+ assert [c.name for c in components] == []