Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/uipath-platform/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath-platform"
version = "0.3.21"
version = "0.3.22"
description = "HTTP client library for programmatic access to UiPath Platform"
readme = { file = "README.md", content-type = "text/markdown" }
requires-python = ">=3.11"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
from .mcp import McpServer, McpServerStatus, McpServerType
from .mcp_tasks import (
McpTask,
McpTaskApiTrigger,
McpTaskCancelledError,
McpTaskFailedError,
McpTaskInputRequiredError,
McpTaskJob,
McpTaskStatus,
McpTaskWatch,
McpToolCallError,
McpToolCallOutcome,
)
Expand Down Expand Up @@ -75,7 +77,9 @@
"McpTaskCancelledError",
"McpTaskFailedError",
"McpTaskInputRequiredError",
"McpTaskApiTrigger",
"McpTaskJob",
"McpTaskWatch",
"McpTaskStatus",
"McpToolCallError",
"McpToolCallOutcome",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import json
import random
import time
from typing import Any, Callable, List, Literal, Optional, cast
from typing import Any, Callable, List, Literal, Optional, Sequence, cast
from urllib.parse import quote

import httpx
Expand All @@ -30,6 +30,9 @@
MCP_TASK_RESULT_TYPE,
MCP_TASKS_EXTENSION_ID,
MCP_TASKS_PROTOCOL_VERSION,
MCP_UIPATH_TASK_API_TRIGGER,
MCP_UIPATH_TASK_JOB_TRIGGER,
MCP_UIPATH_TASK_META_KEY,
MCP_UIPATH_TASKS_CAPABILITY,
MCP_UIPATH_TASKS_EXTENSION_ID,
McpTask,
Expand Down Expand Up @@ -131,6 +134,9 @@ def _encode_header_value(value: str) -> str:
#: whose retry is the poll loop itself.
ResendPolicy = Literal["platform", "connect-only", "never"]

# What a request that asks for a watch declares: it can suspend on either kind.
_WATCH_TRIGGER_TYPES = (MCP_UIPATH_TASK_JOB_TRIGGER, MCP_UIPATH_TASK_API_TRIGGER)


class McpService(FolderContext, BaseService):
"""Service for managing MCP (Model Context Protocol) servers in UiPath.
Expand Down Expand Up @@ -383,6 +389,7 @@ def call_tool(
arguments: Optional[dict[str, Any]] = None,
*,
folder_path: str | None = None,
resume_trigger_types: Optional[Sequence[str]] = None,
) -> McpToolCallOutcome:
"""Call a tool on an MCP server, accepting a task handle for long-running calls.

Expand All @@ -394,6 +401,11 @@ def call_tool(
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.
resume_trigger_types (Optional[Sequence[str]]): The resume-trigger
kinds the caller can suspend on, declared to the server.
Defaults to ``["Job"]``. A caller that can also suspend through
a watch (``watch_task``) passes ``["Job", "Api"]``, and a task a
Remote server runs then carries ``api_trigger``.

Returns:
McpToolCallOutcome: Either the plain CallToolResult (``result``)
Expand All @@ -409,6 +421,7 @@ def call_tool(
{"name": tool_name, "arguments": arguments or {}},
routing_name=tool_name,
resend="connect-only",
resume_trigger_types=resume_trigger_types,
)
return self._outcome_from_result(result, server_url)

Expand All @@ -420,6 +433,7 @@ async def call_tool_async(
arguments: Optional[dict[str, Any]] = None,
*,
folder_path: str | None = None,
resume_trigger_types: Optional[Sequence[str]] = None,
) -> McpToolCallOutcome:
"""Asynchronously call a tool on an MCP server, accepting a task handle.

Expand All @@ -428,6 +442,11 @@ async def call_tool_async(
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.
resume_trigger_types (Optional[Sequence[str]]): The resume-trigger
kinds the caller can suspend on, declared to the server.
Defaults to ``["Job"]``. A caller that can also suspend through
a watch (``watch_task``) passes ``["Job", "Api"]``, and a task a
Remote server runs then carries ``api_trigger``.

Returns:
McpToolCallOutcome: Either the plain CallToolResult (``result``)
Expand All @@ -443,6 +462,7 @@ async def call_tool_async(
{"name": tool_name, "arguments": arguments or {}},
routing_name=tool_name,
resend="connect-only",
resume_trigger_types=resume_trigger_types,
)
return self._outcome_from_result(result, server_url)

Expand Down Expand Up @@ -482,6 +502,74 @@ async def get_task_async(self, task: McpTask) -> McpTask:
)
return self._task_from_result(result, server_url)

@staticmethod
def _watch_request(job_key: str, folder_key: str) -> dict[str, Any]:
return {
MCP_UIPATH_TASK_META_KEY: {
"watch": {"jobKey": job_key, "folderKey": folder_key}
}
}

@traced(name="mcp_watch_task", run_type="uipath")
def watch_task(self, task: McpTask, *, job_key: str, folder_key: str) -> McpTask:
"""Poll an MCP task once and ask the server to watch it for a job.

For a task a Remote MCP server runs (``task.api_trigger``): the server
watches the task and wakes the Orchestrator job named here through the
API trigger it suspended on. The reply is the task as ``get_task``
returns it; when the task is still working and a watch was started,
``watch`` on it names the watch and how long it runs.

Args:
task (McpTask): A handle returned by ``call_tool`` (or an earlier poll).
job_key (str): The caller's own job, the one to wake.
folder_key (str): The folder that job runs in.

Returns:
McpTask: The fresh task snapshot.

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},
resume_trigger_types=_WATCH_TRIGGER_TYPES,
request_meta=self._watch_request(job_key, folder_key),
)
return self._task_from_result(result, server_url)

