Skip to content

feat(platform): add MCP Tasks extension support to McpService - #2015

Merged
alessandromuresan merged 1 commit into
mainfrom
feat/mcp-tasks-client
Nov 24, 2026
Merged

alessandromuresan merged 1 commit into
mainfrom
feat/mcp-tasks-client

Conversation

@alessandromuresan

@alessandromuresan alessandromuresan commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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/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.

API

Each method has a sync and an _async form:

Method Purpose
call_tool Call a tool, accepting either shape; returns McpToolCallOutcome (result or task)
get_task Poll a task once
wait_for_task Poll to terminal, honouring the server's pollIntervalMs, with an optional timeout
call_tool_and_wait The convenience path: call, and if it came back as a task, wait for the final CallToolResult
cancel_task Signal cancellation

Models live in orchestrator/mcp_tasks.py: McpTaskStatus, McpTask, McpToolCallOutcome, and the errors McpToolCallError / McpTaskFailedError / McpTaskCancelledError / McpTaskInputRequiredError.

McpTaskInputRequiredError is the one status that is terminal for a waiter without being terminal per spec: input_required means the task is parked on an elicitation, and wait_for_task has 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

  • Protocol era. The extension exists only under the stateless 2026-07-28 revision, so _mcp_rpc_envelope sends the per-request _meta["io.modelcontextprotocol/clientCapabilities"] declaration plus the MCP-Protocol-Version / Mcp-Method / Mcp-Name headers; _parse_mcp_envelope accepts both a JSON body and an SSE frame.
  • McpTask.server_url is 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.
  • The task id is opaque. The server mints a self-contained handle; this client never inspects or parses it, and treats it as a capability -- whoever holds it can read the task's result -- so it is shortened in messages and logs.
  • Wire shape. The models mirror the ext-tasks wire (ttlMs/pollIntervalMs, flat CreateTaskResult keyed by resultType: "task"). The SDK's own mcp.types.Task still carries the superseded SEP-1686 names (ttl/pollInterval) and cannot validate this wire — see typescript-sdk#2782, which lands the same flat shape.
  • On a timeout the task keeps running server-side and its id stays valid; call cancel_task if that is not wanted.

What gets re-sent, and what does not

tools/call starts 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):

Request Policy Why
tools/call connect-only A failed connect, connect timeout or pool timeout never put the request on the wire; nothing else is re-sent
tasks/get never The poll loop is the retry, on the task's own cadence and inside the deadline
everything else platform The service-wide policy, unchanged

How a wait handles a failed poll

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 — 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-After and 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 becomes TimeoutError.

Tests

packages/uipath-platform/tests/services/test_mcp_tasks.py — 66 pytest-httpx tests: both answer shapes, polling to completion, every terminal state plus input_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, the Retry-After floor 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 format and mypy clean; the full uipath-platform suite passes.

The server-side half of this is already merged.

Known limits

  • The configured secret is 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 of BaseService auth, not of Tasks.
  • The two poll loops (this one and 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

Copilot AI balanced review requested due to automatic review settings November 23, 2026 10:25
@github-actions github-actions Bot added test:uipath-langchain Triggers tests in the uipath-langchain-python repository test:uipath-integrations labels Nov 23, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment on lines +437 to +438
time.sleep(self._poll_delay_seconds(snapshot, deadline, timeout))
snapshot = self.get_task(snapshot)
Comment on lines +463 to +472
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)
Comment on lines +666 to +681
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)
alessandromuresan added a commit that referenced this pull request Nov 23, 2026
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>
alessandromuresan added a commit that referenced this pull request Nov 23, 2026
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>
alessandromuresan added a commit that referenced this pull request Nov 24, 2026
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>
alessandromuresan added a commit that referenced this pull request Nov 24, 2026
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>
alessandromuresan added a commit that referenced this pull request Nov 24, 2026
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>
alessandromuresan added a commit that referenced this pull request Nov 24, 2026
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>
@github-actions

Copy link
Copy Markdown

🚨 Heads up: uipath-langchain cross-tests are FAILING 🚨

Your changes may break the uipath-langchain-python integration.

⚠️ These checks are NOT enforced by branch protection rules. Please review the failures before merging.

🔍 Inspect the failed run →

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>
@github-actions

Copy link
Copy Markdown

🚨 Heads up: uipath-integrations cross-tests are FAILING 🚨

Your changes may break one or more integrations in uipath-integrations-python:

  • uipath-openai-agents
  • uipath-google-adk
  • uipath-agent-framework
  • uipath-llamaindex
  • uipath-pydantic-ai

⚠️ These checks are NOT enforced by branch protection rules. Please review the failures before merging.

🔍 Inspect the failed run →

@sonarqubecloud

Copy link
Copy Markdown

@alessandromuresan
alessandromuresan merged commit 6cc9d7c into main Nov 24, 2026
189 of 192 checks passed
@alessandromuresan
alessandromuresan deleted the feat/mcp-tasks-client branch November 24, 2026 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:uipath-integrations test:uipath-langchain Triggers tests in the uipath-langchain-python repository

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants