π The fast, Pythonic way to build MCP servers and clients.
Bound task drive by one deadline; version-aware tasking; serialize cancel
Jeremiah Lowinf62717008890
diff --git a/fastmcp_tasks/fastmcp_tasks/client.py b/fastmcp_tasks/fastmcp_tasks/client.pyindex 34012b3e7..006104e02 100644--- a/fastmcp_tasks/fastmcp_tasks/client.py+++ b/fastmcp_tasks/fastmcp_tasks/client.py@@ -200,20 +200,37 @@ async def _drive_to_terminal(session: ClientSession,task_id: str,elicitation_callback: ElicitationFnT | None,- read_timeout_seconds: float | None = None,+ timeout_seconds: float | None = None,) -> ClientGetTaskResult:"""Poll `tasks/get` until the task reaches a terminal state.`working` sleeps and polls again; `input_required` answers the outstandingrequests through the elicitation handler and re-enters; a terminal state(completed / failed / cancelled) is returned. Shared by the transparent- resolver and `ToolTask.result()`. `read_timeout_seconds`, when set, bounds- each `tasks/get`/`tasks/update` request so a stalled poll can't outlast the- per-call timeout the synchronous path would have honored.+ resolver and `ToolTask.result()`.++ `timeout_seconds`, when set, is one deadline for the *entire* drive β not a+ per-request timeout. The synchronous path aborts a `tools/call` once total+ execution exceeds the call's timeout, so the tasked path must too: each poll+ and sleep is bounded by the time remaining, and a `TimeoutError` is raised+ once the deadline passes. `None` drives to completion unbounded (the default+ for `ToolTask.result()`, whose caller bounds waiting via `wait(timeout=...)`)."""+ loop = asyncio.get_event_loop()+ deadline = None if timeout_seconds is None else loop.time() + timeout_secondsbackoff = MIN_POLL_INTERVAL++ def remaining() -> float | None:+ return None if deadline is None else deadline - loop.time()+while True:- current = await _send_get(session, task_id, read_timeout_seconds)+ budget = remaining()+ if budget is not None and budget <= 0:+ raise TimeoutError(+ f"Task {task_id} did not finish within {timeout_seconds}s"+ )++ current = await _send_get(session, task_id, budget)if current.status in _TERMINAL_STATES:return currentif current.status == "input_required":@@ -222,12 +239,15 @@ async def _drive_to_terminal(task_id,current.input_requests or {},elicitation_callback,- read_timeout_seconds,+ remaining(),)backoff = MIN_POLL_INTERVALcontinue# workingdelay, backoff = _next_poll_delay(current.poll_interval_ms, backoff)+ budget = remaining()+ if budget is not None:+ delay = min(delay, budget)await asyncio.sleep(delay)diff --git a/fastmcp_tasks/fastmcp_tasks/extension.py b/fastmcp_tasks/fastmcp_tasks/extension.pyindex aff882736..bc34daaa8 100644--- a/fastmcp_tasks/fastmcp_tasks/extension.py+++ b/fastmcp_tasks/fastmcp_tasks/extension.py@@ -35,6 +35,7 @@ from mcp.shared.exceptions import MCPErrorfrom mcp_types.version import MODERN_PROTOCOL_VERSIONSfrom fastmcp.exceptions import NotFoundError+from fastmcp.server.dependencies import extract_version_specfrom fastmcp.server.extensions import (MethodBinding,ServerExtension,@@ -42,6 +43,7 @@ from fastmcp.server.extensions import ()from fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.tasks import TASKS_EXTENSION_ID+from fastmcp.utilities.versions import VersionSpecfrom fastmcp_tasks.creation import create_taskfrom fastmcp_tasks.handlers import tasks_cancel, tasks_get, tasks_updatefrom fastmcp_tasks.models import (@@ -185,8 +187,14 @@ class TasksExtension(ServerExtension):opt in), ``optional`` tasks only when the client opted in, ``forbidden``never tasks. A non-task call passes straight through to the tool body."""+ # Resolve the same version core would dispatch: a versioned tools/call+ # carries its VersionSpec in the request _meta, so omitting it here would+ # task the highest version even when the client targeted an older one+ # (which may differ in task mode or implementation).+ version_str = extract_version_spec(params.meta)+ version = VersionSpec(eq=version_str) if version_str else Nonetry:- tool = await context.fastmcp.get_tool(params.name)+ tool = await context.fastmcp.get_tool(params.name, version)except NotFoundError:tool = Noneif tool is None or not tool.task_config.supports_tasks():diff --git a/fastmcp_tasks/fastmcp_tasks/handlers.py b/fastmcp_tasks/fastmcp_tasks/handlers.pyindex 61006937c..a4f7b0800 100644--- a/fastmcp_tasks/fastmcp_tasks/handlers.py+++ b/fastmcp_tasks/fastmcp_tasks/handlers.py@@ -36,6 +36,7 @@ from fastmcp_tasks.context import get_task_scopefrom fastmcp_tasks.creation import enqueue_task_leg, registered_component_for_keyfrom fastmcp_tasks.input_store import (acquire_update_lock,+ acquire_update_lock_blocking,clear_outstanding,is_cancelled,load_current_leg,@@ -370,17 +371,34 @@ async def tasks_cancel(server: FastMCP, task_id: str) -> CancelTaskResult:on it a no-op. The current leg's outstanding requests are cleared so aracing ``tasks/update`` naming them finds nothing, and the runningexecution is still cancelled cooperatively for the ``working`` case.++ Cancellation runs under the per-task update lock and re-resolves the leg+ once held, so it never cancels a stale leg while ``tasks/update`` is+ concurrently enqueuing the next one: whichever wins the lock runs to+ completion before the other, and the update rechecks the marker under the+ same lock. If the lock is wedged past its timeout, cancel proceeds+ best-effort rather than hang."""docket = server._docketif docket is None:raise _task_not_found(task_id)task_scope = get_task_scope()- execution, _base_task_key, leg_number, _created_at, _poll = await _lookup_task(- docket, task_scope, task_id- )- ttl_seconds = int(docket.execution_ttl.total_seconds())- await mark_cancelled(docket, task_scope, task_id, ttl_seconds)- await clear_outstanding(docket, task_scope, task_id, leg_number)- await docket.cancel(execution.key)+ # Validate the task exists within scope before taking the lock.+ await _lookup_task(docket, task_scope, task_id)++ got_lock = await acquire_update_lock_blocking(docket, task_scope, task_id)+ try:+ # Re-resolve under the lock: an update that ran first has advanced the+ # current leg, so this cancels the leg that is actually live now.+ execution, _base_task_key, leg_number, _created_at, _poll = await _lookup_task(+ docket, task_scope, task_id+ )+ ttl_seconds = int(docket.execution_ttl.total_seconds())+ await mark_cancelled(docket, task_scope, task_id, ttl_seconds)+ await clear_outstanding(docket, task_scope, task_id, leg_number)+ await docket.cancel(execution.key)+ finally:+ if got_lock:+ await release_update_lock(docket, task_scope, task_id)return CancelTaskResult()diff --git a/fastmcp_tasks/fastmcp_tasks/input_store.py b/fastmcp_tasks/fastmcp_tasks/input_store.pyindex 92b56d9bf..edd46ef64 100644--- a/fastmcp_tasks/fastmcp_tasks/input_store.py+++ b/fastmcp_tasks/fastmcp_tasks/input_store.py@@ -26,6 +26,7 @@ translated `input_responses`.from __future__ import annotations+import asyncioimport jsonimport loggingimport secrets@@ -416,6 +417,32 @@ async def acquire_update_lock(return bool(got)+async def acquire_update_lock_blocking(+ docket: Docket,+ task_scope: str | None,+ task_id: str,+ *,+ timeout: float = 5.0,+ poll: float = 0.02,+) -> bool:+ """Wait for the per-task update lock, up to ``timeout`` seconds.++ ``tasks/cancel`` uses this to serialize with an in-flight ``tasks/update``:+ it must not cancel a stale leg while an update concurrently enqueues the+ next one. A single update is fast (milliseconds), so contention is brief;+ returns False if the lock is still held at the deadline (a wedged holder),+ letting the caller proceed best-effort rather than hang.+ """+ loop = asyncio.get_event_loop()+ deadline = loop.time() + timeout+ while True:+ if await acquire_update_lock(docket, task_scope, task_id):+ return True+ if loop.time() >= deadline:+ return False+ await asyncio.sleep(poll)++async def release_update_lock(docket: Docket, task_scope: str | None, task_id: str) -> None:diff --git a/tests/tasks/client/test_transparent_tasks.py b/tests/tasks/client/test_transparent_tasks.pyindex 348ff0e76..7af25f10f 100644--- a/tests/tasks/client/test_transparent_tasks.py+++ b/tests/tasks/client/test_transparent_tasks.py@@ -14,6 +14,7 @@ from dataclasses import dataclassimport mcp_typesimport pytest+from mcp.shared.exceptions import MCPErrorfrom fastmcp import Context, FastMCPfrom fastmcp.client import Client@@ -35,9 +36,26 @@ def task_server() -> FastMCP:async def boom() -> str:raise ValueError("kaboom")+ @mcp.tool(task=True)+ async def slow() -> str:+ await asyncio.sleep(5)+ return "done"+return mcp+async def test_call_tool_timeout_bounds_total_task_drive(task_server: FastMCP):+ """A per-call timeout bounds the whole tasked drive, not just one poll.++ The tool runs far longer than the timeout while each individual poll answers+ instantly; the transparent path must still abort once total execution passes+ the deadline, matching the synchronous `tools/call` timeout contract.+ """+ async with Client(task_server, mode="auto") as client:+ with pytest.raises((TimeoutError, MCPError)):+ await client.call_tool("slow", {}, timeout=0.3)++async def test_call_tool_transparently_completes_a_task(task_server: FastMCP):"""call_tool returns the tool's real result; the caller never sees a task."""async with Client(task_server, mode="auto") as client:diff --git a/tests/tasks/server/test_task_config.py b/tests/tasks/server/test_task_config.pyindex dc214acb5..bfd2533a8 100644--- a/tests/tasks/server/test_task_config.py+++ b/tests/tasks/server/test_task_config.py@@ -21,6 +21,7 @@ from mcp_types import ToolExecutionfrom fastmcp import FastMCPfrom fastmcp.tools.base import Toolfrom fastmcp.utilities.tasks import TaskConfig+from fastmcp.utilities.versions import VersionSpecfrom fastmcp_tasks import TasksExtensionfrom tests.tasks.task_helpers import (_opted_in_request,@@ -37,6 +38,32 @@ async def _opted_in_call(server: FastMCP, name: str, arguments: dict | None = Noreturn await server.call_tool(name, arguments or {})+async def test_interceptor_tasks_the_requested_version_not_the_highest():+ """A versioned tools/call tasks the version the caller asked for.++ Two versions share a name but differ in task mode: v1 is task-forbidden,+ v2 is task-optional. A call targeting v1 (with the tasks opt-in) must run v1+ synchronously β resolving the highest version instead would wrongly task v2.+ """+ mcp = FastMCP("versioned-tasks")+ mcp.add_extension(TasksExtension())++ @mcp.tool(name="calc", version="1.0")+ async def calc_v1() -> str:+ return "v1-sync"++ @mcp.tool(name="calc", version="2.0", task=True)+ async def calc_v2() -> str:+ return "v2"++ async with running_task_server(mcp):+ with auth_scope(None), _opted_in_request("calc", {}, None):+ result = await mcp.call_tool("calc", {}, version=VersionSpec(eq="1.0"))++ assert not isinstance(result, CreateTaskResult)+ assert result.structured_content == {"result": "v1-sync"}++class TestTaskConfigNormalization:"""Test that boolean task values normalize correctly to TaskConfig."""