From e34c475ec892f6da4f976fabce8421e9dc73cfeb Mon Sep 17 00:00:00 2001 From: alessandromuresan Date: Tue, 10 Nov 2026 09:27:10 +0200 Subject: [PATCH 1/4] feat(platform): add MCP Tasks extension support to McpService A long-running tools/call on a UiPath MCP server can now return a durable task handle instead of holding the request open. McpService gains call_tool / get_task / cancel_task / wait_for_task / call_tool_and_wait (sync + async): they declare the io.modelcontextprotocol/tasks extension per request over the stateless 2026-07-28 protocol revision - the only revision the extension is served on - and poll tasks/get at the server-suggested cadence until terminal. call_tool_and_wait makes an hour-long process invocation look synchronous to coded agents, and gives the langchain runtime one shared implementation to wire its MCP tool layer to. The official mcp SDK cannot express this wire shape (1.x models the older 2025-11-25 task flavor, 2.x dropped tasks), so the handful of shapes are local pydantic models. --- .../uipath/platform/orchestrator/__init__.py | 14 + .../platform/orchestrator/_mcp_service.py | 461 +++++++++++++++++- .../uipath/platform/orchestrator/mcp_tasks.py | 116 +++++ .../tests/services/test_mcp_tasks.py | 313 ++++++++++++ 4 files changed, 903 insertions(+), 1 deletion(-) create mode 100644 packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py create mode 100644 packages/uipath-platform/tests/services/test_mcp_tasks.py diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py b/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py index 79d6dde30..9275569aa 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py @@ -22,6 +22,14 @@ from .buckets import Bucket, BucketFile from .job import Job, JobErrorInfo, JobState from .mcp import McpServer, McpServerStatus, McpServerType +from .mcp_tasks import ( + McpTask, + McpTaskCancelledError, + McpTaskFailedError, + McpTaskStatus, + McpToolCallError, + McpToolCallOutcome, +) from .processes import Process from .queues import ( CommitType, @@ -61,4 +69,10 @@ "McpServer", "McpServerStatus", "McpServerType", + "McpTask", + "McpTaskCancelledError", + "McpTaskFailedError", + "McpTaskStatus", + "McpToolCallError", + "McpToolCallOutcome", ] diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py index e2a9f13c3..34c60b5eb 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py @@ -1,6 +1,11 @@ -from typing import List +import asyncio +import base64 +import json +import time +from typing import Any, List, Optional from urllib.parse import quote +import httpx from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -12,6 +17,19 @@ from ..common._resource_identifier import resolve_retrieve_identifier from ._folder_service import FolderService from .mcp import McpServer +from .mcp_tasks import ( + MCP_TASK_RESULT_TYPE, + MCP_TASKS_EXTENSION_ID, + MCP_TASKS_PROTOCOL_VERSION, + McpTask, + McpTaskCancelledError, + McpTaskFailedError, + McpTaskStatus, + McpToolCallError, + McpToolCallOutcome, +) + +_DEFAULT_POLL_INTERVAL_MS = 5000 class McpService(FolderContext, BaseService): @@ -245,3 +263,444 @@ def _retrieve_spec( **header_folder(folder_key, None), }, ) + + # ------------------------------------------------------------------ + # MCP Tasks extension (io.modelcontextprotocol/tasks) + # + # A long-running tools/call on a UiPath MCP server can return a durable + # task handle instead of holding the request open; the handle is polled + # via tasks/get until terminal. These methods speak the stateless + # 2026-07-28 per-request protocol revision directly — the only revision + # the extension is served on — so no initialize handshake or session is + # involved. + # ------------------------------------------------------------------ + + @traced(name="mcp_call_tool", run_type="uipath") + def call_tool( + self, + slug: str, + tool_name: str, + arguments: Optional[dict[str, Any]] = None, + *, + folder_path: str | None = None, + ) -> McpToolCallOutcome: + """Call a tool on an MCP server, accepting a task handle for long-running calls. + + Declares the MCP Tasks extension on the request; the server decides + per call whether to answer synchronously or with a durable task. + + Args: + slug (str): The MCP server's slug or display name. + tool_name (str): The MCP tool to invoke. + arguments (Optional[dict[str, Any]]): The tool arguments. + folder_path (Optional[str]): The folder the server lives in. + + Returns: + McpToolCallOutcome: Either the plain CallToolResult (``result``) + or the durable handle to poll (``task``). + + Raises: + McpToolCallError: If the server answers with a JSON-RPC error. + """ + server_url = self._resolve_mcp_url(slug, folder_path=folder_path) + result = self._send_mcp( + server_url, + "tools/call", + {"name": tool_name, "arguments": arguments or {}}, + routing_name=tool_name, + ) + return self._outcome_from_result(result, server_url) + + @traced(name="mcp_call_tool", run_type="uipath") + async def call_tool_async( + self, + slug: str, + tool_name: str, + arguments: Optional[dict[str, Any]] = None, + *, + folder_path: str | None = None, + ) -> McpToolCallOutcome: + """Asynchronously call a tool on an MCP server, accepting a task handle. + + Args: + slug (str): The MCP server's slug or display name. + tool_name (str): The MCP tool to invoke. + arguments (Optional[dict[str, Any]]): The tool arguments. + folder_path (Optional[str]): The folder the server lives in. + + Returns: + McpToolCallOutcome: Either the plain CallToolResult (``result``) + or the durable handle to poll (``task``). + + Raises: + McpToolCallError: If the server answers with a JSON-RPC error. + """ + server_url = await self._resolve_mcp_url_async(slug, folder_path=folder_path) + result = await self._send_mcp_async( + server_url, + "tools/call", + {"name": tool_name, "arguments": arguments or {}}, + routing_name=tool_name, + ) + return self._outcome_from_result(result, server_url) + + @traced(name="mcp_get_task", run_type="uipath") + def get_task(self, task: McpTask) -> McpTask: + """Poll the current state of an MCP task once. + + Args: + task (McpTask): A handle returned by ``call_tool`` (or an earlier poll). + + Returns: + McpTask: The fresh task snapshot; ``result`` is set once completed. + + Raises: + McpToolCallError: If the task id is unknown or expired. + """ + server_url = self._require_server_url(task) + result = self._send_mcp(server_url, "tasks/get", {"taskId": task.task_id}) + return self._task_from_result(result, server_url) + + @traced(name="mcp_get_task", run_type="uipath") + async def get_task_async(self, task: McpTask) -> McpTask: + """Asynchronously poll the current state of an MCP task once. + + Args: + task (McpTask): A handle returned by ``call_tool_async`` (or an earlier poll). + + Returns: + McpTask: The fresh task snapshot; ``result`` is set once completed. + + Raises: + McpToolCallError: If the task id is unknown or expired. + """ + server_url = self._require_server_url(task) + result = await self._send_mcp_async( + server_url, "tasks/get", {"taskId": task.task_id} + ) + return self._task_from_result(result, server_url) + + @traced(name="mcp_cancel_task", run_type="uipath") + def cancel_task(self, task: McpTask) -> None: + """Signal cancellation of an MCP task. + + Cancellation is cooperative: the server acknowledges the intent and + the next poll reports the state the underlying job actually reached. + + Args: + task (McpTask): The task to cancel. + """ + server_url = self._require_server_url(task) + self._send_mcp(server_url, "tasks/cancel", {"taskId": task.task_id}) + + @traced(name="mcp_cancel_task", run_type="uipath") + async def cancel_task_async(self, task: McpTask) -> None: + """Asynchronously signal cancellation of an MCP task. + + Args: + task (McpTask): The task to cancel. + """ + server_url = self._require_server_url(task) + await self._send_mcp_async(server_url, "tasks/cancel", {"taskId": task.task_id}) + + @traced(name="mcp_wait_for_task", run_type="uipath") + def wait_for_task( + self, + task: McpTask, + *, + timeout: Optional[float] = None, + ) -> dict[str, Any]: + """Poll an MCP task until terminal, honoring the server's poll interval. + + Args: + task (McpTask): The handle to wait on. + timeout (Optional[float]): Seconds to wait before raising + ``TimeoutError``. The task keeps running server-side on + timeout; call ``cancel_task`` if that is not wanted. + + Returns: + dict[str, Any]: The completed task's CallToolResult object. + + Raises: + McpTaskFailedError: If the task reaches ``failed``. + McpTaskCancelledError: If the task reaches ``cancelled``. + TimeoutError: If ``timeout`` elapses first. + """ + deadline = None if timeout is None else time.monotonic() + timeout + snapshot = task + + while True: + terminal = self._terminal_result(snapshot) + if terminal is not None: + return terminal + + time.sleep(self._poll_delay_seconds(snapshot, deadline, timeout)) + snapshot = self.get_task(snapshot) + + @traced(name="mcp_wait_for_task", run_type="uipath") + async def wait_for_task_async( + self, + task: McpTask, + *, + timeout: Optional[float] = None, + ) -> dict[str, Any]: + """Asynchronously poll an MCP task until terminal. + + Args: + task (McpTask): The handle to wait on. + timeout (Optional[float]): Seconds to wait before raising + ``TimeoutError``. The task keeps running server-side on + timeout; call ``cancel_task_async`` if that is not wanted. + + Returns: + dict[str, Any]: The completed task's CallToolResult object. + + Raises: + McpTaskFailedError: If the task reaches ``failed``. + McpTaskCancelledError: If the task reaches ``cancelled``. + TimeoutError: If ``timeout`` elapses first. + """ + deadline = None if timeout is None else time.monotonic() + timeout + snapshot = task + + while True: + terminal = self._terminal_result(snapshot) + if terminal is not None: + return terminal + + await asyncio.sleep(self._poll_delay_seconds(snapshot, deadline, timeout)) + snapshot = await self.get_task_async(snapshot) + + @traced(name="mcp_call_tool_and_wait", run_type="uipath") + def call_tool_and_wait( + self, + slug: str, + tool_name: str, + arguments: Optional[dict[str, Any]] = None, + *, + folder_path: str | None = None, + timeout: Optional[float] = None, + ) -> dict[str, Any]: + """Call an MCP tool and always return the final result, task or not. + + Args: + slug (str): The MCP server's slug or display name. + tool_name (str): The MCP tool to invoke. + arguments (Optional[dict[str, Any]]): The tool arguments. + folder_path (Optional[str]): The folder the server lives in. + timeout (Optional[float]): Seconds to wait for a task to finish. + + Returns: + dict[str, Any]: The CallToolResult object. + + Examples: + ```python + from uipath import UiPath + + sdk = UiPath() + + result = sdk.mcp.call_tool_and_wait( + "my-server", "invoke-long-process", {"input": "..."}, timeout=3600 + ) + print(result["content"][0]["text"]) + ``` + """ + outcome = self.call_tool(slug, tool_name, arguments, folder_path=folder_path) + if outcome.task is None: + return outcome.result or {} + return self.wait_for_task(outcome.task, timeout=timeout) + + @traced(name="mcp_call_tool_and_wait", run_type="uipath") + async def call_tool_and_wait_async( + self, + slug: str, + tool_name: str, + arguments: Optional[dict[str, Any]] = None, + *, + folder_path: str | None = None, + timeout: Optional[float] = None, + ) -> dict[str, Any]: + """Asynchronously call an MCP tool and always return the final result. + + Args: + slug (str): The MCP server's slug or display name. + tool_name (str): The MCP tool to invoke. + arguments (Optional[dict[str, Any]]): The tool arguments. + folder_path (Optional[str]): The folder the server lives in. + timeout (Optional[float]): Seconds to wait for a task to finish. + + Returns: + dict[str, Any]: The CallToolResult object. + """ + outcome = await self.call_tool_async( + slug, tool_name, arguments, folder_path=folder_path + ) + if outcome.task is None: + return outcome.result or {} + return await self.wait_for_task_async(outcome.task, timeout=timeout) + + def _resolve_mcp_url(self, slug: str, *, folder_path: str | None) -> str: + server = self.retrieve(slug, folder_path=folder_path) + if not server.mcp_url: + raise McpToolCallError(0, f"MCP server '{slug}' exposes no MCP URL.") + return server.mcp_url + + async def _resolve_mcp_url_async( + self, slug: str, *, folder_path: str | None + ) -> str: + server = await self.retrieve_async(slug, folder_path=folder_path) + if not server.mcp_url: + raise McpToolCallError(0, f"MCP server '{slug}' exposes no MCP URL.") + return server.mcp_url + + @staticmethod + def _require_server_url(task: McpTask) -> str: + if not task.server_url: + raise McpToolCallError( + 0, + "The task carries no server URL; use a handle returned by call_tool.", + ) + return task.server_url + + def _outcome_from_result( + self, result: dict[str, Any], server_url: str + ) -> McpToolCallOutcome: + if result.get("resultType") == MCP_TASK_RESULT_TYPE: + return McpToolCallOutcome(task=self._task_from_result(result, server_url)) + return McpToolCallOutcome(result=result) + + @staticmethod + def _task_from_result(result: dict[str, Any], server_url: str) -> McpTask: + task = McpTask.model_validate(result) + task.server_url = server_url + return task + + def _terminal_result(self, snapshot: McpTask) -> Optional[dict[str, Any]]: + """The completed result, None while running, raising on failure states.""" + if snapshot.status == McpTaskStatus.COMPLETED: + return snapshot.result or {} + if snapshot.status == McpTaskStatus.FAILED: + raise McpTaskFailedError(snapshot) + if snapshot.status == McpTaskStatus.CANCELLED: + raise McpTaskCancelledError(snapshot) + return None + + @staticmethod + def _poll_delay_seconds( + snapshot: McpTask, deadline: Optional[float], timeout: Optional[float] + ) -> float: + delay = (snapshot.poll_interval_ms or _DEFAULT_POLL_INTERVAL_MS) / 1000.0 + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError( + f"MCP task {snapshot.task_id} did not finish within {timeout} seconds." + ) + delay = min(delay, remaining) + return delay + + def _mcp_rpc_envelope( + self, method: str, params: dict[str, Any], routing_name: Optional[str] + ) -> tuple[dict[str, Any], dict[str, str]]: + self._mcp_request_id = getattr(self, "_mcp_request_id", 0) + 1 + params = { + **params, + "_meta": { + "io.modelcontextprotocol/protocolVersion": MCP_TASKS_PROTOCOL_VERSION, + "io.modelcontextprotocol/clientInfo": { + "name": "UiPath.Python.Sdk", + "version": "1.0.0", + }, + "io.modelcontextprotocol/clientCapabilities": { + "extensions": {MCP_TASKS_EXTENSION_ID: {}}, + }, + }, + } + body = { + "jsonrpc": "2.0", + "id": self._mcp_request_id, + "method": method, + "params": params, + } + # The current protocol mirrors the method (and, for tools/call, the + # Base64 routing name) into headers so gateways can route without + # reading the body. + headers = { + "MCP-Protocol-Version": MCP_TASKS_PROTOCOL_VERSION, + "Mcp-Method": method, + "Accept": "application/json, text/event-stream", + } + if routing_name is not None: + headers["Mcp-Name"] = base64.b64encode(routing_name.encode("utf-8")).decode( + "ascii" + ) + return body, headers + + def _send_mcp( + self, + server_url: str, + method: str, + params: dict[str, Any], + routing_name: Optional[str] = None, + ) -> dict[str, Any]: + body, headers = self._mcp_rpc_envelope(method, params, routing_name) + response = self.request("POST", server_url, json=body, headers=headers) + return self._parse_mcp_envelope(response, method) + + async def _send_mcp_async( + self, + server_url: str, + method: str, + params: dict[str, Any], + routing_name: Optional[str] = None, + ) -> dict[str, Any]: + body, headers = self._mcp_rpc_envelope(method, params, routing_name) + response = await self.request_async( + "POST", server_url, json=body, headers=headers + ) + return self._parse_mcp_envelope(response, method) + + @staticmethod + def _parse_mcp_envelope(response: httpx.Response, method: str) -> dict[str, Any]: + """The JSON-RPC envelope, whether framed as plain JSON or one SSE event.""" + text = response.text + if "text/event-stream" in response.headers.get("content-type", ""): + data_lines: list[str] = [] + for line in text.replace("\r\n", "\n").split("\n"): + if not line and data_lines: + break + if line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if not data_lines: + raise McpToolCallError( + 0, f"The MCP SSE response to '{method}' had no data event." + ) + text = "\n".join(data_lines) + + try: + envelope = json.loads(text) + except json.JSONDecodeError: + raise McpToolCallError( + 0, f"The MCP response to '{method}' was not JSON." + ) from None + + if not isinstance(envelope, dict): + raise McpToolCallError( + 0, f"The MCP response to '{method}' was not an envelope." + ) + + if "error" in envelope: + error = envelope["error"] or {} + raise McpToolCallError( + code=error.get("code", 0), + message=error.get("message", "Unknown MCP error"), + data=error.get("data"), + ) + + result = envelope.get("result") + if not isinstance(result, dict): + raise McpToolCallError( + 0, f"The MCP response to '{method}' carried no result object." + ) + + return result diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py b/packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py new file mode 100644 index 000000000..9fbe39923 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py @@ -0,0 +1,116 @@ +"""Models for the MCP Tasks extension on UiPath MCP servers. + +The Tasks extension (``io.modelcontextprotocol/tasks``) lets a long-running +``tools/call`` — typically a UiPath process invocation — return a durable task +handle instead of holding the request open; the caller then polls ``tasks/get`` +until the task is terminal. UiPath MCP servers serve the extension on the +2026-07-28 per-request-metadata protocol revision, which is stateless: no +initialize handshake, no session, every request self-contained. +""" + +from enum import Enum +from typing import Any, Optional + +from pydantic import BaseModel, ConfigDict, Field +from pydantic.alias_generators import to_camel + +MCP_TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks" +MCP_TASKS_PROTOCOL_VERSION = "2026-07-28" +MCP_TASK_RESULT_TYPE = "task" + + +class McpTaskStatus(str, Enum): + """Task lifecycle states; the last three are terminal.""" + + WORKING = "working" + INPUT_REQUIRED = "input_required" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + + @property + def is_terminal(self) -> bool: + """Whether the status is final and can no longer change.""" + return self in ( + McpTaskStatus.COMPLETED, + McpTaskStatus.FAILED, + McpTaskStatus.CANCELLED, + ) + + +class McpTask(BaseModel): + """A durable task handle over a long-running MCP tool call. + + Returned by ``tools/call`` when the server decides the call is + long-running, and by every ``tasks/get`` poll. Once terminal, ``result`` + carries what the original call would have returned synchronously + (a CallToolResult object), or ``error`` carries the JSON-RPC error. + """ + + model_config = ConfigDict( + alias_generator=to_camel, + populate_by_name=True, + extra="allow", + ) + + task_id: str + status: McpTaskStatus + status_message: Optional[str] = None + created_at: Optional[str] = None + last_updated_at: Optional[str] = None + ttl_ms: Optional[int] = None + poll_interval_ms: Optional[int] = None + result: Optional[dict[str, Any]] = None + error: Optional[dict[str, Any]] = None + + # Client-side only: the MCP endpoint this task was minted by, so follow-up + # tasks/get, cancel, and wait calls know where to go. Never serialized. + server_url: Optional[str] = Field(default=None, exclude=True) + + +class McpToolCallOutcome(BaseModel): + """Either shape a task-capable ``tools/call`` can answer. + + ``result`` holds the plain CallToolResult object when the server answered + synchronously; ``task`` holds the durable handle when it did not. Exactly + one is set. + """ + + model_config = ConfigDict(extra="forbid") + + result: Optional[dict[str, Any]] = None + task: Optional[McpTask] = None + + @property + def is_task(self) -> bool: + """Whether the server answered with a task handle instead of a result.""" + return self.task is not None + + +class McpToolCallError(Exception): + """A JSON-RPC error answered an MCP request.""" + + def __init__(self, code: int, message: str, data: Any = None) -> None: + """Initialize with the JSON-RPC error code, message, and optional data.""" + super().__init__(f"MCP error {code}: {message}") + self.code = code + self.message = message + self.data = data + + +class McpTaskFailedError(Exception): + """The task reached ``failed``; carries the server's JSON-RPC error object.""" + + def __init__(self, task: McpTask) -> None: + """Initialize with the terminal task snapshot.""" + super().__init__(f"MCP task {task.task_id} failed: {task.error}") + self.task = task + + +class McpTaskCancelledError(Exception): + """The task reached ``cancelled`` before producing a result.""" + + def __init__(self, task: McpTask) -> None: + """Initialize with the terminal task snapshot.""" + super().__init__(f"MCP task {task.task_id} was cancelled.") + self.task = task diff --git a/packages/uipath-platform/tests/services/test_mcp_tasks.py b/packages/uipath-platform/tests/services/test_mcp_tasks.py new file mode 100644 index 000000000..859ae3983 --- /dev/null +++ b/packages/uipath-platform/tests/services/test_mcp_tasks.py @@ -0,0 +1,313 @@ +import base64 +import json +from typing import Any, Optional + +import pytest +from pytest_httpx import HTTPXMock + +from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.orchestrator import McpService +from uipath.platform.orchestrator._folder_service import FolderService +from uipath.platform.orchestrator.mcp_tasks import ( + McpTask, + McpTaskFailedError, + McpTaskStatus, + McpToolCallError, +) + +MCP_URL = "https://test.com/mcp/folder-key/test-mcp-server" + + +@pytest.fixture +def folders_service( + config: UiPathApiConfig, + execution_context: UiPathExecutionContext, + monkeypatch: pytest.MonkeyPatch, +) -> FolderService: + monkeypatch.setenv("UIPATH_FOLDER_KEY", "test-folder-key") + return FolderService(config=config, execution_context=execution_context) + + +@pytest.fixture +def service( + config: UiPathApiConfig, + execution_context: UiPathExecutionContext, + folders_service: FolderService, + monkeypatch: pytest.MonkeyPatch, +) -> McpService: + monkeypatch.setenv("UIPATH_FOLDER_KEY", "test-folder-key") + return McpService( + config=config, + execution_context=execution_context, + folders_service=folders_service, + ) + + +def mock_retrieve(httpx_mock: HTTPXMock, base_url: str, org: str, tenant: str) -> None: + httpx_mock.add_response( + url=f"{base_url}{org}{tenant}/agenthub_/api/servers/test-mcp-server", + status_code=200, + json={ + "id": "server-id-1", + "name": "Test MCP Server", + "slug": "test-mcp-server", + "type": 0, + "folderKey": "test-folder-key", + "mcpUrl": MCP_URL, + }, + ) + + +def rpc_result(result: dict[str, Any], request_id: int = 1) -> dict[str, Any]: + return {"jsonrpc": "2.0", "id": request_id, "result": result} + + +def task_result( + status: str, + *, + result: Optional[dict[str, Any]] = None, + error: Optional[dict[str, Any]] = None, + result_type: str = "complete", + poll_interval_ms: int = 1, +) -> dict[str, Any]: + payload: dict[str, Any] = { + "resultType": result_type, + "taskId": "task-1", + "status": status, + "createdAt": "2026-11-10T10:00:00Z", + "lastUpdatedAt": "2026-11-10T10:00:01Z", + "ttlMs": None, + "pollIntervalMs": poll_interval_ms, + } + if result is not None: + payload["result"] = result + if error is not None: + payload["error"] = error + return payload + + +def known_task() -> McpTask: + return McpTask( + task_id="task-1", + status=McpTaskStatus.WORKING, + server_url=MCP_URL, + ) + + +class TestMcpTasks: + def test_call_tool_declares_extension_and_wire_headers( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result(task_result("working", result_type="task")), + ) + + outcome = service.call_tool("test-mcp-server", "long-process", {"a": 1}) + + assert outcome.is_task + assert outcome.task is not None + assert outcome.task.task_id == "task-1" + assert outcome.task.status == McpTaskStatus.WORKING + assert outcome.task.server_url == MCP_URL + + call_request = httpx_mock.get_requests()[1] + assert call_request.method == "POST" + assert call_request.headers["MCP-Protocol-Version"] == "2026-07-28" + assert call_request.headers["Mcp-Method"] == "tools/call" + assert call_request.headers["Mcp-Name"] == base64.b64encode( + b"long-process" + ).decode("ascii") + + body = json.loads(call_request.content) + assert body["method"] == "tools/call" + assert body["params"]["name"] == "long-process" + assert body["params"]["arguments"] == {"a": 1} + meta = body["params"]["_meta"] + assert meta["io.modelcontextprotocol/protocolVersion"] == "2026-07-28" + capabilities = meta["io.modelcontextprotocol/clientCapabilities"] + assert "io.modelcontextprotocol/tasks" in capabilities["extensions"] + + def test_call_tool_passes_through_synchronous_result( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + {"content": [{"type": "text", "text": "quick"}], "isError": False} + ), + ) + + outcome = service.call_tool("test-mcp-server", "quick-process") + + assert not outcome.is_task + assert outcome.result is not None + assert outcome.result["content"][0]["text"] == "quick" + + def test_call_tool_and_wait_polls_until_completed( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result(task_result("working", result_type="task")), + ) + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result(task_result("working")) + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={ + "isError": False, + "content": [{"type": "text", "text": "finally"}], + "structuredContent": {"output": "finally"}, + }, + ) + ), + ) + + result = service.call_tool_and_wait( + "test-mcp-server", "long-process", timeout=10 + ) + + assert result["content"][0]["text"] == "finally" + + methods = [ + json.loads(request.content)["method"] + for request in httpx_mock.get_requests()[1:] + ] + assert methods == ["tools/call", "tasks/get", "tasks/get"] + + get_request = httpx_mock.get_requests()[2] + assert json.loads(get_request.content)["params"]["taskId"] == "task-1" + assert "Mcp-Name" not in get_request.headers + + def test_wait_for_task_raises_on_failed( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result("failed", error={"code": -32603, "message": "job faulted"}) + ), + ) + + with pytest.raises(McpTaskFailedError) as failure: + service.wait_for_task(known_task(), timeout=10) + + assert failure.value.task.error == {"code": -32603, "message": "job faulted"} + + def test_cancel_task_sends_tasks_cancel( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result({"resultType": "complete"}) + ) + + service.cancel_task(known_task()) + + body = json.loads(httpx_mock.get_requests()[0].content) + assert body["method"] == "tasks/cancel" + assert body["params"]["taskId"] == "task-1" + + def test_json_rpc_error_raises_tool_call_error( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json={ + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32602, "message": "Unknown task id."}, + }, + ) + + with pytest.raises(McpToolCallError) as error: + service.get_task(known_task()) + + assert error.value.code == -32602 + assert error.value.message == "Unknown task id." + + def test_sse_framed_response_is_parsed( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + envelope = rpc_result(task_result("working")) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + headers={"content-type": "text/event-stream"}, + text=f"event: message\ndata: {json.dumps(envelope)}\n\n", + ) + + snapshot = service.get_task(known_task()) + + assert snapshot.task_id == "task-1" + assert snapshot.status == McpTaskStatus.WORKING + assert snapshot.server_url == MCP_URL + + def test_task_without_server_url_is_rejected(self, service: McpService) -> None: + orphan = McpTask(task_id="task-9", status=McpTaskStatus.WORKING) + + with pytest.raises(McpToolCallError, match="no server URL"): + service.get_task(orphan) + + @pytest.mark.anyio + async def test_call_tool_and_wait_async_polls_until_completed( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result(task_result("working", result_type="task")), + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={ + "isError": False, + "content": [{"type": "text", "text": "async done"}], + }, + ) + ), + ) + + result = await service.call_tool_and_wait_async( + "test-mcp-server", "long-process", timeout=10 + ) + + assert result["content"][0]["text"] == "async done" From e14ad9f7172fa87c5f7a4697217554ed4cdaa2f7 Mon Sep 17 00:00:00 2001 From: alessandromuresan Date: Mon, 23 Nov 2026 13:00:12 +0200 Subject: [PATCH 2/4] fix(platform): address review findings on the MCP Tasks client Three fixes from the Copilot review of #2015: - SSE framing: _parse_mcp_envelope stopped at the first data event, so a stream that delivers a notification before the response read the notification as the answer and reported a perfectly good result as missing. Every event is now parsed and the first one carrying result or error wins; a body with no response at all says so explicitly. - The inter-poll sleep was clamped to the deadline but the poll that followed was unbounded, so a slow or stalled tasks/get could answer long after the caller's timeout. The remaining budget is now re-checked after the sleep and passed as the request timeout, in both the sync and async waiters, with a transport timeout surfacing as TimeoutError naming the task. - Both waiters raise the same TimeoutError shape, so a caller can still poll or cancel the task it names. Jira: PRODEV-2011 Co-Authored-By: Claude Opus 5 --- .../platform/orchestrator/_mcp_service.py | 140 +++++++++++++++--- .../tests/services/test_mcp_tasks.py | 82 ++++++++++ 2 files changed, 200 insertions(+), 22 deletions(-) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py index 34c60b5eb..a8224ea51 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py @@ -435,7 +435,11 @@ def wait_for_task( return terminal time.sleep(self._poll_delay_seconds(snapshot, deadline, timeout)) - snapshot = self.get_task(snapshot) + budget = self._poll_budget_seconds(snapshot, deadline, timeout) + try: + snapshot = self._get_task_within(snapshot, budget) + except httpx.TimeoutException as exhausted: + raise self._task_timeout(snapshot, timeout) from exhausted @traced(name="mcp_wait_for_task", run_type="uipath") async def wait_for_task_async( @@ -469,7 +473,11 @@ async def wait_for_task_async( return terminal await asyncio.sleep(self._poll_delay_seconds(snapshot, deadline, timeout)) - snapshot = await self.get_task_async(snapshot) + budget = self._poll_budget_seconds(snapshot, deadline, timeout) + try: + snapshot = await self._get_task_within_async(snapshot, budget) + except httpx.TimeoutException as exhausted: + raise self._task_timeout(snapshot, timeout) from exhausted @traced(name="mcp_call_tool_and_wait", run_type="uipath") def call_tool_and_wait( @@ -599,6 +607,48 @@ def _poll_delay_seconds( delay = min(delay, remaining) return delay + @staticmethod + def _task_timeout(snapshot: McpTask, timeout: Optional[float]) -> TimeoutError: + """The uniform timeout, naming the task so the caller can still poll or cancel it.""" + return TimeoutError( + f"MCP task {snapshot.task_id} did not finish within {timeout} seconds." + ) + + @staticmethod + def _poll_budget_seconds( + snapshot: McpTask, deadline: Optional[float], timeout: Optional[float] + ) -> Optional[float]: + """What is left of the caller's budget, as a bound for one poll request. + + Checked after the inter-poll sleep: a sleep clamped to the deadline + would otherwise be followed by an unbounded request, letting a slow or + stalled ``tasks/get`` answer long after the budget expired. + """ + if deadline is None: + return None + remaining = deadline - time.monotonic() + if remaining <= 0: + raise McpService._task_timeout(snapshot, timeout) + return remaining + + def _get_task_within(self, task: McpTask, budget: Optional[float]) -> McpTask: + """``get_task``, with the HTTP request bounded by *budget* seconds.""" + server_url = self._require_server_url(task) + result = self._send_mcp( + server_url, "tasks/get", {"taskId": task.task_id}, request_timeout=budget + ) + return self._task_from_result(result, server_url) + + async def _get_task_within_async( + self, task: McpTask, budget: Optional[float] + ) -> McpTask: + """``get_task_async``, with the HTTP request bounded by *budget* seconds.""" + server_url = self._require_server_url(task) + result = await self._send_mcp_async( + server_url, "tasks/get", {"taskId": task.task_id}, request_timeout=budget + ) + return self._task_from_result(result, server_url) + def _mcp_rpc_envelope( self, method: str, params: dict[str, Any], routing_name: Optional[str] ) -> tuple[dict[str, Any], dict[str, str]]: @@ -642,9 +692,13 @@ def _send_mcp( method: str, params: dict[str, Any], routing_name: Optional[str] = None, + request_timeout: Optional[float] = None, ) -> dict[str, Any]: body, headers = self._mcp_rpc_envelope(method, params, routing_name) - response = self.request("POST", server_url, json=body, headers=headers) + extra: dict[str, Any] = ( + {} if request_timeout is None else {"timeout": request_timeout} + ) + response = self.request("POST", server_url, json=body, headers=headers, **extra) return self._parse_mcp_envelope(response, method) async def _send_mcp_async( @@ -653,36 +707,78 @@ async def _send_mcp_async( method: str, params: dict[str, Any], routing_name: Optional[str] = None, + request_timeout: Optional[float] = None, ) -> dict[str, Any]: body, headers = self._mcp_rpc_envelope(method, params, routing_name) + extra: dict[str, Any] = ( + {} if request_timeout is None else {"timeout": request_timeout} + ) response = await self.request_async( - "POST", server_url, json=body, headers=headers + "POST", server_url, json=body, headers=headers, **extra ) return self._parse_mcp_envelope(response, method) + @staticmethod + def _sse_data_events(text: str) -> List[str]: + """The payload of every ``data:`` event in an SSE body, in order.""" + events: List[str] = [] + data_lines: List[str] = [] + for line in text.replace("\r\n", "\n").split("\n"): + if not line: + if data_lines: + events.append("\n".join(data_lines)) + data_lines = [] + continue + if line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if data_lines: + events.append("\n".join(data_lines)) + return events + + @staticmethod + def _sse_response_envelope(text: str, method: str) -> dict[str, Any]: + """The JSON-RPC response carried by an SSE body. + + A stream may deliver notifications, and server-initiated requests, + before the response to our own call, so every event is parsed and the + first one carrying ``result`` or ``error`` wins. Reading only the + first event would take a leading notification for the answer and then + report a perfectly good result as missing. + """ + events = McpService._sse_data_events(text) + if not events: + raise McpToolCallError( + 0, f"The MCP SSE response to '{method}' had no data event." + ) + + for payload in events: + try: + candidate = json.loads(payload) + except json.JSONDecodeError: + continue + if isinstance(candidate, dict) and ( + "result" in candidate or "error" in candidate + ): + return candidate + + raise McpToolCallError( + 0, f"The MCP SSE response to '{method}' carried no JSON-RPC response." + ) + @staticmethod def _parse_mcp_envelope(response: httpx.Response, method: str) -> dict[str, Any]: - """The JSON-RPC envelope, whether framed as plain JSON or one SSE event.""" + """The JSON-RPC envelope, whether framed as plain JSON or SSE.""" text = response.text + envelope: Any if "text/event-stream" in response.headers.get("content-type", ""): - data_lines: list[str] = [] - for line in text.replace("\r\n", "\n").split("\n"): - if not line and data_lines: - break - if line.startswith("data:"): - data_lines.append(line[5:].lstrip()) - if not data_lines: + envelope = McpService._sse_response_envelope(text, method) + else: + try: + envelope = json.loads(text) + except json.JSONDecodeError: raise McpToolCallError( - 0, f"The MCP SSE response to '{method}' had no data event." - ) - text = "\n".join(data_lines) - - try: - envelope = json.loads(text) - except json.JSONDecodeError: - raise McpToolCallError( - 0, f"The MCP response to '{method}' was not JSON." - ) from None + 0, f"The MCP response to '{method}' was not JSON." + ) from None if not isinstance(envelope, dict): raise McpToolCallError( diff --git a/packages/uipath-platform/tests/services/test_mcp_tasks.py b/packages/uipath-platform/tests/services/test_mcp_tasks.py index 859ae3983..4a9971b74 100644 --- a/packages/uipath-platform/tests/services/test_mcp_tasks.py +++ b/packages/uipath-platform/tests/services/test_mcp_tasks.py @@ -1,5 +1,6 @@ import base64 import json +import time from typing import Any, Optional import pytest @@ -311,3 +312,84 @@ async def test_call_tool_and_wait_async_polls_until_completed( ) assert result["content"][0]["text"] == "async done" + + +class TestMcpTasksReviewFindings: + """Regression cover for the review findings on PR #2015.""" + + def test_sse_response_after_a_notification_is_still_read( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """A leading notification must not be mistaken for the answer.""" + mock_retrieve(httpx_mock, base_url, org, tenant) + notification = json.dumps( + { + "jsonrpc": "2.0", + "method": "notifications/message", + "params": {"level": "info", "data": "job started"}, + } + ) + answer = json.dumps(rpc_result(task_result("working", result_type="task"))) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + headers={"content-type": "text/event-stream"}, + text=( + "event: message\ndata: " + + notification + + "\n\nevent: message\ndata: " + + answer + + "\n\n" + ), + ) + + outcome = service.call_tool("test-mcp-server", "long-process", {}) + + assert outcome.is_task + assert outcome.task is not None + assert outcome.task.task_id == "task-1" + + def test_sse_body_carrying_only_notifications_is_reported( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """Notifications alone are not an answer, and the error says so.""" + mock_retrieve(httpx_mock, base_url, org, tenant) + notification = json.dumps( + {"jsonrpc": "2.0", "method": "notifications/message", "params": {}} + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + headers={"content-type": "text/event-stream"}, + text="data: " + notification + "\n\n", + ) + + with pytest.raises(McpToolCallError, match="carried no JSON-RPC response"): + service.call_tool("test-mcp-server", "long-process", {}) + + def test_a_poll_is_bounded_by_the_remaining_budget(self) -> None: + """The request bound shrinks with the deadline, so a slow poll cannot outlive it.""" + budget = McpService._poll_budget_seconds( + known_task(), time.monotonic() + 7.5, 30.0 + ) + + assert budget is not None + assert 0 < budget <= 7.5 + + def test_an_expired_budget_raises_before_the_poll_goes_out(self) -> None: + """Checked after the sleep: an exhausted budget must not start another request.""" + with pytest.raises(TimeoutError, match="task-1"): + McpService._poll_budget_seconds(known_task(), time.monotonic() - 0.01, 30.0) + + def test_no_timeout_means_no_request_bound(self) -> None: + assert McpService._poll_budget_seconds(known_task(), None, None) is None From 64170ca1bbed117b123ed4081f9b2e44340236c7 Mon Sep 17 00:00:00 2001 From: alessandromuresan Date: Mon, 23 Nov 2026 13:21:24 +0200 Subject: [PATCH 3/4] test(platform): cover the MCP Tasks client's async and framing paths Lifts new-code coverage over the Sonar gate (89.6% -> both new files at 100%): the async twins of get/cancel, both synchronous-passthrough shortcuts, the cancelled terminal state, a server with no MCP URL, the poll-bound timeout on each loop, and the SSE/envelope framing edges only a malformed server produces. Also bumps uipath-platform to 0.3.15 (0.3.14 is on PyPI) and records the one thing the per-poll request bound does not do: the platform retry policy treats a timeout as transient and re-sends, so an unreachable server can still overrun the caller's timeout by the retry budget before the loop gives up. What it does prevent is a *successful* snapshot arriving past the deadline and being taken as the result. Co-Authored-By: Claude Opus 5 --- packages/uipath-platform/pyproject.toml | 2 +- .../platform/orchestrator/_mcp_service.py | 6 + .../tests/services/test_mcp_tasks.py | 235 ++++++++++++++++++ packages/uipath-platform/uv.lock | 2 +- packages/uipath/uv.lock | 2 +- 5 files changed, 244 insertions(+), 3 deletions(-) diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index 303c61d24..8b4276434 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.14" +version = "0.3.15" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py index a8224ea51..75613fac4 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py @@ -623,6 +623,12 @@ def _poll_budget_seconds( Checked after the inter-poll sleep: a sleep clamped to the deadline would otherwise be followed by an unbounded request, letting a slow or stalled ``tasks/get`` answer long after the budget expired. + + The bound caps one HTTP attempt. The platform retry policy treats a + timeout as transient and re-sends, so an unreachable server can still + overrun the caller's timeout by the retry budget before the loop gives + up -- but a *successful* snapshot can no longer arrive past it, which + is what would otherwise be taken as a result. """ if deadline is None: return None diff --git a/packages/uipath-platform/tests/services/test_mcp_tasks.py b/packages/uipath-platform/tests/services/test_mcp_tasks.py index 4a9971b74..4fe1e5af2 100644 --- a/packages/uipath-platform/tests/services/test_mcp_tasks.py +++ b/packages/uipath-platform/tests/services/test_mcp_tasks.py @@ -3,6 +3,7 @@ import time from typing import Any, Optional +import httpx import pytest from pytest_httpx import HTTPXMock @@ -11,6 +12,7 @@ from uipath.platform.orchestrator._folder_service import FolderService from uipath.platform.orchestrator.mcp_tasks import ( McpTask, + McpTaskCancelledError, McpTaskFailedError, McpTaskStatus, McpToolCallError, @@ -95,6 +97,16 @@ def known_task() -> McpTask: ) +def polling_task() -> McpTask: + """A known task whose poll interval keeps a timeout test quick.""" + return McpTask( + task_id="task-1", + status=McpTaskStatus.WORKING, + server_url=MCP_URL, + poll_interval_ms=1, + ) + + class TestMcpTasks: def test_call_tool_declares_extension_and_wire_headers( self, @@ -393,3 +405,226 @@ def test_an_expired_budget_raises_before_the_poll_goes_out(self) -> None: def test_no_timeout_means_no_request_bound(self) -> None: assert McpService._poll_budget_seconds(known_task(), None, None) is None + + +class TestMcpTaskAsyncSurface: + """The async twins, the terminal paths, and the two refusals.""" + + @pytest.mark.anyio + async def test_get_task_async_reads_one_snapshot( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result(task_result("working")) + ) + + snapshot = await service.get_task_async(known_task()) + + assert snapshot.status == McpTaskStatus.WORKING + assert json.loads(httpx_mock.get_requests()[0].content)["method"] == "tasks/get" + + @pytest.mark.anyio + async def test_cancel_task_async_sends_tasks_cancel( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result({"resultType": "complete"}) + ) + + await service.cancel_task_async(known_task()) + + body = json.loads(httpx_mock.get_requests()[0].content) + assert body["method"] == "tasks/cancel" + assert body["params"]["taskId"] == "task-1" + + def test_call_tool_and_wait_passes_a_synchronous_result_through( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """No task, no poll: the one-call convenience must not cost a round trip.""" + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + {"content": [{"type": "text", "text": "quick"}], "isError": False} + ), + ) + + result = service.call_tool_and_wait( + "test-mcp-server", "quick-process", timeout=10 + ) + + assert result["content"][0]["text"] == "quick" + methods = [ + json.loads(request.content)["method"] + for request in httpx_mock.get_requests()[1:] + ] + assert methods == ["tools/call"] + + @pytest.mark.anyio + async def test_call_tool_and_wait_async_passes_a_synchronous_result_through( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + {"content": [{"type": "text", "text": "quick"}], "isError": False} + ), + ) + + result = await service.call_tool_and_wait_async( + "test-mcp-server", "quick-process", timeout=10 + ) + + assert result["content"][0]["text"] == "quick" + + def test_wait_for_task_raises_on_cancelled( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result(task_result("cancelled")) + ) + + with pytest.raises(McpTaskCancelledError) as cancelled: + service.wait_for_task(known_task(), timeout=10) + + assert cancelled.value.task.task_id == "task-1" + + def test_only_the_three_final_statuses_are_terminal(self) -> None: + terminal = [status for status in McpTaskStatus if status.is_terminal] + + assert terminal == [ + McpTaskStatus.COMPLETED, + McpTaskStatus.FAILED, + McpTaskStatus.CANCELLED, + ] + + def test_a_server_without_an_mcp_url_is_reported( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + httpx_mock.add_response( + url=f"{base_url}{org}{tenant}/agenthub_/api/servers/test-mcp-server", + status_code=200, + json={ + "id": "server-id-1", + "name": "Test MCP Server", + "slug": "test-mcp-server", + "type": 0, + "folderKey": "test-folder-key", + }, + ) + + with pytest.raises(McpToolCallError, match="exposes no MCP URL"): + service.call_tool("test-mcp-server", "long-process") + + @pytest.mark.anyio + async def test_a_server_without_an_mcp_url_is_reported_async( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + httpx_mock.add_response( + url=f"{base_url}{org}{tenant}/agenthub_/api/servers/test-mcp-server", + status_code=200, + json={ + "id": "server-id-1", + "name": "Test MCP Server", + "slug": "test-mcp-server", + "type": 0, + "folderKey": "test-folder-key", + }, + ) + + with pytest.raises(McpToolCallError, match="exposes no MCP URL"): + await service.call_tool_async("test-mcp-server", "long-process") + + def test_a_poll_that_hits_its_bound_becomes_a_task_timeout( + self, service: McpService, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The HTTP timeout is the budget running out, so it reads as one.""" + + def exhausted(task: McpTask, budget: Optional[float]) -> McpTask: + raise httpx.ReadTimeout("the server never answered") + + monkeypatch.setattr(service, "_get_task_within", exhausted) + + with pytest.raises(TimeoutError, match="task-1"): + service.wait_for_task(polling_task(), timeout=10) + + @pytest.mark.anyio + async def test_a_poll_that_hits_its_bound_becomes_a_task_timeout_async( + self, service: McpService, monkeypatch: pytest.MonkeyPatch + ) -> None: + async def exhausted(task: McpTask, budget: Optional[float]) -> McpTask: + raise httpx.ReadTimeout("the server never answered") + + monkeypatch.setattr(service, "_get_task_within_async", exhausted) + + with pytest.raises(TimeoutError, match="task-1"): + await service.wait_for_task_async(polling_task(), timeout=10) + + def test_a_deadline_already_past_stops_before_sleeping(self) -> None: + with pytest.raises(TimeoutError, match="task-1"): + McpService._poll_delay_seconds(known_task(), time.monotonic() - 1, 30.0) + + +class TestMcpEnvelopeParsing: + """The framing edges, which only a malformed server produces.""" + + def test_a_trailing_event_without_a_blank_line_is_still_read(self) -> None: + """SSE bodies are not required to end with the event separator.""" + events = McpService._sse_data_events('data: {"a": 1}') + + assert events == ['{"a": 1}'] + + def test_an_sse_body_with_no_data_event_is_reported(self) -> None: + with pytest.raises(McpToolCallError, match="had no data event"): + McpService._sse_response_envelope("event: ping\n\n", "tasks/get") + + def test_an_unparseable_event_is_skipped_for_the_next_one(self) -> None: + """A heartbeat or comment payload must not mask the response behind it.""" + answer = json.dumps(rpc_result(task_result("working"))) + + envelope = McpService._sse_response_envelope( + f"data: not-json\n\ndata: {answer}\n\n", "tasks/get" + ) + + assert envelope["result"]["taskId"] == "task-1" + + def test_a_body_that_is_not_json_is_reported(self) -> None: + response = httpx.Response(200, text="login") + + with pytest.raises(McpToolCallError, match="was not JSON"): + McpService._parse_mcp_envelope(response, "tools/call") + + def test_a_body_that_is_not_an_envelope_is_reported(self) -> None: + response = httpx.Response(200, json=[1, 2, 3]) + + with pytest.raises(McpToolCallError, match="was not an envelope"): + McpService._parse_mcp_envelope(response, "tools/call") + + def test_an_envelope_without_a_result_object_is_reported(self) -> None: + response = httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": None}) + + with pytest.raises(McpToolCallError, match="carried no result object"): + McpService._parse_mcp_envelope(response, "tools/call") diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index b0b0ea69e..bd1d58394 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1082,7 +1082,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.14" +version = "0.3.15" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ffe6b8ab7..738bbb257 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.14" +version = "0.3.15" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" }, From 3f6dd549b1977f354dca78baf2b067640529fe61 Mon Sep 17 00:00:00 2001 From: alessandromuresan Date: Mon, 23 Nov 2026 14:06:37 +0200 Subject: [PATCH 4/4] fix(platform): make the MCP task wait timeout a hard deadline Addresses codex P1 on #2015. Bounding each tasks/get by the remaining budget was not enough: the platform retry policy treats a timeout as transient and re-sends it up to MAX_RETRY_ATTEMPTS times with exponential backoff between them, so a wait could return long after its documented timeout -- and in a serverless runtime, eat the execution window it was sized against. Polls now go out as a single attempt (`_request_once`, tenacity's own `retry_with`), and the poll loop is the retry: it re-sends on the task's own cadence and re-checks the deadline every time, so a transient blip still does not end a long wait. A poll bounded by the remaining budget timing out *is* the deadline arriving, so it becomes the task timeout. Waits with no timeout have no deadline to bound them, so five consecutive failures end them instead of polling a vanished server forever. Tests pin all four: one request per timed-out poll (not five), a blip absorbed by the loop in both the sync and async paths, the failure cap, and a non-transient status raised at once. Co-Authored-By: Claude Opus 5 --- .../platform/orchestrator/_mcp_service.py | 127 +++++++++++++++--- .../tests/services/test_mcp_tasks.py | 83 ++++++++++++ 2 files changed, 192 insertions(+), 18 deletions(-) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py index 75613fac4..07e6d6d14 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py @@ -2,10 +2,11 @@ import base64 import json import time -from typing import Any, List, Optional +from typing import Any, List, Optional, cast from urllib.parse import quote import httpx +from tenacity import stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -15,6 +16,8 @@ from ..common._folder_context import FolderContext, header_folder from ..common._models import Endpoint, RequestSpec from ..common._resource_identifier import resolve_retrieve_identifier +from ..common.retry import MAX_RETRY_ATTEMPTS, is_retryable_platform_exception +from ..errors import EnrichedException from ._folder_service import FolderService from .mcp import McpServer from .mcp_tasks import ( @@ -31,6 +34,11 @@ _DEFAULT_POLL_INTERVAL_MS = 5000 +# Consecutive failed polls tolerated before a wait gives up. Polls bypass the +# platform retry policy (see ``_get_task_within``), so this is what stops an +# unreachable server from being polled forever when the caller set no timeout. +_MAX_POLL_FAILURES = MAX_RETRY_ATTEMPTS + class McpService(FolderContext, BaseService): """Service for managing MCP (Model Context Protocol) servers in UiPath. @@ -428,6 +436,7 @@ def wait_for_task( """ deadline = None if timeout is None else time.monotonic() + timeout snapshot = task + failures = 0 while True: terminal = self._terminal_result(snapshot) @@ -438,8 +447,12 @@ def wait_for_task( budget = self._poll_budget_seconds(snapshot, deadline, timeout) try: snapshot = self._get_task_within(snapshot, budget) - except httpx.TimeoutException as exhausted: - raise self._task_timeout(snapshot, timeout) from exhausted + except (httpx.TransportError, EnrichedException) as failure: + failures = self._poll_failure( + snapshot, failure, failures, deadline, timeout + ) + else: + failures = 0 @traced(name="mcp_wait_for_task", run_type="uipath") async def wait_for_task_async( @@ -466,6 +479,7 @@ async def wait_for_task_async( """ deadline = None if timeout is None else time.monotonic() + timeout snapshot = task + failures = 0 while True: terminal = self._terminal_result(snapshot) @@ -476,8 +490,12 @@ async def wait_for_task_async( budget = self._poll_budget_seconds(snapshot, deadline, timeout) try: snapshot = await self._get_task_within_async(snapshot, budget) - except httpx.TimeoutException as exhausted: - raise self._task_timeout(snapshot, timeout) from exhausted + except (httpx.TransportError, EnrichedException) as failure: + failures = self._poll_failure( + snapshot, failure, failures, deadline, timeout + ) + else: + failures = 0 @traced(name="mcp_call_tool_and_wait", run_type="uipath") def call_tool_and_wait( @@ -624,11 +642,9 @@ def _poll_budget_seconds( would otherwise be followed by an unbounded request, letting a slow or stalled ``tasks/get`` answer long after the budget expired. - The bound caps one HTTP attempt. The platform retry policy treats a - timeout as transient and re-sends, so an unreachable server can still - overrun the caller's timeout by the retry budget before the loop gives - up -- but a *successful* snapshot can no longer arrive past it, which - is what would otherwise be taken as a result. + The bound is what makes ``timeout`` a hard deadline rather than a + hint, together with polls bypassing the platform retry policy: see + :meth:`_get_task_within`. """ if deadline is None: return None @@ -637,21 +653,94 @@ def _poll_budget_seconds( raise McpService._task_timeout(snapshot, timeout) return remaining + def _poll_failure( + self, + snapshot: McpTask, + failure: Exception, + failures: int, + deadline: Optional[float], + timeout: Optional[float], + ) -> int: + """Handle a failed poll: re-raise it, or count it and poll on. + + A poll bounded by the remaining budget timing out *is* the deadline + arriving, so it becomes the task timeout. Anything else transient is + left to the loop, which re-sends ``tasks/get`` on its own cadence -- + the platform retry policy is off for polls precisely so that retrying + cannot outlive the deadline. The cap bounds a wait with no timeout + against a server that is simply gone. + + Returns: + int: The new consecutive-failure count. + + Raises: + TimeoutError: When a bounded poll ran out of budget. + Exception: The failure itself, when it is not transient or the + cap is reached. + """ + if deadline is not None and isinstance(failure, httpx.TimeoutException): + raise self._task_timeout(snapshot, timeout) from failure + + failures += 1 + if failures >= _MAX_POLL_FAILURES or not is_retryable_platform_exception( + failure + ): + raise failure + + self._logger.warning( + f"Transient failure polling MCP task {snapshot.task_id} " + f"({failures}/{_MAX_POLL_FAILURES}): {failure}" + ) + return failures + + def _request_once(self, method: str, url: str, **kwargs: Any) -> httpx.Response: + """``request`` with the platform retry policy stopped at one attempt.""" + single = type(self).request.retry_with(stop=stop_after_attempt(1)) # type: ignore[attr-defined] + return cast(httpx.Response, single(self, method, url, **kwargs)) + + async def _request_once_async( + self, method: str, url: str, **kwargs: Any + ) -> httpx.Response: + """``request_async`` with the platform retry policy stopped at one attempt.""" + single = type(self).request_async.retry_with( # type: ignore[attr-defined] + stop=stop_after_attempt(1) + ) + return cast(httpx.Response, await single(self, method, url, **kwargs)) + def _get_task_within(self, task: McpTask, budget: Optional[float]) -> McpTask: - """``get_task``, with the HTTP request bounded by *budget* seconds.""" + """``get_task``, bounded by *budget* seconds and tried exactly once. + + The platform retry policy is deliberately off: it re-sends a timed-out + request up to ``MAX_RETRY_ATTEMPTS`` times with exponential backoff + between them, which -- even with every attempt bounded -- lands the + answer long after the caller's deadline. The poll loop is the retry + instead; it re-sends on the task's own cadence and re-checks the + deadline every time. + """ server_url = self._require_server_url(task) result = self._send_mcp( - server_url, "tasks/get", {"taskId": task.task_id}, request_timeout=budget + server_url, + "tasks/get", + {"taskId": task.task_id}, + request_timeout=budget, + single_attempt=True, ) return self._task_from_result(result, server_url) async def _get_task_within_async( self, task: McpTask, budget: Optional[float] ) -> McpTask: - """``get_task_async``, with the HTTP request bounded by *budget* seconds.""" + """``get_task_async``, bounded by *budget* and tried exactly once. + + See :meth:`_get_task_within` for why the retry policy is off here. + """ server_url = self._require_server_url(task) result = await self._send_mcp_async( - server_url, "tasks/get", {"taskId": task.task_id}, request_timeout=budget + server_url, + "tasks/get", + {"taskId": task.task_id}, + request_timeout=budget, + single_attempt=True, ) return self._task_from_result(result, server_url) @@ -699,12 +788,14 @@ def _send_mcp( params: dict[str, Any], routing_name: Optional[str] = None, request_timeout: Optional[float] = None, + single_attempt: bool = False, ) -> dict[str, Any]: body, headers = self._mcp_rpc_envelope(method, params, routing_name) extra: dict[str, Any] = ( {} if request_timeout is None else {"timeout": request_timeout} ) - response = self.request("POST", server_url, json=body, headers=headers, **extra) + send = self._request_once if single_attempt else self.request + response = send("POST", server_url, json=body, headers=headers, **extra) return self._parse_mcp_envelope(response, method) async def _send_mcp_async( @@ -714,14 +805,14 @@ async def _send_mcp_async( params: dict[str, Any], routing_name: Optional[str] = None, request_timeout: Optional[float] = None, + single_attempt: bool = False, ) -> dict[str, Any]: body, headers = self._mcp_rpc_envelope(method, params, routing_name) extra: dict[str, Any] = ( {} if request_timeout is None else {"timeout": request_timeout} ) - response = await self.request_async( - "POST", server_url, json=body, headers=headers, **extra - ) + send = self._request_once_async if single_attempt else self.request_async + response = await send("POST", server_url, json=body, headers=headers, **extra) return self._parse_mcp_envelope(response, method) @staticmethod diff --git a/packages/uipath-platform/tests/services/test_mcp_tasks.py b/packages/uipath-platform/tests/services/test_mcp_tasks.py index 4fe1e5af2..89b540cba 100644 --- a/packages/uipath-platform/tests/services/test_mcp_tasks.py +++ b/packages/uipath-platform/tests/services/test_mcp_tasks.py @@ -583,6 +583,89 @@ async def exhausted(task: McpTask, budget: Optional[float]) -> McpTask: with pytest.raises(TimeoutError, match="task-1"): await service.wait_for_task_async(polling_task(), timeout=10) + def test_a_timed_out_poll_is_sent_once_not_five_times( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """The platform retry policy would outlive the deadline it is bounded by.""" + httpx_mock.add_exception( + httpx.ReadTimeout("the server never answered"), url=MCP_URL + ) + + with pytest.raises(TimeoutError, match="task-1"): + service.wait_for_task(polling_task(), timeout=10) + + assert len(httpx_mock.get_requests()) == 1 + + def test_a_transient_poll_failure_is_retried_by_the_loop( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """A blip must not end a long wait: the next tick re-polls the same task.""" + httpx_mock.add_exception(httpx.ConnectError("connection reset"), url=MCP_URL) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={ + "content": [{"type": "text", "text": "late"}], + "isError": False, + }, + ) + ), + ) + + result = service.wait_for_task(polling_task(), timeout=10) + + assert result["content"][0]["text"] == "late" + assert len(httpx_mock.get_requests()) == 2 + + @pytest.mark.anyio + async def test_a_transient_poll_failure_is_retried_by_the_loop_async( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + httpx_mock.add_exception(httpx.ConnectError("connection reset"), url=MCP_URL) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={ + "content": [{"type": "text", "text": "late"}], + "isError": False, + }, + ) + ), + ) + + result = await service.wait_for_task_async(polling_task(), timeout=10) + + assert result["content"][0]["text"] == "late" + + def test_a_server_that_is_simply_gone_stops_at_the_failure_cap( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """Without a timeout there is no deadline, so the cap is the only bound.""" + for _ in range(5): + httpx_mock.add_exception(httpx.ConnectError("gone"), url=MCP_URL) + + with pytest.raises(httpx.ConnectError): + service.wait_for_task(polling_task()) + + assert len(httpx_mock.get_requests()) == 5 + + def test_a_non_transient_poll_failure_is_raised_at_once( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """Only transient failures are the loop's to absorb.""" + httpx_mock.add_response(url=MCP_URL, status_code=403, json={"message": "nope"}) + + with pytest.raises(Exception, match="403"): + service.wait_for_task(polling_task(), timeout=10) + + assert len(httpx_mock.get_requests()) == 1 + def test_a_deadline_already_past_stops_before_sleeping(self) -> None: with pytest.raises(TimeoutError, match="task-1"): McpService._poll_delay_seconds(known_task(), time.monotonic() - 1, 30.0)