From 5c14cf8c3f72780e836291bf612b09f1ba07a01c Mon Sep 17 00:00:00 2001 From: alessandromuresan Date: Tue, 24 Nov 2026 21:25:13 +0200 Subject: [PATCH] feat(platform): add MCP Tasks extension support to McpService Adds the MCP Tasks extension (ext-tasks, revision 2026-07-28) to McpService, so the SDK can call an MCP tool whose work outlives the HTTP request -- in particular a UiPath-type server tool that starts an Orchestrator job. A task-capable tools/call declares the extension per request; the server decides whether to answer synchronously or with a durable task handle, and the caller polls tasks/get until the task is terminal. Each method has a sync and an async form: call_tool, get_task, wait_for_task, cancel_task, and call_tool_and_wait. Models and errors live in orchestrator/mcp_tasks.py. What gets re-sent, and what does not. A tools/call starts a job on every delivery, so the service-wide retry policy is wrong for it: a read timeout or a gateway 504 is consistent with the server having received the request and started work, and re-sending then runs the tool twice. Each request therefore picks its own policy -- tools/call re-sends only when a connect failed (nothing left the client), a poll never re-sends because the loop is the retry, and everything else keeps the service-wide policy. How a wait handles a failed poll. The timeout is a hard deadline: each tasks/get is bounded by what is left of it, the clock is re-read after the inter-poll sleep, and the platform retry policy is off so no retry can outlive it. Each poll is also capped at 30 seconds, because bounding it only by the remaining budget made a long timeout less resilient than no timeout at all -- one stalled socket consumed the whole wait and then reported the task as unfinished. A poll reads state and starts nothing, so while budget remains the loop absorbs any transport failure, any 5xx, and a JSON-RPC internal error; a 4xx other than 408 or 429 and any other JSON-RPC code reach the caller at once. Only a failure landing after the deadline becomes TimeoutError. Also: Mcp-Name is encoded per SEP-2243 (verbatim when it is plain printable ASCII, inside the =?base64?...?= sentinel otherwise), since a bare Base64 value decodes to itself and is rejected by the server's header/body cross-check; a non-2xx body carrying a JSON-RPC error reaches the caller as McpToolCallError rather than a bare HTTP error; a status the spec adds later keeps the wait polling; a task payload cannot name the endpoint its own follow-ups post the bearer token to; an SSE answer is matched by request id; and the long opaque task id is shortened in messages and logs while every request still carries it in full. Validated end to end against a live tenant: the extension advertised on server/discover, a tools/call answered with a task handle, polling to completion at the server's interval, the deadline expiring on an unfinished job, and cancellation. Co-Authored-By: Claude Opus 5 --- packages/uipath-platform/pyproject.toml | 2 +- .../uipath/platform/orchestrator/__init__.py | 16 + .../platform/orchestrator/_mcp_service.py | 935 ++++++++++++- .../uipath/platform/orchestrator/mcp_tasks.py | 219 +++ .../tests/services/test_mcp_tasks.py | 1171 +++++++++++++++++ packages/uipath-platform/uv.lock | 2 +- packages/uipath/uv.lock | 2 +- 7 files changed, 2343 insertions(+), 4 deletions(-) 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/pyproject.toml b/packages/uipath-platform/pyproject.toml index 4c0e4c119..ffb06bb1a 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.15" +version = "0.3.16" 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/__init__.py b/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py index 79d6dde30..72908c2c4 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py @@ -22,6 +22,15 @@ from .buckets import Bucket, BucketFile from .job import Job, JobErrorInfo, JobState from .mcp import McpServer, McpServerStatus, McpServerType +from .mcp_tasks import ( + McpTask, + McpTaskCancelledError, + McpTaskFailedError, + McpTaskInputRequiredError, + McpTaskStatus, + McpToolCallError, + McpToolCallOutcome, +) from .processes import Process from .queues import ( CommitType, @@ -61,4 +70,11 @@ "McpServer", "McpServerStatus", "McpServerType", + "McpTask", + "McpTaskCancelledError", + "McpTaskFailedError", + "McpTaskInputRequiredError", + "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..8bba1385e 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,14 @@ -from typing import List +import asyncio +import base64 +import importlib.metadata +import json +import random +import time +from typing import Any, Callable, List, Literal, Optional, cast from urllib.parse import quote +import httpx +from tenacity import retry_if_exception, stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -10,8 +18,116 @@ 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, + RETRYABLE_STATUS_CODES, + extract_retry_after_from_chain, +) +from ..errors import EnrichedException 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, + McpTaskInputRequiredError, + McpTaskStatus, + McpToolCallError, + McpToolCallOutcome, + task_ref, +) + + +def _sdk_version() -> str: + """This package's version, for the MCP ``clientInfo`` block.""" + try: + return importlib.metadata.version("uipath-platform") + except importlib.metadata.PackageNotFoundError: # pragma: no cover + return "unknown" + + +_HEADER_BASE64_PREFIX = "=?base64?" +_HEADER_BASE64_SUFFIX = "?=" + + +def _encode_header_value(value: str) -> str: + """Encode one value for an MCP HTTP header, per SEP-2243. + + The encoding is conditional, not unconditional: a value that is plain + printable ASCII travels verbatim, because these headers exist so a gateway + can route on them *without* decoding anything or reading the body. Only a + value HTTP cannot carry -- non-ASCII, a control character, significant + leading or trailing whitespace -- is Base64'd, inside the + ``=?base64?...?=`` sentinel that tells the receiver which of the two it got. + A value that already looks like the sentinel is encoded too, so the two + cases stay distinguishable. + + Sending bare Base64 is therefore not a safe shortcut: the receiver finds no + sentinel, takes the blob to *be* the value, and the server's header/body + cross-check fails on every call. + """ + needs_base64 = ( + value[:1] in (" ", "\t") + or value[-1:] in (" ", "\t") + or ( + value.startswith(_HEADER_BASE64_PREFIX) + and value.endswith(_HEADER_BASE64_SUFFIX) + ) + or any(character < "\x20" or character > "\x7e" for character in value) + ) + if not needs_base64: + return value + + encoded = base64.b64encode(value.encode("utf-8")).decode("ascii") + return f"{_HEADER_BASE64_PREFIX}{encoded}{_HEADER_BASE64_SUFFIX}" + + +_DEFAULT_POLL_INTERVAL_MS = 5000 + +#: Floor under the server's poll interval. A server that asks to be polled +#: every millisecond gets a hot loop otherwise. +_MIN_POLL_INTERVAL_SECONDS = 0.1 + +#: Ceiling on one ``tasks/get`` request, independent of how much budget is +#: left. Bounding a poll by the whole remaining budget makes a stalled +#: connection cost the entire wait: an hour-long timeout would sit on one +#: black-holed socket for an hour and then report the task as unfinished, +#: while the same stall with no timeout at all is noticed in 30 seconds and +#: re-polled. The poll loop is the retry, so each attempt only needs to be +#: long enough for a healthy server to answer. +_MAX_POLL_REQUEST_SECONDS = 30.0 + +#: Backoff between consecutive failed polls, so a throttled or briefly broken +#: server is not hammered at the poll interval. +_POLL_BACKOFF_INITIAL_SECONDS = 1.0 +_MAX_POLL_BACKOFF_SECONDS = 30.0 + +#: JSON-RPC internal error. On a poll it says the server could not answer +#: *this* question, not that the task is gone, so the loop asks again. +_JSONRPC_INTERNAL_ERROR = -32603 + +# Consecutive failed polls tolerated by a wait with *no* deadline. Polls +# bypass the platform retry policy (see ``_get_task_within``), so this is what +# stops an unreachable server from being polled forever. A wait that was given +# a timeout is bounded by that timeout instead and keeps absorbing transient +# failures until it expires -- a caller who asked to wait an hour meant to ride +# out a blip, not to be handed the first one. +_MAX_POLL_FAILURES = MAX_RETRY_ATTEMPTS + +#: How a failed MCP request may be re-sent. +#: +#: ``platform`` is the service-wide policy: five attempts, retrying read +#: timeouts and 408/429/5xx. That is correct for a request the server can only +#: have read or not read -- and wrong for one that *starts work*. A read +#: timeout means the server received the request; the 30-second client timeout +#: or a gateway 504 says nothing about whether it already created an +#: Orchestrator job. So ``tools/call`` uses ``connect-only``: a failed connect +#: never left the client, and nothing else is re-sent. ``never`` is for a poll, +#: whose retry is the poll loop itself. +ResendPolicy = Literal["platform", "connect-only", "never"] class McpService(FolderContext, BaseService): @@ -245,3 +361,820 @@ 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, + resend="connect-only", + ) + 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, + resend="connect-only", + ) + 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 + failures = 0 + retry_after: Optional[float] = None + + while True: + terminal = self._terminal_result(snapshot) + if terminal is not None: + return terminal + + time.sleep( + self._poll_delay_seconds( + snapshot, deadline, timeout, failures, retry_after + ) + ) + budget = self._poll_budget_seconds(snapshot, deadline, timeout) + try: + snapshot = self._get_task_within(snapshot, budget) + except ( + httpx.TransportError, + EnrichedException, + McpToolCallError, + ) as failure: + failures = self._poll_failure( + snapshot, failure, failures, deadline, timeout + ) + retry_after = extract_retry_after_from_chain(failure) + else: + failures = 0 + retry_after = None + + @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 + failures = 0 + retry_after: Optional[float] = None + + while True: + terminal = self._terminal_result(snapshot) + if terminal is not None: + return terminal + + await asyncio.sleep( + self._poll_delay_seconds( + snapshot, deadline, timeout, failures, retry_after + ) + ) + budget = self._poll_budget_seconds(snapshot, deadline, timeout) + try: + snapshot = await self._get_task_within_async(snapshot, budget) + except ( + httpx.TransportError, + EnrichedException, + McpToolCallError, + ) as failure: + failures = self._poll_failure( + snapshot, failure, failures, deadline, timeout + ) + retry_after = extract_retry_after_from_chain(failure) + else: + failures = 0 + retry_after = None + + @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) + if snapshot.status == McpTaskStatus.INPUT_REQUIRED: + # Not terminal per spec, but terminal for a *waiter*: nothing here + # can answer an elicitation, and `timeout` defaults to None, so + # polling on would mean polling forever. The handle rides on the + # error, so a caller that can answer still has it. + raise McpTaskInputRequiredError(snapshot) + return None + + @staticmethod + def _poll_delay_seconds( + snapshot: McpTask, + deadline: Optional[float], + timeout: Optional[float], + failures: int = 0, + retry_after: Optional[float] = None, + ) -> float: + """How long to wait before the next poll. + + The server's interval is the baseline, floored so a zero or + one-millisecond interval cannot turn the loop into a spin. After a + failed poll the wait is whichever is longer: a ``Retry-After`` the + server asked for, or exponential backoff on the consecutive failure + count -- so a throttled server is not polled at full rate while it is + asking for room. The deadline still clamps the result, which is also + where an exhausted budget is noticed. + """ + delay = max( + (snapshot.poll_interval_ms or _DEFAULT_POLL_INTERVAL_MS) / 1000.0, + _MIN_POLL_INTERVAL_SECONDS, + ) + if failures: + delay = max(delay, McpService._poll_backoff_seconds(failures)) + if retry_after is not None: + delay = max(delay, retry_after) + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise McpService._task_timeout(snapshot, timeout) + 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 {task_ref(snapshot.task_id)} did not finish " + f"within {timeout} seconds." + ) + + @staticmethod + def _poll_backoff_seconds(failures: int) -> float: + """Backoff after *failures* consecutive failed polls. + + Doubling, capped, and jittered proportionally: many agent jobs can be + waiting on the same server, and a shared outage would otherwise have + all of them re-poll in lockstep. + """ + doubling = _POLL_BACKOFF_INITIAL_SECONDS * (2 ** (failures - 1)) + return min(doubling, _MAX_POLL_BACKOFF_SECONDS) * random.uniform(0.5, 1.0) + + @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. + + 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`. It is also capped at + ``_MAX_POLL_REQUEST_SECONDS`` so that a long deadline does not turn one + stalled connection into the whole wait. + """ + if deadline is None: + return None + remaining = deadline - time.monotonic() + if remaining <= 0: + raise McpService._task_timeout(snapshot, timeout) + return min(remaining, _MAX_POLL_REQUEST_SECONDS) + + 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. + + What ends the wait is the deadline, not the failure: a timeout, a + gateway error or a 429 says nothing about the task, which is still + running on the server. So a transient failure 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 -- and only an expired budget becomes ``TimeoutError``. + + The consecutive-failure cap applies to a wait with *no* deadline, + where it is the only thing standing between the loop and a server + that is simply gone. A wait that was given a timeout keeps absorbing + until that timeout expires: a caller who asked for an hour meant to + ride out a blip. + + Returns: + int: The new consecutive-failure count. + + Raises: + TimeoutError: When the deadline has passed. + Exception: The failure itself, when it is not transient, or when + an open-ended wait reaches the cap. + """ + if deadline is not None and time.monotonic() >= deadline: + raise self._task_timeout(snapshot, timeout) from failure + + failures += 1 + if not self._poll_is_transient(failure): + raise failure + if deadline is None and failures >= _MAX_POLL_FAILURES: + raise failure + + self._logger.warning( + f"Transient failure polling MCP task {task_ref(snapshot.task_id)} " + f"(consecutive failure {failures}): {failure}" + ) + return failures + + @staticmethod + def _poll_is_transient(failure: Exception) -> bool: + """Whether *failure* leaves the task worth asking about again. + + A poll reads state and starts nothing, so anything that looks like the + answer went missing is worth re-asking: every transport failure, every + 5xx (not only the subset the platform policy retries -- a plain 500 on + one poll is no verdict on the task), and a JSON-RPC internal error, + which is the same thing arriving inside a 200. A 4xx other than 408 or + 429, and any other JSON-RPC code, are answers rather than mishaps: the + task id is unknown, the method is not there, the caller is not allowed. + """ + if isinstance(failure, httpx.TransportError): + return True + + status: Optional[int] = None + if isinstance(failure, EnrichedException): + status = failure.status_code + elif isinstance(failure, McpToolCallError): + if failure.code == _JSONRPC_INTERNAL_ERROR: + return True + status = failure.status_code + + if status is None: + return False + return status in RETRYABLE_STATUS_CODES or 500 <= status < 600 + + @staticmethod + def _never_reached_the_server(exception: BaseException) -> bool: + """Whether *exception* proves the request was never delivered. + + A connect that failed, timed out, or never got a pool slot did not + put the request on the wire, so re-sending cannot duplicate anything. + Everything else the platform policy retries -- a read timeout, a 429, + a gateway 5xx -- is consistent with the server having received the + request and started work on it. + """ + return isinstance( + exception, + (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout), + ) + + def _sender(self, resend: ResendPolicy) -> Callable[..., httpx.Response]: + """The ``request`` variant implementing *resend*.""" + if resend == "platform": + return self.request + request = cast(Any, type(self).request) + if resend == "never": + narrowed = request.retry_with(stop=stop_after_attempt(1)) + else: + narrowed = request.retry_with( + retry=retry_if_exception(McpService._never_reached_the_server) + ) + return lambda *args, **kwargs: cast( + httpx.Response, narrowed(self, *args, **kwargs) + ) + + def _sender_async(self, resend: ResendPolicy) -> Callable[..., Any]: + """The ``request_async`` variant implementing *resend*.""" + if resend == "platform": + return self.request_async + request = cast(Any, type(self).request_async) + if resend == "never": + narrowed = request.retry_with(stop=stop_after_attempt(1)) + else: + narrowed = request.retry_with( + retry=retry_if_exception(McpService._never_reached_the_server) + ) + return lambda *args, **kwargs: narrowed(self, *args, **kwargs) + + def _get_task_within(self, task: McpTask, budget: Optional[float]) -> McpTask: + """``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, + resend="never", + ) + return self._task_from_result(result, server_url) + + async def _get_task_within_async( + self, task: McpTask, budget: Optional[float] + ) -> McpTask: + """``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, + resend="never", + ) + 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]]: + 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": _sdk_version(), + }, + "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 the routed + # methods, the name or uri being addressed) 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"] = _encode_header_value(routing_name) + return body, headers + + def _send_mcp( + self, + server_url: str, + method: str, + params: dict[str, Any], + routing_name: Optional[str] = None, + request_timeout: Optional[float] = None, + resend: ResendPolicy = "platform", + ) -> 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} + ) + send = self._sender(resend) + try: + response = send("POST", server_url, json=body, headers=headers, **extra) + except EnrichedException as failure: + # Bare re-raise when there is no JSON-RPC error to recover: `raise + # failure from failure` would make the exception its own __cause__, + # and anything walking that chain (the Retry-After lookup, for one) + # would never come back. + recovered = self._jsonrpc_error_in(failure) + if recovered is None: + raise + raise recovered from failure + return self._parse_mcp_envelope(response, method, body["id"]) + + async def _send_mcp_async( + self, + server_url: str, + method: str, + params: dict[str, Any], + routing_name: Optional[str] = None, + request_timeout: Optional[float] = None, + resend: ResendPolicy = "platform", + ) -> 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} + ) + send = self._sender_async(resend) + try: + response = await send( + "POST", server_url, json=body, headers=headers, **extra + ) + except EnrichedException as failure: + recovered = self._jsonrpc_error_in(failure) + if recovered is None: + raise + raise recovered from failure + return self._parse_mcp_envelope(response, method, body["id"]) + + @staticmethod + def _jsonrpc_error_in(failure: EnrichedException) -> Optional[McpToolCallError]: + """The JSON-RPC error a non-2xx response carried, if it carried one. + + ``request`` raises on status before the body is ever parsed, so a + server that answered "no such method" in JSON-RPC and mapped it onto + 404 would otherwise reach the caller as a bare HTTP error with the + code and message dropped -- while every docstring here promises + ``McpToolCallError``. The status rides along on the error, because it + is what says whether asking again could help, and the HTTP failure + stays the ``__cause__`` so a ``Retry-After`` is still reachable. + """ + cause: Optional[BaseException] = failure + while cause is not None and not isinstance(cause, httpx.HTTPStatusError): + cause = cause.__cause__ + if cause is None: + return None + + try: + envelope = json.loads(cause.response.text) + except (json.JSONDecodeError, UnicodeDecodeError): + return None + if not isinstance(envelope, dict) or not isinstance( + envelope.get("error"), dict + ): + return None + + error = envelope["error"] + return McpToolCallError( + code=error.get("code", 0), + message=error.get("message", "Unknown MCP error"), + data=error.get("data"), + status_code=failure.status_code, + ) + + @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:"): + # Exactly one optional space after the colon belongs to the + # framing; the rest of the line is payload. + payload = line[5:] + data_lines.append(payload[1:] if payload.startswith(" ") else payload) + if data_lines: + events.append("\n".join(data_lines)) + return events + + @staticmethod + def _sse_response_envelope( + text: str, method: str, request_id: Optional[Any] = None + ) -> 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 + answer is picked by id. Reading only the first event would take a + leading notification for the answer and then report a perfectly good + result as missing; taking the first event that merely carries + ``result`` or ``error`` would accept the answer to somebody else's + request. + """ + 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 not isinstance(candidate, dict) or not ( + "result" in candidate or "error" in candidate + ): + continue + if request_id is not None and "id" in candidate: + # Compared as text: JSON-RPC allows a string or a number, and + # a server is free to echo ours as either. + if str(candidate["id"]) != str(request_id): + continue + 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, request_id: Optional[Any] = None + ) -> dict[str, Any]: + """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", ""): + envelope = McpService._sse_response_envelope(text, method, request_id) + else: + 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..282daebd2 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py @@ -0,0 +1,219 @@ +"""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, Union + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic.alias_generators import to_camel + + +def task_ref(task_id: str) -> str: + """A task id shortened for a message or a log line. + + An MCP task id is a self-contained handle, not a short key: a UiPath server + mints one of 368 characters, and the first 27 of those are identical across + tasks (a header on the encrypted blob). Taking a prefix therefore + distinguishes nothing -- every task reads the same -- so this takes both + ends. Short ids, which is what tests use, are left alone. + + Whoever can reach the server can read or cancel a task with its id, and a + message or a log line travels further than the call that produced it; on + the agent path this text is also read by a model, where a few hundred + characters of opaque handle is noise it may well repeat. The full id stays + in the one log line written when the task is first seen, which is what an + operator needs to find a task that outlived its wait. + """ + if len(task_id) <= 32: + return task_id + return f"{task_id[:12]}...{task_id[-8:]}" + + +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 + + # A status the spec adds later must not break a poll in flight: an + # unrecognized one stays a plain string, which no terminal check matches, + # so the loop keeps polling instead of raising a ValidationError out of + # somebody's hour-long wait. Known values are always the enum. + status: Union[McpTaskStatus, str] + + 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, and + # never read off the wire either -- see _ignore_a_server_supplied_url. + server_url: Optional[str] = Field(default=None, exclude=True) + + @model_validator(mode="before") + @classmethod + def _ignore_a_server_supplied_url(cls, data: Any) -> Any: + """Drop ``serverUrl`` when it arrives as input data. + + This field is the client's own bookkeeping: the endpoint *we* sent the + call to. Every follow-up carries the caller's bearer token, so a task + payload that named its own endpoint would be a way to have this client + post that token wherever the payload said. The server has no business + setting it, and the camel-case spelling is the only one a payload can + arrive in -- the Python name stays available to this client, which is + how ``_task_from_result`` fills it in. + """ + if isinstance(data, dict) and "serverUrl" in data: + return {key: value for key, value in data.items() if key != "serverUrl"} + return data + + @field_validator("status", mode="before") + @classmethod + def _known_status_stays_typed(cls, value: Any) -> Any: + """Map a known status onto the enum, leave an unknown one a string. + + Pydantic's union resolution would hand back a plain ``str`` for a value + that is also a valid enum member, which would quietly break + ``status.is_terminal`` for callers. + """ + if isinstance(value, str) and not isinstance(value, McpTaskStatus): + try: + return McpTaskStatus(value) + except ValueError: + return value + return value + + +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 + + @model_validator(mode="after") + def _exactly_one(self) -> "McpToolCallOutcome": + """Enforce the either/or the docstring promises.""" + if (self.result is None) == (self.task is None): + raise ValueError( + "An MCP tool call answers with either a result or a task, not both " + "and not neither." + ) + return self + + @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. + + ``status_code`` is the HTTP status the error arrived with, when it arrived + on a non-2xx response. A server is free to answer a JSON-RPC error with a + matching HTTP status, so the status is kept alongside the code: it is what + says whether re-sending could help. + """ + + def __init__( + self, + code: int, + message: str, + data: Any = None, + status_code: Optional[int] = 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 + self.status_code = status_code + + +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_ref(task.task_id)} failed: {task.error}") + self.task = task + + +class McpTaskInputRequiredError(Exception): + """The task is parked on ``input_required``, which a waiter cannot answer. + + Not a terminal status per the spec -- the task can still proceed once the + input arrives -- but terminal for ``wait_for_task``, which has no way to + supply it and would otherwise poll until the caller's timeout, or forever + when there is none. + """ + + def __init__(self, task: McpTask) -> None: + """Initialize with the parked task snapshot.""" + super().__init__( + f"MCP task {task_ref(task.task_id)} requires additional input, " + "which this client cannot provide." + ) + 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_ref(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..584318b9f --- /dev/null +++ b/packages/uipath-platform/tests/services/test_mcp_tasks.py @@ -0,0 +1,1171 @@ +import base64 +import json +import time +from typing import Any, Optional + +import httpx +import pytest +from pytest_httpx import HTTPXMock + +from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.common.retry import extract_retry_after_from_chain +from uipath.platform.orchestrator import McpService, _mcp_service +from uipath.platform.orchestrator._folder_service import FolderService +from uipath.platform.orchestrator.mcp_tasks import ( + McpTask, + McpTaskCancelledError, + McpTaskFailedError, + McpTaskInputRequiredError, + McpTaskStatus, + McpToolCallError, + McpToolCallOutcome, + task_ref, +) + +MCP_URL = "https://test.com/mcp/folder-key/test-mcp-server" + + +@pytest.fixture(autouse=True) +def quick_poll_backoff(monkeypatch: pytest.MonkeyPatch) -> None: + """Shrink the inter-failure backoff so the retry paths run in milliseconds.""" + monkeypatch.setattr(_mcp_service, "_POLL_BACKOFF_INITIAL_SECONDS", 0.001) + monkeypatch.setattr(_mcp_service, "_MIN_POLL_INTERVAL_SECONDS", 0.001) + + +@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 decode_header_value(header_value: str) -> Optional[str]: + """Decode an MCP header value the way a server does (SEP-2243). + + Mirrors ``McpHeaderEncoder.DecodeValue`` in the MCP SDKs, which is what a + server cross-checks the header against the body with: strip the sentinel + and Base64-decode when both markers are present, and otherwise take the + value as it stands. ``None`` is a decode failure, which a server rejects. + """ + if header_value.startswith("=?base64?") and header_value.endswith("?="): + try: + return base64.b64decode( + header_value[len("=?base64?") : -len("?=")], validate=True + ).decode("utf-8") + except (ValueError, UnicodeDecodeError): + return None + return header_value + + +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, + ) + + +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, + 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" + # A plain tool name travels as itself -- the header is there to be read + # by a gateway that decodes nothing. + assert call_request.headers["Mcp-Name"] == "long-process" + + 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"] + + @pytest.mark.parametrize( + "tool_name", + [ + "long-process", + "café ☕", + "=?base64?bm90LWJhc2U2NA==?=", + "tool\twith\tcontrol", + ], + ids=["plain", "non-ascii", "sentinel-collision", "control-characters"], + ) + def test_call_tool_name_header_round_trips_to_the_body( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + tool_name: str, + ) -> None: + """The server accepts the call only if the header decodes to the body's name. + + Whatever the name, decoding the header the way a server does has to give + back exactly what the body carries; a bare Base64 blob decodes to itself + and fails that check. + """ + 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")), + ) + + service.call_tool("test-mcp-server", tool_name) + + call_request = httpx_mock.get_requests()[1] + name_header = call_request.headers["Mcp-Name"] + assert all("\x20" <= character <= "\x7e" for character in name_header), ( + "the header value must be printable ASCII" + ) + assert ( + decode_header_value(name_header) + == json.loads(call_request.content)["params"]["name"] + ) + + 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" + + +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 + ) + + # approx, not <=: (now + 7.5) - now is not exactly 7.5 in binary + # floating point, and on a clock with a large magnitude the error + # lands above the bound rather than below it. + assert budget == pytest.approx(7.5, abs=0.5) + + def test_one_poll_is_capped_even_when_the_deadline_is_far_away(self) -> None: + """Otherwise a long wait rides on one socket for its whole duration.""" + budget = McpService._poll_budget_seconds( + known_task(), time.monotonic() + 3600, 3600.0 + ) + + assert budget == pytest.approx(30.0, abs=0.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 + + +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_an_exhausted_deadline_is_what_becomes_a_task_timeout( + self, service: McpService, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A poll that runs past the deadline ends the wait, as a timeout.""" + + def exhausted(task: McpTask, budget: Optional[float]) -> McpTask: + time.sleep(0.06) + 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=0.05) + + @pytest.mark.anyio + async def test_an_exhausted_deadline_is_what_becomes_a_task_timeout_async( + self, service: McpService, monkeypatch: pytest.MonkeyPatch + ) -> None: + async def exhausted(task: McpTask, budget: Optional[float]) -> McpTask: + time.sleep(0.06) + 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=0.05) + + def test_a_timed_out_poll_with_budget_left_is_polled_again( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """A stalled connection is not the task's verdict, and not the deadline's. + + Treating any read timeout as the deadline made a long wait *less* + resilient than one with no timeout at all: one black-holed socket + ended an hour-long wait, while the same stall with ``timeout=None`` + was re-polled. + """ + httpx_mock.add_exception(httpx.ReadTimeout("no answer"), 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=30) + + assert result["content"][0]["text"] == "late" + assert len(httpx_mock.get_requests()) == 2 + + def test_a_timed_out_poll_is_sent_once_per_tick_not_five_times( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """The platform retry policy would outlive the deadline it is bounded by. + + Five ticks, five requests: the loop is the retry. With the policy on, + each tick would have re-sent up to ``MAX_RETRY_ATTEMPTS`` times behind + backoff of its own. + """ + for _ in range(5): + httpx_mock.add_exception(httpx.ReadTimeout("no answer"), url=MCP_URL) + + with pytest.raises(httpx.ReadTimeout): + service.wait_for_task(polling_task()) + + assert len(httpx_mock.get_requests()) == 5 + + 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_plain_500_on_a_poll_is_absorbed( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """500 is outside the platform's retryable set, but a poll is a read. + + The task is still running; the server just failed to describe it. + """ + httpx_mock.add_response(url=MCP_URL, status_code=500, json={"message": "boom"}) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={"content": [{"type": "text", "text": "ok"}]}, + ) + ), + ) + + result = service.wait_for_task(polling_task(), timeout=30) + + assert result["content"][0]["text"] == "ok" + + def test_a_json_rpc_internal_error_on_a_poll_is_absorbed( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """The same failure arriving inside a 200, which the loop never caught.""" + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json={ + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32603, "message": "internal error"}, + }, + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={"content": [{"type": "text", "text": "ok"}]}, + ) + ), + ) + + result = service.wait_for_task(polling_task(), timeout=30) + + assert result["content"][0]["text"] == "ok" + + def test_an_unknown_task_on_a_poll_is_raised_at_once( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """Not every JSON-RPC error is a blip: this one is an answer.""" + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json={ + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32602, "message": "unknown task"}, + }, + ) + + with pytest.raises(McpToolCallError, match="unknown task"): + service.wait_for_task(polling_task(), timeout=30) + + assert len(httpx_mock.get_requests()) == 1 + + def test_a_transient_failure_rides_until_the_deadline_not_the_cap( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """A caller who asked to wait meant to ride out more than four blips.""" + for _ in range(6): + httpx_mock.add_response( + url=MCP_URL, status_code=503, json={"message": "unavailable"} + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={"content": [{"type": "text", "text": "eventually"}]}, + ) + ), + ) + + result = service.wait_for_task(polling_task(), timeout=30) + + assert result["content"][0]["text"] == "eventually" + assert len(httpx_mock.get_requests()) == 7 + + def test_a_retry_after_sets_the_floor_for_the_next_poll(self) -> None: + """A throttled server asked for room; the poll interval does not override it.""" + failure = httpx.HTTPStatusError( + "throttled", + request=httpx.Request("POST", MCP_URL), + response=httpx.Response(429, headers={"retry-after": "4"}), + ) + + delay = McpService._poll_delay_seconds( + polling_task(), None, None, failures=1, retry_after=4.0 + ) + + assert delay == pytest.approx(4.0) + assert extract_retry_after_from_chain(failure) == 4.0 + + def test_a_zero_poll_interval_does_not_spin(self) -> None: + """A server asking to be polled instantly gets the floor instead.""" + eager = McpTask( + task_id="task-1", + status=McpTaskStatus.WORKING, + server_url=MCP_URL, + poll_interval_ms=0, + ) + + assert McpService._poll_delay_seconds(eager, None, None) >= 0.001 + + 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 TestTaskReference: + """What a task id looks like once it reaches a message or a log line.""" + + # Two real ids from a UiPath server: 368 characters, sharing their first 27. + REAL_A = "AfDP2j-98rUt7wxBowad5FIlYGx" + "A" * 333 + "4VD53jN7yzE8" + REAL_B = "AfDP2j-98rUt7wxBowad5FIlYGx" + "B" * 333 + "8eMkW1DIPfrp" + + def test_two_different_tasks_do_not_read_the_same(self) -> None: + """The whole point: a prefix of these ids is a constant, not a name.""" + assert task_ref(self.REAL_A) != task_ref(self.REAL_B) + + def test_a_long_id_is_shortened(self) -> None: + shortened = task_ref(self.REAL_A) + + assert len(shortened) < 40 + assert self.REAL_A not in shortened + # Both ends, so it can still be matched by eye against a full id. + assert shortened.startswith(self.REAL_A[:12]) + assert shortened.endswith(self.REAL_A[-8:]) + + def test_a_short_id_is_left_alone(self) -> None: + assert task_ref("task-1") == "task-1" + + def test_the_wire_carries_the_whole_id( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """Shortening is for text only: a request addresses the task by its id. + + A truncated id on the wire would be a different task -- or no task at + all -- so this pins the one thing the shortening must never touch. + """ + long_task = McpTask( + task_id=self.REAL_A, status=McpTaskStatus.WORKING, server_url=MCP_URL + ) + 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({"resultType": "complete"}) + ) + + service.get_task(long_task) + service.cancel_task(long_task) + + sent = [json.loads(request.content) for request in httpx_mock.get_requests()] + assert [body["method"] for body in sent] == ["tasks/get", "tasks/cancel"] + for body in sent: + assert body["params"]["taskId"] == self.REAL_A + + def test_the_wait_timeout_names_the_task_without_quoting_it(self) -> None: + task = McpTask(task_id=self.REAL_A, status=McpTaskStatus.WORKING) + + message = str(McpService._task_timeout(task, 30.0)) + + assert self.REAL_A not in message + assert self.REAL_A[:12] in message + + +class TestMcpTaskHandle: + """What a handle accepts, and what it refuses to take from the wire.""" + + def test_an_unknown_status_keeps_the_wait_polling( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """A status the spec adds later must not raise out of somebody's wait.""" + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result(task_result("suspended", poll_interval_ms=1)), + ) + httpx_mock.add_response( + url=MCP_URL, + status_code=200, + json=rpc_result( + task_result( + "completed", + result={"content": [{"type": "text", "text": "resumed"}]}, + ) + ), + ) + + result = service.wait_for_task(polling_task(), timeout=30) + + assert result["content"][0]["text"] == "resumed" + + def test_a_known_status_is_still_the_enum(self) -> None: + """Union resolution must not quietly hand back a plain string.""" + task = McpTask.model_validate({"taskId": "task-1", "status": "working"}) + + assert task.status is McpTaskStatus.WORKING + assert isinstance(task.status, McpTaskStatus) + + def test_a_payload_cannot_name_its_own_endpoint(self) -> None: + """Follow-ups carry the bearer token, so the server does not pick the host.""" + task = McpTask.model_validate( + { + "taskId": "task-1", + "status": "working", + "serverUrl": "https://evil.example.com/mcp", + } + ) + + assert task.server_url is None + + def test_the_client_still_records_where_it_sent_the_call(self) -> None: + task = McpTask( + task_id="task-1", status=McpTaskStatus.WORKING, server_url=MCP_URL + ) + + assert task.server_url == MCP_URL + assert "serverUrl" not in task.model_dump(by_alias=True) + + +class TestMcpToolCallIsNotResent: + """A tool call starts work server-side, so it must not be re-sent blindly.""" + + @staticmethod + def _tool_calls(httpx_mock: HTTPXMock) -> int: + return len([r for r in httpx_mock.get_requests() if str(r.url) == MCP_URL]) + + def test_a_read_timeout_does_not_resend_the_tool_call( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """The server has the request: re-sending it can start a second job. + + The platform policy would retry a timeout five times; the 30-second + client timeout makes that reachable for any tool answering slowly in + the synchronous shape. + """ + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_exception(httpx.ReadTimeout("still working"), url=MCP_URL) + + with pytest.raises(httpx.ReadTimeout): + service.call_tool("test-mcp-server", "long-process") + + assert self._tool_calls(httpx_mock) == 1 + + def test_a_gateway_504_does_not_resend_the_tool_call( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """A 504 says the gateway gave up, not that the server did nothing.""" + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_response(url=MCP_URL, status_code=504, json={"error": "timeout"}) + + with pytest.raises(Exception, match="504"): + service.call_tool("test-mcp-server", "long-process") + + assert self._tool_calls(httpx_mock) == 1 + + @pytest.mark.anyio + async def test_a_read_timeout_does_not_resend_the_tool_call_async( + 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_exception(httpx.ReadTimeout("still working"), url=MCP_URL) + + with pytest.raises(httpx.ReadTimeout): + await service.call_tool_async("test-mcp-server", "long-process") + + assert self._tool_calls(httpx_mock) == 1 + + def test_a_failed_connect_is_still_retried( + self, + httpx_mock: HTTPXMock, + service: McpService, + base_url: str, + org: str, + tenant: str, + ) -> None: + """Nothing was delivered, so re-sending cannot duplicate the work.""" + mock_retrieve(httpx_mock, base_url, org, tenant) + httpx_mock.add_exception(httpx.ConnectError("no route"), url=MCP_URL) + 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") + + assert outcome.is_task + assert self._tool_calls(httpx_mock) == 2 + + def test_a_task_parked_on_input_required_is_not_polled_forever( + self, httpx_mock: HTTPXMock, service: McpService + ) -> None: + """`timeout` defaults to None, so polling on would never end.""" + httpx_mock.add_response( + url=MCP_URL, status_code=200, json=rpc_result(task_result("input_required")) + ) + + with pytest.raises(McpTaskInputRequiredError) as parked: + service.wait_for_task(known_task()) + + assert parked.value.task.task_id == "task-1" + + def test_an_outcome_must_carry_exactly_one_shape(self) -> None: + with pytest.raises(ValueError, match="not both and not neither"): + McpToolCallOutcome(result={"content": []}, task=known_task()) + + with pytest.raises(ValueError, match="not both and not neither"): + McpToolCallOutcome() + + +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 9cf6f9918..e572e5a3e 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.15" +version = "0.3.16" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 97317fbec..5df0cda61 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.15" +version = "0.3.16" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" },