π The fast, Pythonic way to build MCP servers and clients.
Proxy tasks forbidden, mount tasks working
Chris Guidry82301773cfe1
diff --git a/pyproject.toml b/pyproject.tomlindex 80405616d..a9e37b46e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ dependencies = ["mcp>=1.23.1","openapi-pydantic>=0.5.1","platformdirs>=4.0.0",- "pydocket>=0.14.0",+ "pydocket>=0.15.2","rich>=13.9.4","cyclopts>=4.0.0","authlib>=1.6.5",diff --git a/src/fastmcp/cli/tasks.py b/src/fastmcp/cli/tasks.pyindex 931802d0f..23ddc6e58 100644--- a/src/fastmcp/cli/tasks.py+++ b/src/fastmcp/cli/tasks.py@@ -82,7 +82,7 @@ def worker(# Load server to get task functionstry:- config, resolved_spec = load_and_merge_config(server_spec)+ config, _resolved_spec = load_and_merge_config(server_spec)except FileNotFoundError:sys.exit(1)diff --git a/src/fastmcp/client/client.py b/src/fastmcp/client/client.pyindex 3842cd4f4..f4804f478 100644--- a/src/fastmcp/client/client.py+++ b/src/fastmcp/client/client.py@@ -849,9 +849,12 @@ class Client(Generic[ClientTransportT]):)# Check if server accepted background execution- if result.meta and "modelcontextprotocol.io/task" in result.meta:+ # If response includes task metadata with taskId, server accepted background mode+ # If response includes returned_immediately=True, server declined and executed sync+ task_meta = (result.meta or {}).get("modelcontextprotocol.io/task", {})+ if task_meta.get("taskId"):# Background execution accepted - extract server-generated taskId- server_task_id = result.meta["modelcontextprotocol.io/task"]["taskId"]+ server_task_id = task_meta["taskId"]# Track this task ID for list_tasks()self._submitted_task_ids.add(server_task_id)@@ -1055,9 +1058,12 @@ class Client(Generic[ClientTransportT]):)# Check if server accepted background execution- if result.meta and "modelcontextprotocol.io/task" in result.meta:+ # If response includes task metadata with taskId, server accepted background mode+ # If response includes returned_immediately=True, server declined and executed sync+ task_meta = (result.meta or {}).get("modelcontextprotocol.io/task", {})+ if task_meta.get("taskId"):# Background execution accepted - extract server-generated taskId- server_task_id = result.meta["modelcontextprotocol.io/task"]["taskId"]+ server_task_id = task_meta["taskId"]# Track this task ID for list_tasks()self._submitted_task_ids.add(server_task_id)@@ -1397,10 +1403,12 @@ class Client(Generic[ClientTransportT]):)# Check if server accepted background execution- # If response includes task metadata, server accepted background mode- if result.meta and "modelcontextprotocol.io/task" in result.meta:+ # If response includes task metadata with taskId, server accepted background mode+ # If response includes returned_immediately=True, server declined and executed sync+ task_meta = (result.meta or {}).get("modelcontextprotocol.io/task", {})+ if task_meta.get("taskId"):# Background execution accepted - extract server-generated taskId- server_task_id = result.meta["modelcontextprotocol.io/task"]["taskId"]+ server_task_id = task_meta["taskId"]# Track this task ID for list_tasks()self._submitted_task_ids.add(server_task_id)@@ -1415,8 +1423,8 @@ class Client(Generic[ClientTransportT]):return task_objelse:# Server declined background execution (graceful degradation)- # Executed synchronously - wrap the immediate result- # Need to convert mcp.types.CallToolResult to our CallToolResult+ # or returned_immediately=True - executed synchronously+ # Wrap the immediate resultparsed_result = await self._parse_call_tool_result(name, result)# Use a synthetic task ID for the immediate resultsynthetic_task_id = task_id or str(uuid.uuid4())diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.pyindex 387450040..1493e730e 100644--- a/src/fastmcp/server/proxy.py+++ b/src/fastmcp/server/proxy.py@@ -35,6 +35,7 @@ from fastmcp.resources.resource_manager import ResourceManagerfrom fastmcp.server.context import Contextfrom fastmcp.server.dependencies import get_contextfrom fastmcp.server.server import FastMCP+from fastmcp.server.tasks.config import TaskConfigfrom fastmcp.tools.tool import Tool, ToolResultfrom fastmcp.tools.tool_manager import ToolManagerfrom fastmcp.tools.tool_transform import (@@ -259,6 +260,8 @@ class ProxyTool(Tool, MirroredComponent):A Tool that represents and executes a tool on a remote server."""+ task_config: TaskConfig = TaskConfig(mode="forbidden")+def __init__(self, client: Client, **kwargs: Any):super().__init__(**kwargs)self._client = client@@ -288,21 +291,36 @@ class ProxyTool(Tool, MirroredComponent):"""Executes the tool by making a call through the client."""async with self._client:context = get_context()- # try to get request context meta- meta = (- dict(context.request_context.meta)- if hasattr(context, "request_context")- and hasattr(context.request_context, "meta")- else None- )+ # Build meta dict from request context+ meta: dict[str, Any] | None = None+ if hasattr(context, "request_context"):+ req_ctx = context.request_context+ # Start with existing meta if present+ if hasattr(req_ctx, "meta") and req_ctx.meta:+ meta = dict(req_ctx.meta)+ # Add task metadata if this is a task request+ if (+ hasattr(req_ctx, "experimental")+ and hasattr(req_ctx.experimental, "is_task")+ and req_ctx.experimental.is_task+ ):+ task_metadata = req_ctx.experimental.task_metadata+ if task_metadata:+ meta = meta or {}+ meta["modelcontextprotocol.io/task"] = task_metadata.model_dump(+ exclude_none=True+ )+result = await self._client.call_tool_mcp(name=self.name, arguments=arguments, meta=meta)if result.isError:raise ToolError(cast(mcp.types.TextContent, result.content[0]).text)+ # Preserve backend's meta (includes task metadata for background tasks)return ToolResult(content=result.content,structured_content=result.structuredContent,+ meta=result.meta,)@@ -311,6 +329,7 @@ class ProxyResource(Resource, MirroredComponent):A Resource that represents and reads a resource from a remote server."""+ task_config: TaskConfig = TaskConfig(mode="forbidden")_client: Client_value: str | bytes | None = None@@ -343,6 +362,7 @@ class ProxyResource(Resource, MirroredComponent):icons=mcp_resource.icons,meta=mcp_resource.meta,tags=(mcp_resource.meta or {}).get("_fastmcp", {}).get("tags", []),+ task_config=TaskConfig(mode="forbidden"),_mirrored=True,)@@ -366,6 +386,8 @@ class ProxyTemplate(ResourceTemplate, MirroredComponent):A ResourceTemplate that represents and creates resources from a remote server template."""+ task_config: TaskConfig = TaskConfig(mode="forbidden")+def __init__(self, client: Client, **kwargs: Any):super().__init__(**kwargs)self._client = client@@ -386,6 +408,7 @@ class ProxyTemplate(ResourceTemplate, MirroredComponent):parameters={}, # Remote templates don't have local parametersmeta=mcp_template.meta,tags=(mcp_template.meta or {}).get("_fastmcp", {}).get("tags", []),+ task_config=TaskConfig(mode="forbidden"),_mirrored=True,)@@ -431,6 +454,7 @@ class ProxyPrompt(Prompt, MirroredComponent):A Prompt that represents and renders a prompt from a remote server."""+ task_config: TaskConfig = TaskConfig(mode="forbidden")_client: Clientdef __init__(self, client: Client, **kwargs):@@ -459,6 +483,7 @@ class ProxyPrompt(Prompt, MirroredComponent):icons=mcp_prompt.icons,meta=mcp_prompt.meta,tags=(mcp_prompt.meta or {}).get("_fastmcp", {}).get("tags", []),+ task_config=TaskConfig(mode="forbidden"),_mirrored=True,)diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 4cb40c5a7..a0f0a0725 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -435,6 +435,13 @@ class FastMCP(Generic[LifespanResultT]):):docket.register(template.fn)+ # Also register functions from mounted servers so tasks can+ # execute in the parent's Docket context+ for mounted in self._mounted_servers:+ await self._register_mounted_server_functions(+ mounted.server, docket+ )+# Set Docket in ContextVar so CurrentDocket can access itdocket_token = _current_docket.set(docket)try:@@ -473,6 +480,47 @@ class FastMCP(Generic[LifespanResultT]):# Reset server ContextVar_current_server.reset(server_token)+ async def _register_mounted_server_functions(+ self, server: FastMCP, docket: Docket+ ) -> None:+ """Register task-enabled functions from a mounted server with Docket.++ This enables background task execution for mounted server components+ through the parent server's Docket context.+ """+ # Register tools+ for tool in server._tool_manager._tools.values():+ if isinstance(tool, FunctionTool) and tool.task_config.mode != "forbidden":+ docket.register(tool.fn)++ # Register prompts+ for prompt in server._prompt_manager._prompts.values():+ if (+ isinstance(prompt, FunctionPrompt)+ and prompt.task_config.mode != "forbidden"+ ):+ docket.register(cast(Callable[..., Awaitable[Any]], prompt.fn))++ # Register resources+ for resource in server._resource_manager._resources.values():+ if (+ isinstance(resource, FunctionResource)+ and resource.task_config.mode != "forbidden"+ ):+ docket.register(resource.fn)++ # Register resource templates+ for template in server._resource_manager._templates.values():+ if (+ isinstance(template, FunctionResourceTemplate)+ and template.task_config.mode != "forbidden"+ ):+ docket.register(template.fn)++ # Recursively register from nested mounted servers+ for nested in server._mounted_servers:+ await self._register_mounted_server_functions(nested.server, docket)+@asynccontextmanagerasync def _lifespan_manager(self) -> AsyncIterator[None]:if self._lifespan_result_set:@@ -591,41 +639,78 @@ class FastMCP(Generic[LifespanResultT]):# Check for task metadata and route appropriatelyif fastmcp.settings.enable_tasks:async with fastmcp.server.context.Context(fastmcp=self):- try:- resource = await self._resource_manager.get_resource(uri)- if resource and isinstance(resource, FunctionResource):- task_mode = resource.task_config.mode-- # Enforce mode="required" - must have task metadata- if task_mode == "required" and not task_meta:- raise McpError(- ErrorData(- code=METHOD_NOT_FOUND,- message=f"Resource '{uri}' requires task-augmented execution",- )- )+ # Get resource including from mounted servers+ resource = await self._get_resource_with_task_config(str(uri))+ if resource and hasattr(resource, "task_config"):+ task_mode = resource.task_config.mode # type: ignore[union-attr]- # Enforce mode="forbidden" - must not have task metadata- if task_mode == "forbidden" and task_meta:- raise McpError(- ErrorData(- code=METHOD_NOT_FOUND,- message=f"Resource '{uri}' does not support task-augmented execution",- )+ # Enforce mode="required" - must have task metadata+ if task_mode == "required" and not task_meta:+ raise McpError(+ ErrorData(+ code=METHOD_NOT_FOUND,+ message=f"Resource '{uri}' requires task-augmented execution",)+ )- # Route to background if task metadata present and mode allows- if task_meta and task_mode != "forbidden":+ # Route to background if task metadata present and mode allows+ if task_meta and task_mode != "forbidden":+ # For FunctionResource/FunctionResourceTemplate, use Docket+ if isinstance(+ resource, (FunctionResource, FunctionResourceTemplate)+ ):task_meta_dict = task_meta.model_dump(exclude_none=True)return await handle_resource_as_task(self, str(uri), resource, task_meta_dict)- except NotFoundError:- pass++ # Forbidden mode: task requested but mode="forbidden"+ # Raise error since resources don't have isError field+ if task_meta and task_mode == "forbidden":+ raise McpError(+ ErrorData(+ code=METHOD_NOT_FOUND,+ message=f"Resource '{uri}' does not support task-augmented execution",+ )+ )# Synchronous executionresult = await self._read_resource_mcp(uri)+ # Graceful degradation: if we got here with task_meta, something went wrong+ # (This should be unreachable now that forbidden raises)+ if task_meta:+ mcp_contents = []+ for item in result:+ if isinstance(item.content, str):+ mcp_contents.append(+ mcp.types.TextResourceContents(+ uri=uri,+ text=item.content,+ mimeType=item.mime_type or "text/plain",+ )+ )+ elif isinstance(item.content, bytes):+ import base64++ mcp_contents.append(+ mcp.types.BlobResourceContents(+ uri=uri,+ blob=base64.b64encode(item.content).decode(),+ mimeType=item.mime_type or "application/octet-stream",+ )+ )+ return mcp.types.ServerResult(+ mcp.types.ReadResourceResult(+ contents=mcp_contents,+ _meta={+ "modelcontextprotocol.io/task": {+ "returned_immediately": True+ }+ },+ )+ )+# Convert to proper ServerResultif isinstance(result, mcp.types.ServerResult):return result@@ -683,8 +768,8 @@ class FastMCP(Generic[LifespanResultT]):async with fastmcp.server.context.Context(fastmcp=self):prompts = await self.get_prompts()prompt = prompts.get(name)- if prompt and isinstance(prompt, FunctionPrompt):- task_mode = prompt.task_config.mode+ if prompt and hasattr(prompt, "task_config") and prompt.task_config:+ task_mode = prompt.task_config.mode # type: ignore[union-attr]# Enforce mode="required" - must have task metadataif task_mode == "required" and not task_meta:@@ -695,15 +780,6 @@ class FastMCP(Generic[LifespanResultT]):))- # Enforce mode="forbidden" - must not have task metadata- if task_mode == "forbidden" and task_meta:- raise McpError(- ErrorData(- code=METHOD_NOT_FOUND,- message=f"Prompt '{name}' does not support task-augmented execution",- )- )-# Route to background if task metadata present and mode allowsif task_meta and task_mode != "forbidden":task_meta_dict = task_meta.model_dump(exclude_none=True)@@ -712,6 +788,16 @@ class FastMCP(Generic[LifespanResultT]):)return mcp.types.ServerResult(result)+ # Forbidden mode: task requested but mode="forbidden"+ # Raise error since prompts don't have isError field+ if task_meta and task_mode == "forbidden":+ raise McpError(+ ErrorData(+ code=METHOD_NOT_FOUND,+ message=f"Prompt '{name}' does not support task-augmented execution",+ )+ )+# Synchronous executionresult = await self._get_prompt_mcp(name, arguments)return mcp.types.ServerResult(result)@@ -813,6 +899,39 @@ class FastMCP(Generic[LifespanResultT]):raise NotFoundError(f"Unknown tool: {key}")return tools[key]+ async def _get_tool_with_task_config(self, key: str) -> Tool | None:+ """Get a tool by key, returning None if not found.++ Used for task config checking where we need the actual tool object+ (including from mounted servers and proxies) but don't want to raise.+ """+ try:+ return await self.get_tool(key)+ except NotFoundError:+ return None++ async def _get_resource_with_task_config(+ self, uri: str+ ) -> Resource | ResourceTemplate | None:+ """Get a resource or template by URI, returning None if not found.++ Used for task config checking where we need the actual resource object+ (including from mounted servers) but don't want to raise.+ """+ # Try exact resource match first+ try:+ return await self.get_resource(uri)+ except NotFoundError:+ pass++ # Try resource templates for URI pattern matching+ templates = await self.get_resource_templates()+ for template in templates.values():+ if template.matches(uri):+ return template++ return None+async def get_resources(self) -> dict[str, Resource]:"""Get all resources (unfiltered), including mounted servers, indexed by key."""all_resources = dict(await self._resource_manager.get_resources())@@ -863,11 +982,12 @@ class FastMCP(Generic[LifespanResultT]):if mounted.prefixelse key)- update = (- {"name": f"{mounted.prefix}_{template.name}"}- if mounted.prefix and template.name- else {}- )+ update: dict[str, Any] = {}+ if mounted.prefix:+ if template.name:+ update["name"] = f"{mounted.prefix}_{template.name}"+ # Update uri_template so matches() works with prefixed URIs+ update["uri_template"] = new_keyall_templates[new_key] = template.model_copy(key=new_key, update=update)@@ -1375,9 +1495,10 @@ class FastMCP(Generic[LifespanResultT]):passif fastmcp.settings.enable_tasks:- tool = self._tool_manager._tools.get(key)- if tool and isinstance(tool, FunctionTool):- task_mode = tool.task_config.mode+ # Get tool from local manager, mounted servers, or proxy+ tool = await self._get_tool_with_task_config(key)+ if tool and hasattr(tool, "task_config"):+ task_mode = tool.task_config.mode # type: ignore[union-attr]# Enforce mode="required" - must have task metadataif task_mode == "required" and not task_meta:@@ -1388,20 +1509,33 @@ class FastMCP(Generic[LifespanResultT]):))- # Enforce mode="forbidden" - must not have task metadata- if task_mode == "forbidden" and task_meta:- raise McpError(- ErrorData(- code=METHOD_NOT_FOUND,- message=f"Tool '{key}' does not support task-augmented execution",- )- )-# Route to background if task metadata present and mode allowsif task_meta and task_mode != "forbidden":- task_meta_dict = task_meta.model_dump(exclude_none=True)- return await handle_tool_as_task(- self, key, arguments, task_meta_dict+ # For FunctionTool, use Docket for background execution+ if isinstance(tool, FunctionTool):+ task_meta_dict = task_meta.model_dump(exclude_none=True)+ return await handle_tool_as_task(+ self, key, arguments, task_meta_dict+ )+ # For ProxyTool/mounted tools, proceed with normal execution+ # They will forward task metadata to their backend++ # Forbidden mode: task requested but mode="forbidden"+ # Return error result with returned_immediately=True+ if task_meta and task_mode == "forbidden":+ return mcp.types.CallToolResult(+ content=[+ mcp.types.TextContent(+ type="text",+ text=f"Tool '{key}' does not support task-augmented execution",+ )+ ],+ isError=True,+ _meta={+ "modelcontextprotocol.io/task": {+ "returned_immediately": True+ }+ },)# Synchronous execution (normal path)diff --git a/src/fastmcp/server/tasks/handlers.py b/src/fastmcp/server/tasks/handlers.pyindex e8be0b477..d3dcd9e3e 100644--- a/src/fastmcp/server/tasks/handlers.py+++ b/src/fastmcp/server/tasks/handlers.py@@ -308,10 +308,20 @@ async def handle_resource_as_task(await ctx.session.send_notification(notification) # type: ignore[arg-type]# Queue function to Docket (result storage via execution_ttl)- await docket.add(- resource.fn, # type: ignore[attr-defined]- key=task_key,- )()+ # For templates, extract URI params and pass them to the function+ from fastmcp.resources.template import FunctionResourceTemplate, match_uri_template++ if isinstance(resource, FunctionResourceTemplate):+ params = match_uri_template(uri, resource.uri_template) or {}+ await docket.add(+ resource.fn, # type: ignore[attr-defined]+ key=task_key,+ )(**params)+ else:+ await docket.add(+ resource.fn, # type: ignore[attr-defined]+ key=task_key,+ )()# Spawn subscription task to send status notifications (SEP-1686 optional feature)from fastmcp.server.tasks.subscriptions import subscribe_to_task_updatesdiff --git a/tests/server/tasks/test_task_mount.py b/tests/server/tasks/test_task_mount.pynew file mode 100644index 000000000..39c125333--- /dev/null+++ b/tests/server/tasks/test_task_mount.py@@ -0,0 +1,475 @@+"""+Tests for MCP SEP-1686 task protocol support through mounted servers.++Verifies that tasks work seamlessly when calling tools/prompts/resources+on mounted child servers through a parent server.+"""++import asyncio++import pytest+from docket import Docket++from fastmcp import FastMCP, TaskConfig+from fastmcp.client import Client+from fastmcp.server.dependencies import CurrentDocket, CurrentFastMCP++[email protected](autouse=True)+def reset_docket_memory_server():+ """Reset the shared Docket memory server between tests.++ Docket uses a class-level FakeServer instance for memory:// URLs which+ persists between tests, causing test isolation issues. This fixture+ clears that shared state before each test.+ """+ # Clear the shared FakeServer before each test+ if hasattr(Docket, "_memory_server"):+ delattr(Docket, "_memory_server")+ yield+ # Clean up after test as well+ if hasattr(Docket, "_memory_server"):+ delattr(Docket, "_memory_server")+++def child_server():+ """Create a child server with task-enabled components."""+ mcp = FastMCP("child-server")++ @mcp.tool(task=True)+ async def multiply(a: int, b: int) -> int:+ """Multiply two numbers."""+ return a * b++ @mcp.tool(task=True)+ async def slow_child_tool(duration: float = 0.1) -> str:+ """A child tool that takes time to execute."""+ await asyncio.sleep(duration)+ return "child completed"++ @mcp.tool(task=False)+ async def sync_child_tool(message: str) -> str:+ """Child tool that only supports synchronous execution."""+ return f"child sync: {message}"++ @mcp.prompt(task=True)+ async def child_prompt(topic: str) -> str:+ """A child prompt that can execute as a task."""+ return f"Here is information about {topic} from the child server."++ @mcp.resource("child://data.txt", task=True)+ async def child_resource() -> str:+ """A child resource that can be read as a task."""+ return "Data from child server"++ @mcp.resource("child://item/{item_id}.json", task=True)+ async def child_item_resource(item_id: str) -> str:+ """A child resource template that can execute as a task."""+ return f'{{"itemId": "{item_id}", "source": "child"}}'++ return mcp+++def parent_server(child_server):+ """Create a parent server with the child mounted."""+ parent = FastMCP("parent-server")++ @parent.tool(task=True)+ async def parent_tool(value: int) -> int:+ """A tool on the parent server."""+ return value * 10++ # Mount child with prefix+ parent.mount(child_server, prefix="child")++ return parent+++def parent_server_no_prefix(child_server):+ """Create a parent server with child mounted without prefix."""+ parent = FastMCP("parent-no-prefix")+ parent.mount(child_server) # No prefix+ return parent+++class TestMountedToolTasks:+ """Test task execution for mounted tools."""++ async def test_mounted_tool_task_returns_task_object(self, parent_server):+ """Mounted tool called with task=True returns a task object."""+ async with Client(parent_server) as client:+ # Tool name is prefixed: child_multiply+ task = await client.call_tool("child_multiply", {"a": 6, "b": 7}, task=True)++ assert task is not None+ assert hasattr(task, "task_id")+ assert isinstance(task.task_id, str)+ assert len(task.task_id) > 0++ async def test_mounted_tool_task_executes_in_background(self, parent_server):+ """Mounted tool task executes in background."""+ async with Client(parent_server) as client:+ task = await client.call_tool("child_multiply", {"a": 3, "b": 4}, task=True)++ # Should execute in background+ assert not task.returned_immediately++ async def test_mounted_tool_task_returns_correct_result(+ self, parent_server: FastMCP+ ):+ """Mounted tool task returns correct result."""+ async with Client(parent_server) as client:+ task = await client.call_tool("child_multiply", {"a": 8, "b": 9}, task=True)++ result = await task.result()+ assert result.data == 72++ async def test_mounted_tool_task_status(self, parent_server):+ """Can poll task status for mounted tool."""+ async with Client(parent_server) as client:+ task = await client.call_tool(+ "child_slow_child_tool", {"duration": 0.5}, task=True+ )++ # Check status while running+ status = await task.status()+ assert status.status in ["working", "completed"]++ # Wait for completion+ await task.wait(timeout=2.0)++ # Check status after completion+ status = await task.status()+ assert status.status == "completed"++ async def test_mounted_tool_task_cancellation(self, parent_server):+ """Can cancel a mounted tool task."""+ async with Client(parent_server) as client:+ task = await client.call_tool(+ "child_slow_child_tool", {"duration": 10.0}, task=True+ )++ # Let it start+ await asyncio.sleep(0.1)++ # Cancel the task+ await task.cancel()++ # Check status+ status = await task.status()+ assert status.status == "cancelled"++ async def test_graceful_degradation_sync_mounted_tool(self, parent_server):+ """Sync-only mounted tool returns error with task=True."""+ async with Client(parent_server) as client:+ task = await client.call_tool(+ "child_sync_child_tool", {"message": "hello"}, task=True+ )++ # Should return immediately with an error+ assert task.returned_immediately++ result = await task.result()+ assert result.is_error++ async def test_parent_and_mounted_tools_both_work(self, parent_server):+ """Both parent and mounted tools work as tasks."""+ async with Client(parent_server) as client:+ # Parent tool+ parent_task = await client.call_tool("parent_tool", {"value": 5}, task=True)+ # Mounted tool+ child_task = await client.call_tool(+ "child_multiply", {"a": 2, "b": 3}, task=True+ )++ parent_result = await parent_task.result()+ child_result = await child_task.result()++ assert parent_result.data == 50+ assert child_result.data == 6+++class TestMountedToolTasksNoPrefix:+ """Test task execution for mounted tools without prefix."""++ async def test_mounted_tool_without_prefix_task_works(+ self, parent_server_no_prefix+ ):+ """Mounted tool without prefix works as task."""+ async with Client(parent_server_no_prefix) as client:+ # No prefix, so tool keeps original name+ task = await client.call_tool("multiply", {"a": 5, "b": 6}, task=True)++ assert not task.returned_immediately++ result = await task.result()+ assert result.data == 30+++class TestMountedPromptTasks:+ """Test task execution for mounted prompts."""++ async def test_mounted_prompt_task_returns_task_object(self, parent_server):+ """Mounted prompt called with task=True returns a task object."""+ async with Client(parent_server) as client:+ # Prompt name is prefixed: child_child_prompt+ task = await client.get_prompt(+ "child_child_prompt", {"topic": "FastMCP"}, task=True+ )++ assert task is not None+ assert hasattr(task, "task_id")+ assert isinstance(task.task_id, str)++ async def test_mounted_prompt_task_executes_in_background(self, parent_server):+ """Mounted prompt task executes in background."""+ async with Client(parent_server) as client:+ task = await client.get_prompt(+ "child_child_prompt", {"topic": "testing"}, task=True+ )++ assert not task.returned_immediately++ async def test_mounted_prompt_task_returns_correct_result(+ self, parent_server: FastMCP+ ):+ """Mounted prompt task returns correct result."""+ async with Client(parent_server) as client:+ task = await client.get_prompt(+ "child_child_prompt", {"topic": "MCP protocol"}, task=True+ )++ result = await task.result()+ assert "MCP protocol" in result.messages[0].content.text+ assert "child server" in result.messages[0].content.text+++class TestMountedResourceTasks:+ """Test task execution for mounted resources."""++ async def test_mounted_resource_task_returns_task_object(self, parent_server):+ """Mounted resource read with task=True returns a task object."""+ async with Client(parent_server) as client:+ # Resource URI is prefixed: child://child/data.txt+ task = await client.read_resource("child://child/data.txt", task=True)++ assert task is not None+ assert hasattr(task, "task_id")+ assert isinstance(task.task_id, str)++ async def test_mounted_resource_task_executes_in_background(self, parent_server):+ """Mounted resource task executes in background."""+ async with Client(parent_server) as client:+ task = await client.read_resource("child://child/data.txt", task=True)++ assert not task.returned_immediately++ async def test_mounted_resource_task_returns_correct_result(self, parent_server):+ """Mounted resource task returns correct result."""+ async with Client(parent_server) as client:+ task = await client.read_resource("child://child/data.txt", task=True)++ result = await task.result()+ assert len(result) > 0+ assert "Data from child server" in result[0].text++ async def test_mounted_resource_template_task(self, parent_server):+ """Mounted resource template with task=True works."""+ async with Client(parent_server) as client:+ task = await client.read_resource("child://child/item/99.json", task=True)++ assert not task.returned_immediately++ result = await task.result()+ assert '"itemId": "99"' in result[0].text+ assert '"source": "child"' in result[0].text+++class TestMountedTaskDependencies:+ """Test that dependencies work correctly in mounted task execution."""++ async def test_mounted_task_receives_docket_dependency(self):+ """Mounted tool task receives CurrentDocket dependency."""+ child = FastMCP("dep-child")+ received_docket = []++ @child.tool(task=True)+ async def tool_with_docket(docket: CurrentDocket = CurrentDocket()) -> str: # type: ignore[invalid-type-form]+ received_docket.append(docket)+ return f"docket available: {docket is not None}"++ parent = FastMCP("dep-parent")+ parent.mount(child, prefix="child")++ async with Client(parent) as client:+ task = await client.call_tool("child_tool_with_docket", {}, task=True)+ result = await task.result()++ assert "docket available: True" in str(result)+ assert len(received_docket) == 1+ assert received_docket[0] is not None++ async def test_mounted_task_receives_server_dependency(self):+ """Mounted tool task receives CurrentFastMCP dependency."""+ child = FastMCP("server-dep-child")+ received_server = []++ @child.tool(task=True)+ async def tool_with_server(server: CurrentFastMCP = CurrentFastMCP()) -> str: # type: ignore[invalid-type-form]+ received_server.append(server)+ return f"server name: {server.name}"++ parent = FastMCP("server-dep-parent")+ parent.mount(child, prefix="child")++ async with Client(parent) as client:+ task = await client.call_tool("child_tool_with_server", {}, task=True)+ await task.result()++ # The server should be the child server since that's where the tool is defined+ assert len(received_server) == 1+ # Note: It might be parent or child depending on implementation+ assert received_server[0] is not None+++class TestMultipleMounts:+ """Test tasks with multiple mounted servers."""++ async def test_tasks_work_with_multiple_mounts(self):+ """Tasks work correctly with multiple mounted servers."""+ child1 = FastMCP("child1")+ child2 = FastMCP("child2")++ @child1.tool(task=True)+ async def add(a: int, b: int) -> int:+ return a + b++ @child2.tool(task=True)+ async def subtract(a: int, b: int) -> int:+ return a - b++ parent = FastMCP("multi-parent")+ parent.mount(child1, prefix="math1")+ parent.mount(child2, prefix="math2")++ async with Client(parent) as client:+ task1 = await client.call_tool("math1_add", {"a": 10, "b": 5}, task=True)+ task2 = await client.call_tool(+ "math2_subtract", {"a": 10, "b": 5}, task=True+ )++ result1 = await task1.result()+ result2 = await task2.result()++ assert result1.data == 15+ assert result2.data == 5+++class TestMountedTaskList:+ """Test task listing with mounted servers."""++ async def test_list_tasks_includes_mounted_tasks(self, parent_server):+ """Task list includes tasks from mounted server tools."""+ async with Client(parent_server) as client:+ # Create tasks on both parent and mounted tools+ parent_task = await client.call_tool("parent_tool", {"value": 1}, task=True)+ child_task = await client.call_tool(+ "child_multiply", {"a": 2, "b": 2}, task=True+ )++ # Wait for completion+ await parent_task.wait(timeout=2.0)+ await child_task.wait(timeout=2.0)++ # List all tasks - returns dict with "tasks" key+ tasks_response = await client.list_tasks()++ task_ids = [t["taskId"] for t in tasks_response["tasks"]]+ assert parent_task.task_id in task_ids+ assert child_task.task_id in task_ids+++class TestMountedTaskConfigModes:+ """Test TaskConfig mode enforcement for mounted tools."""++ @pytest.fixture+ def child_with_modes(self):+ """Create a child server with tools in all three TaskConfig modes."""+ mcp = FastMCP("child-modes", tasks=False)++ @mcp.tool(task=TaskConfig(mode="optional"))+ async def optional_tool() -> str:+ """Tool that supports both sync and task execution."""+ return "optional result"++ @mcp.tool(task=TaskConfig(mode="required"))+ async def required_tool() -> str:+ """Tool that requires task execution."""+ return "required result"++ @mcp.tool(task=TaskConfig(mode="forbidden"))+ async def forbidden_tool() -> str:+ """Tool that forbids task execution."""+ return "forbidden result"++ return mcp++ @pytest.fixture+ def parent_with_modes(self, child_with_modes):+ """Create a parent server with the child mounted."""+ parent = FastMCP("parent-modes")+ parent.mount(child_with_modes, prefix="child")+ return parent++ async def test_optional_mode_sync_through_mount(self, parent_with_modes):+ """Optional mode tool works without task through mount."""+ async with Client(parent_with_modes) as client:+ result = await client.call_tool("child_optional_tool", {})+ assert "optional result" in str(result)++ async def test_optional_mode_task_through_mount(self, parent_with_modes):+ """Optional mode tool works with task through mount."""+ async with Client(parent_with_modes) as client:+ task = await client.call_tool("child_optional_tool", {}, task=True)+ assert task is not None+ result = await task.result()+ assert result.data == "optional result"++ async def test_required_mode_with_task_through_mount(self, parent_with_modes):+ """Required mode tool succeeds with task through mount."""+ async with Client(parent_with_modes) as client:+ task = await client.call_tool("child_required_tool", {}, task=True)+ assert task is not None+ result = await task.result()+ assert result.data == "required result"++ async def test_required_mode_without_task_through_mount(self, parent_with_modes):+ """Required mode tool errors without task through mount."""+ from fastmcp.exceptions import ToolError++ async with Client(parent_with_modes) as client:+ with pytest.raises(ToolError) as exc_info:+ await client.call_tool("child_required_tool", {})++ assert "requires task-augmented execution" in str(exc_info.value)++ async def test_forbidden_mode_sync_through_mount(self, parent_with_modes):+ """Forbidden mode tool works without task through mount."""+ async with Client(parent_with_modes) as client:+ result = await client.call_tool("child_forbidden_tool", {})+ assert "forbidden result" in str(result)++ async def test_forbidden_mode_with_task_through_mount(self, parent_with_modes):+ """Forbidden mode tool degrades gracefully with task through mount."""+ async with Client(parent_with_modes) as client:+ task = await client.call_tool("child_forbidden_tool", {}, task=True)++ # Should return immediately (graceful degradation)+ assert task.returned_immediately++ result = await task.result()+ # Result is available but may indicate error or sync execution+ assert result is not Nonediff --git a/tests/server/tasks/test_task_proxy.py b/tests/server/tasks/test_task_proxy.pynew file mode 100644index 000000000..2d5da5b75--- /dev/null+++ b/tests/server/tasks/test_task_proxy.py@@ -0,0 +1,165 @@+"""+Tests for MCP SEP-1686 task protocol behavior through proxy servers.++Proxy servers explicitly forbid task-augmented execution. All proxy components+(tools, prompts, resources) have task_config.mode="forbidden".++Clients connecting through proxies can:+- Execute tools/prompts/resources normally (sync execution)+- NOT use task-augmented execution (task=True fails gracefully for tools,+ raises McpError for prompts/resources)+"""++import pytest+from mcp.shared.exceptions import McpError++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.client.transports import FastMCPTransport+from fastmcp.server.proxy import ProxyClient+++def backend_server() -> FastMCP:+ """Create a backend server with task-enabled components.++ The backend has tasks enabled, but the proxy should NOT forward+ task execution - it should treat all components as forbidden.+ """+ mcp = FastMCP("backend-server")++ @mcp.tool(task=True)+ async def add_numbers(a: int, b: int) -> int:+ """Add two numbers together."""+ return a + b++ @mcp.tool(task=False)+ async def sync_only_tool(message: str) -> str:+ """Tool that only supports synchronous execution."""+ return f"sync: {message}"++ @mcp.prompt(task=True)+ async def greeting_prompt(name: str) -> str:+ """A prompt that can execute as a task."""+ return f"Hello, {name}! Welcome to the system."++ @mcp.resource("data://info.txt", task=True)+ async def info_resource() -> str:+ """A resource that can be read as a task."""+ return "Important information from the backend"++ @mcp.resource("data://user/{user_id}.json", task=True)+ async def user_resource(user_id: str) -> str:+ """A resource template that can execute as a task."""+ return f'{{"id": "{user_id}", "name": "User {user_id}"}}'++ return mcp+++def proxy_server(backend_server: FastMCP) -> FastMCP:+ """Create a proxy server that forwards to the backend."""+ return FastMCP.as_proxy(ProxyClient(transport=FastMCPTransport(backend_server)))+++class TestProxyToolsSyncExecution:+ """Test that tools work normally through proxy (sync execution)."""++ async def test_tool_sync_execution_works(self, proxy_server: FastMCP):+ """Tool called without task=True works through proxy."""+ async with Client(proxy_server) as client:+ result = await client.call_tool("add_numbers", {"a": 5, "b": 3})+ assert "8" in str(result)++ async def test_sync_only_tool_works(self, proxy_server: FastMCP):+ """Sync-only tool works through proxy."""+ async with Client(proxy_server) as client:+ result = await client.call_tool("sync_only_tool", {"message": "test"})+ assert "sync: test" in str(result)+++class TestProxyToolsTaskForbidden:+ """Test that tools with task=True are forbidden through proxy."""++ async def test_tool_task_returns_error_immediately(self, proxy_server: FastMCP):+ """Tool called with task=True through proxy returns error immediately."""+ async with Client(proxy_server) as client:+ task = await client.call_tool("add_numbers", {"a": 5, "b": 3}, task=True)++ # Should return immediately (forbidden behavior)+ assert task.returned_immediately++ # Result should be an error+ result = await task.result()+ assert result.is_error++ async def test_sync_only_tool_task_returns_error_immediately(+ self, proxy_server: FastMCP+ ):+ """Sync-only tool with task=True also returns error immediately."""+ async with Client(proxy_server) as client:+ task = await client.call_tool(+ "sync_only_tool", {"message": "test"}, task=True+ )++ assert task.returned_immediately+ result = await task.result()+ assert result.is_error+++class TestProxyPromptsSyncExecution:+ """Test that prompts work normally through proxy (sync execution)."""++ async def test_prompt_sync_execution_works(self, proxy_server: FastMCP):+ """Prompt called without task=True works through proxy."""+ async with Client(proxy_server) as client:+ result = await client.get_prompt("greeting_prompt", {"name": "Alice"})+ assert "Hello, Alice!" in result.messages[0].content.text # type: ignore[attr-defined]+++class TestProxyPromptsTaskForbidden:+ """Test that prompts with task=True are forbidden through proxy."""++ async def test_prompt_task_raises_mcp_error(self, proxy_server: FastMCP):+ """Prompt called with task=True through proxy raises McpError."""+ async with Client(proxy_server) as client:+ with pytest.raises(McpError) as exc_info:+ await client.get_prompt("greeting_prompt", {"name": "Alice"}, task=True)++ assert "does not support task-augmented execution" in str(exc_info.value)+++class TestProxyResourcesSyncExecution:+ """Test that resources work normally through proxy (sync execution)."""++ async def test_resource_sync_execution_works(self, proxy_server: FastMCP):+ """Resource read without task=True works through proxy."""+ async with Client(proxy_server) as client:+ result = await client.read_resource("data://info.txt")+ assert "Important information from the backend" in result[0].text # type: ignore[attr-defined]++ async def test_resource_template_sync_execution_works(self, proxy_server: FastMCP):+ """Resource template without task=True works through proxy."""+ async with Client(proxy_server) as client:+ result = await client.read_resource("data://user/42.json")+ assert '"id": "42"' in result[0].text # type: ignore[attr-defined]+++class TestProxyResourcesTaskForbidden:+ """Test that resources with task=True are forbidden through proxy."""++ async def test_resource_task_raises_mcp_error(self, proxy_server: FastMCP):+ """Resource read with task=True through proxy raises McpError."""+ async with Client(proxy_server) as client:+ with pytest.raises(McpError) as exc_info:+ await client.read_resource("data://info.txt", task=True)++ assert "does not support task-augmented execution" in str(exc_info.value)++ async def test_resource_template_task_raises_mcp_error(self, proxy_server: FastMCP):+ """Resource template with task=True through proxy raises McpError."""+ async with Client(proxy_server) as client:+ with pytest.raises(McpError) as exc_info:+ await client.read_resource("data://user/42.json", task=True)++ assert "does not support task-augmented execution" in str(exc_info.value)diff --git a/uv.lock b/uv.lockindex e6f97d86c..e3e4da4a1 100644--- a/uv.lock+++ b/uv.lock@@ -729,7 +729,7 @@ requires-dist = [{ name = "platformdirs", specifier = ">=4.0.0" },{ name = "py-key-value-aio", extras = ["disk", "keyring", "memory"], specifier = ">=0.3.0,<0.4.0" },{ name = "pydantic", extras = ["email"], specifier = ">=2.11.7" },- { name = "pydocket", specifier = ">=0.14.0" },+ { name = "pydocket", specifier = ">=0.15.2" },{ name = "pyperclip", specifier = ">=1.9.0" },{ name = "python-dotenv", specifier = ">=1.1.0" },{ name = "rich", specifier = ">=13.9.4" },@@ -1737,7 +1737,7 @@ wheels = [[[package]]name = "pydocket"-version = "0.15.0"+version = "0.15.2"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "cloudpickle" },@@ -1753,9 +1753,9 @@ dependencies = [{ name = "typer" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/70/74/8040c44785d4b004cb314146ae33fafd0977ce2c64af9183e48e9caac534/pydocket-0.15.0.tar.gz", hash = "sha256:2c83dd3d979d76169bf485bdc4087be44a63bf1cc09b3dad0725d67d993add42", size = 265328, upload-time = "2025-11-25T21:23:37.067Z" }+sdist = { url = "https://files.pythonhosted.org/packages/9f/a8/7786b0d528823fda886370fb58222ace079afffc9b28bbbc22e8b9e668d6/pydocket-0.15.2.tar.gz", hash = "sha256:c4d3c8d221251eb57c98c0e69aa60adf1eba163afcfeded01c8f32b2e4aaae37", size = 269495, upload-time = "2025-12-08T15:53:22.766Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/4f/63/1cee9989cdce573c53f64bc142cd75c899c3830e7feb7126510d620d1fa6/pydocket-0.15.0-py3-none-any.whl", hash = "sha256:701cf063f2e32a3e5b5bd5b07b4db9698a705367e4f8b9b8143632ac02807f20", size = 56803, upload-time = "2025-11-25T21:23:35.606Z" },+ { url = "https://files.pythonhosted.org/packages/82/22/d449dd17453a3b7e0168d9045f2f609c4a12a3288277f9358e580721ae9d/pydocket-0.15.2-py3-none-any.whl", hash = "sha256:8f8414315bdb2db588a09bd5ea399573052ff2cc185743e5a003db3e91f1cefc", size = 57292, upload-time = "2025-12-08T15:53:21.184Z" },][[package]]