@traced(name="mcp_watch_task", run_type="uipath")
async def watch_task_async(
self, task: McpTask, *, job_key: str, folder_key: str
) -> McpTask:
"""Asynchronously poll an MCP task once and ask the server to watch it.

See ``watch_task``.

Args:
task (McpTask): A handle returned by ``call_tool_async`` (or an earlier poll).
job_key (str): The caller's own job, the one to wake.
folder_key (str): The folder that job runs in.

Returns:
McpTask: The fresh task snapshot.

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},
resume_trigger_types=_WATCH_TRIGGER_TYPES,
request_meta=self._watch_request(job_key, folder_key),
)
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.
Expand Down Expand Up @@ -962,12 +1050,23 @@ async def _get_task_within_async(
return self._task_from_result(result, server_url)

def _mcp_rpc_envelope(
self, method: str, params: dict[str, Any], routing_name: Optional[str]
self,
method: str,
params: dict[str, Any],
routing_name: Optional[str],
resume_trigger_types: Optional[Sequence[str]] = None,
request_meta: Optional[dict[str, Any]] = None,
) -> tuple[dict[str, Any], dict[str, str]]:
self._mcp_request_id = getattr(self, "_mcp_request_id", 0) + 1
uipath_tasks: dict[str, Any] = (
MCP_UIPATH_TASKS_CAPABILITY
if resume_trigger_types is None
else {"resumeTriggerTypes": list(resume_trigger_types)}
)
params = {
**params,
"_meta": {
**(request_meta or {}),
"io.modelcontextprotocol/protocolVersion": MCP_TASKS_PROTOCOL_VERSION,
"io.modelcontextprotocol/clientInfo": {
"name": "UiPath.Python.Sdk",
Expand All @@ -981,7 +1080,7 @@ def _mcp_rpc_envelope(
# the entry.
"extensions": {
MCP_TASKS_EXTENSION_ID: {},
MCP_UIPATH_TASKS_EXTENSION_ID: MCP_UIPATH_TASKS_CAPABILITY,
MCP_UIPATH_TASKS_EXTENSION_ID: uipath_tasks,
},
},
},
Expand Down Expand Up @@ -1012,8 +1111,12 @@ def _send_mcp(
routing_name: Optional[str] = None,
request_timeout: Optional[float] = None,
resend: ResendPolicy = "platform",
resume_trigger_types: Optional[Sequence[str]] = None,
request_meta: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
body, headers = self._mcp_rpc_envelope(method, params, routing_name)
body, headers = self._mcp_rpc_envelope(
method, params, routing_name, resume_trigger_types, request_meta
)
extra: dict[str, Any] = (
{} if request_timeout is None else {"timeout": request_timeout}
)
Expand All @@ -1039,8 +1142,12 @@ async def _send_mcp_async(
routing_name: Optional[str] = None,
request_timeout: Optional[float] = None,
resend: ResendPolicy = "platform",
resume_trigger_types: Optional[Sequence[str]] = None,
request_meta: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
body, headers = self._mcp_rpc_envelope(method, params, routing_name)
body, headers = self._mcp_rpc_envelope(
method, params, routing_name, resume_trigger_types, request_meta
)
extra: dict[str, Any] = (
{} if request_timeout is None else {"timeout": request_timeout}
)
Expand Down
114 changes: 114 additions & 0 deletions packages/uipath-platform/src/uipath/platform/orchestrator/mcp_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ def task_ref(task_id: str) -> str:
#: The resume-trigger kind this client can suspend on. The server may name
#: other kinds later; a task annotated with one of those is polled.
MCP_UIPATH_TASK_JOB_TRIGGER = "Job"
#: The resume-trigger kind for a task the server does not run itself (a Remote
#: MCP server's own task): the caller suspends on an API trigger, which the
#: server fires once the task has ended. Declared only by a caller that asks
#: for it (``call_tool(resume_trigger_types=...)``, ``watch_task``).
MCP_UIPATH_TASK_API_TRIGGER = "Api"
#: This client's ``com.uipath/tasks`` declaration: the trigger kinds it handles.
MCP_UIPATH_TASKS_CAPABILITY: dict[str, Any] = {
"resumeTriggerTypes": [MCP_UIPATH_TASK_JOB_TRIGGER]
Expand Down Expand Up @@ -77,6 +82,66 @@ def is_terminal(self) -> bool:
)


class McpTaskApiTrigger(BaseModel):
"""That a task can be suspended on through a watch (``McpTask.api_trigger``).

