Repository navigation
feat(platform): add MCP Tasks extension support to McpService - #2015
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Both synchronous and asynchronous polling can exceed the caller’s timeout, and SSE parsing can discard valid results when notifications precede the response.
3 open issues
What changed in this PR
Adds MCP Tasks extension support to the UiPath Platform SDK, allowing McpService to invoke long-running tools and poll durable task handles for their results.
Changes:
- Adds sync and async APIs for tool calls, task polling, waiting, and cancellation.
- Introduces public task models and errors, plus protocol metadata, routing headers, and JSON/SSE response parsing.
- Adds mocked HTTP tests for synchronous results, task lifecycles, error handling, and async polling.
| File | Description |
|---|---|
packages/uipath-platform/tests/services/test_mcp_tasks.py |
Tests task workflows, request formatting, and response handling. |
packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py |
Defines task states, handles, outcomes, and exceptions. |
packages/uipath-platform/src/uipath/platform/orchestrator/_mcp_service.py |
Implements task-capable tool calls and lifecycle operations. |
packages/uipath-platform/src/uipath/platform/orchestrator/__init__.py |
Exports the new task models and errors. |
Review effort: Balanced
| time.sleep(self._poll_delay_seconds(snapshot, deadline, timeout)) | ||
| snapshot = self.get_task(snapshot) |
| 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) |
| 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) |
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
520e49a to
07c33ed
Compare
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. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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 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 <noreply@anthropic.com>
4f20dff to
2348f63
Compare
🚨 Heads up:
|
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 <noreply@anthropic.com>
3ace44d to
5c14cf8
Compare
🚨 Heads up:
|
|




What
Adds MCP Tasks extension support (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 MCP server tool that starts an Orchestrator job.A task-capable
tools/calldeclares the extension per request; the server decides whether to answer synchronously or with a durable task handle, and the caller pollstasks/getuntil the task is terminal.API
Each method has a sync and an
_asyncform:call_toolMcpToolCallOutcome(resultortask)get_taskwait_for_taskpollIntervalMs, with an optional timeoutcall_tool_and_waitCallToolResultcancel_taskModels live in
orchestrator/mcp_tasks.py:McpTaskStatus,McpTask,McpToolCallOutcome, and the errorsMcpToolCallError/McpTaskFailedError/McpTaskCancelledError/McpTaskInputRequiredError.McpTaskInputRequiredErroris the one status that is terminal for a waiter without being terminal per spec:input_requiredmeans the task is parked on an elicitation, andwait_for_taskhas no way to answer one. Polling on would mean polling until the caller's timeout, or forever when there is none, so the wait stops and the handle rides on the error for a caller that can answer it.Notes for reviewers
_mcp_rpc_envelopesends the per-request_meta["io.modelcontextprotocol/clientCapabilities"]declaration plus theMCP-Protocol-Version/Mcp-Method/Mcp-Nameheaders;_parse_mcp_envelopeaccepts both a JSON body and an SSE frame.McpTask.server_urlis client-only state (which endpoint minted the handle) and is excluded from the wire, so a task can be polled without re-resolving the server.ttlMs/pollIntervalMs, flatCreateTaskResultkeyed byresultType: "task"). The SDK's ownmcp.types.Taskstill carries the superseded SEP-1686 names (ttl/pollInterval) and cannot validate this wire — see typescript-sdk#2782, which lands the same flat shape.cancel_taskif that is not wanted.What gets re-sent, and what does not
tools/callstarts an Orchestrator 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 the job, and re-sending then runs the tool twice. Each request therefore picks its own policy (ResendPolicy):tools/callconnect-onlytasks/getneverplatformHow a wait handles a failed poll
timeoutis a hard deadline: eachtasks/getis 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 — bounding it only by the remaining budget made a long timeout less resilient than no timeout at all, since 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 anything that looks like the answer went missing: any transport failure, any 5xx (not just the platform's retryable subset), and a JSON-RPC internal error, which is the same thing arriving inside a 200. It honours
Retry-Afterand backs off between consecutive failures. A 4xx other than 408/429, and any other JSON-RPC code, are answers rather than mishaps and reach the caller at once. Only a failure landing after the deadline becomesTimeoutError.Tests
packages/uipath-platform/tests/services/test_mcp_tasks.py— 66 pytest-httpx tests: both answer shapes, polling to completion, every terminal state plusinput_required, the deadline (before the sleep, after the sleep, and inside the request), the per-poll cap, each resend policy's send count, the transient/non-transient split on a poll, theRetry-Afterfloor and the interval floor, the header encoding round-trip, SSE framing, and what a task handle refuses to accept from the wire. Sync and async paths are covered separately.ruff,ruff formatandmypyclean; the fulluipath-platformsuite passes.The server-side half of this is already merged.
Known limits
secretis static for the life of the service, so a wait longer than the token's lifetime will fail on a non-retryable 401 and lose the handle. Out of scope here; it is a property ofBaseServiceauth, not of Tasks.uipath-langchain's) are independent by design — different transports — but their semantics are deliberately aligned: same transient set, same interval floor, same per-poll cap, same "the deadline is what ends the wait".🤖 Generated with Claude Code