A task a Remote MCP server runs has no Orchestrator job behind it. The
server (AgentHub) annotates it with an ``Api`` resume trigger instead: a
caller that is itself a job can ask for a watch (``McpService.watch_task``)
and suspend on an API trigger the server fires when the task has ended.
"""

model_config = ConfigDict(populate_by_name=True, extra="ignore")

suspend_after_ms: Optional[int] = Field(default=None, alias="suspendAfterMs")

@field_validator("suspend_after_ms", mode="before")
@classmethod
def _is_a_duration(cls, value: Any) -> Optional[int]:
return _whole_milliseconds(value)


class McpTaskWatch(BaseModel):
"""A watch the server started on a task (``McpTask.watch``).

Attributes:
watch_id: Names the watch. The caller suspends on an API trigger whose
request is ``{"com.uipath/task": {"watchId": watch_id}}``; the
server delivers only to a trigger that carries it.
expires_in_ms: How long the watch runs. The caller should also suspend
on a timer for this long, so it wakes whether or not it is woken.
"""

model_config = ConfigDict(populate_by_name=True, extra="ignore")

watch_id: str = Field(alias="id")
expires_in_ms: int = Field(alias="expiresInMs")

@field_validator("watch_id")
@classmethod
def _is_a_guid(cls, value: str) -> str:
return str(uuid.UUID(value))

@field_validator("expires_in_ms", mode="before")
@classmethod
def _is_a_positive_duration(cls, value: Any) -> int:
milliseconds = _whole_milliseconds(value)
if milliseconds is None or milliseconds <= 0:
raise ValueError("expiresInMs must be a positive number of milliseconds")
return milliseconds


def _whole_milliseconds(value: Any) -> Optional[int]:
"""A whole, non-negative number of milliseconds, else ``None``."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
if isinstance(value, float) and not value.is_integer():
return None
if value < 0:
return None
return int(value)


class McpTaskJob(BaseModel):
"""The Orchestrator job behind a task, from its ``com.uipath/task`` annotation.

Expand Down Expand Up @@ -228,6 +293,55 @@ def job(self) -> Optional[McpTaskJob]:
except ValueError:
return None

def _annotation(self, trigger_type: str) -> Optional[dict[str, Any]]:
"""The ``com.uipath/task`` annotation of a working task, at this version."""
if isinstance(self.status, McpTaskStatus) and self.status.is_terminal:
return None
meta = (self.model_extra or {}).get("_meta")
annotation = (
meta.get(MCP_UIPATH_TASK_META_KEY) if isinstance(meta, dict) else None
)
if not isinstance(annotation, dict):
return None
version = annotation.get("version")
if type(version) is not int or version != MCP_UIPATH_TASK_ANNOTATION_VERSION:
return None
trigger = annotation.get("resumeTrigger")
if not isinstance(trigger, dict) or trigger.get("triggerType") != trigger_type:
return None
return annotation

@property
def api_trigger(self) -> Optional[McpTaskApiTrigger]:
"""That this task can be suspended on through a watch, when it can.

``None`` for a task the server names a job for (``job``), for one with
no annotation, for a terminal one, and for an annotation this client
cannot read. The task is still pollable in every such case.
"""
annotation = self._annotation(MCP_UIPATH_TASK_API_TRIGGER)
if annotation is None:
return None
return McpTaskApiTrigger.model_validate(annotation)

@property
def watch(self) -> Optional[McpTaskWatch]:
"""The watch the server started on this task, from a ``watch_task`` reply.

``None`` when the reply names no watch, or one that cannot be used (an
id that is not a GUID, a lifetime that is not a positive number): the
caller keeps polling rather than suspend on a watch it cannot name or
time.
"""
annotation = self._annotation(MCP_UIPATH_TASK_API_TRIGGER)
watch = annotation.get("watch") if annotation is not None else None
if not isinstance(watch, dict):
return None
try:
return McpTaskWatch.model_validate(watch)
except ValueError:
return None

@field_validator("status", mode="before")
@classmethod
def _known_status_stays_typed(cls, value: Any) -> Any:
Expand Down
Loading
Loading