Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: workflow schedule management via MCP tools and `skyvern schedule` CLI (#5713)
Marc Kelechavae80fc40b8b1d
diff --git a/skyvern/cli/commands/__init__.py b/skyvern/cli/commands/__init__.pyindex 432eb22cf..51ff9cc2d 100644--- a/skyvern/cli/commands/__init__.py+++ b/skyvern/cli/commands/__init__.py@@ -37,6 +37,12 @@ register_lazy_command("Read and update organization settings (max_steps_per_run, webhook URL, retries, artifact URL expiry).",)register_lazy_command("workflow", "skyvern.cli.workflow", "workflow_app", "Workflow management commands.")+register_lazy_command(+ "schedule",+ "skyvern.cli.schedule_command",+ "schedule_app",+ "Manage workflow schedules (list, create, update, enable/disable, delete).",+)register_lazy_command("tasks", "skyvern.cli.tasks", "tasks_app", "Task management commands.")register_lazy_command("credentials",diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 154777951..3bcdace79 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -71,6 +71,16 @@ from .org import ()from .prompts import build_workflow, debug_automation, extract_data, qa_testfrom .response import size_capped+from .schedule import (+ skyvern_schedule_create,+ skyvern_schedule_delete,+ skyvern_schedule_disable,+ skyvern_schedule_enable,+ skyvern_schedule_get,+ skyvern_schedule_list,+ skyvern_schedule_list_for_workflow,+ skyvern_schedule_update,+)from .scripts import (skyvern_script_deploy,skyvern_script_fallback_episodes,@@ -167,7 +177,8 @@ static JSON/XML fetches, or generic web search.| Multi-step (simple, fast) | "fill the form and submit" | skyvern_observe + skyvern_execute | 0 Skyvern LLM | A11y tree + YOUR LLM plans from refs + batched primitives. Fast, cheap. || Throwaway autonomous trial | "try this once", "see if this works" | skyvern_run_task | Higher | One-off autonomous agent for exploratory work. Do not use for reusable or multi-page production automations. || Multi-step (complex) | "navigate a multi-page wizard" | skyvern_workflow_create (multi-block) | N LLM + screenshots | Build a workflow with one navigation block per step. Each block gets visual reasoning + verification. |-| Repeated/production | "automate this weekly", "run every Monday", "schedule", "recurring" | skyvern_workflow_create + run | Varies | Caching converts AI runs into deterministic scripts over time (10-100x faster on repeat). |+| Reusable workflow | "automate this", "wizard", "multi-step", "production" | skyvern_workflow_create | Varies | Caching converts AI runs into deterministic scripts over time (10-100x faster on repeat). |+| Recurring schedule | "every Monday", "weekly", "schedule", "recurring", "cron" | skyvern_schedule_create (after the workflow exists) | API call | Server-side cron registration; route returns 501 if schedules are disabled in this build. |## Decision Rules (highest precedence)@@ -175,7 +186,7 @@ static JSON/XML fetches, or generic web search.2. If you only need a yes/no answer, use skyvern_validate -- not skyvern_extract or skyvern_act.3. If the work stays on one page and the UI is standard, prefer skyvern_observe + skyvern_execute.4. If the user says "try this once", "see if this works", or clearly wants a one-off exploratory trial, use skyvern_run_task.-5. If the task spans multiple pages and is meant to be reusable, scheduled, repeatable, or explicitly "set up" as automation, use skyvern_workflow_create.+5. If the task spans multiple pages and is meant to be reusable/repeatable, use skyvern_workflow_create. To run it on a recurring cadence, follow up with skyvern_schedule_create against the resulting workflow_permanent_id.6. Never type passwords. Always use skyvern_login with stored credentials.## Quick Reference (one example per classification)@@ -211,6 +222,7 @@ file_upload, find, navigate, screenshot, evaluate**Tier 3 — Management** (no session needed):- **Sessions:** browser_session_create/close/list/get/connect- **Workflows:** workflow_create/run/status/get/list/update/delete/cancel/update_folder+- **Schedules:** schedule_list/list_for_workflow/get/create/update/enable/disable/delete- **Scripts:** script_list_for_workflow, script_get_code, script_versions, script_fallback_episodes, script_deploy- **Credentials:** credential_list/get/delete- **Folders/Blocks:** folder_list/get/create/update/delete, block_schema, block_validate@@ -222,7 +234,8 @@ Precision tools support intent (AI), selector (deterministic), or hybrid (both)- login requires a session AND a credential_id from credential_list.- file_upload requires a navigated page with an upload element.- console_messages and network_requests capture events from session start — call anytime.-- Workflow, credential, script, folder, and block tools do NOT need a browser session.+- Workflow, schedule, credential, script, folder, and block tools do NOT need a browser session.+- schedule_create requires an existing workflow_permanent_id — call workflow_list or workflow_create first.## Session Lifecycle@@ -392,6 +405,16 @@ mcp.tool(tags={"workflow"}, annotations=_web_dest("Run Workflow"))(skyvern_workfmcp.tool(tags={"workflow"}, annotations=_ro("Get Workflow Run Status"))(skyvern_workflow_status)mcp.tool(tags={"workflow"}, annotations=_dest("Cancel Workflow Run"))(skyvern_workflow_cancel)+# -- Schedule management (no browser needed) --+mcp.tool(tags={"schedule"}, annotations=_ro("List Workflow Schedules"))(skyvern_schedule_list)+mcp.tool(tags={"schedule"}, annotations=_ro("List Schedules for a Workflow"))(skyvern_schedule_list_for_workflow)+mcp.tool(tags={"schedule"}, annotations=_ro("Get Workflow Schedule"))(skyvern_schedule_get)+mcp.tool(tags={"schedule"}, annotations=_mut("Create Workflow Schedule"))(skyvern_schedule_create)+mcp.tool(tags={"schedule"}, annotations=_mut("Update Workflow Schedule"))(skyvern_schedule_update)+mcp.tool(tags={"schedule"}, annotations=_mut("Enable Workflow Schedule"))(skyvern_schedule_enable)+mcp.tool(tags={"schedule"}, annotations=_mut("Disable Workflow Schedule"))(skyvern_schedule_disable)+mcp.tool(tags={"schedule"}, annotations=_dest("Delete Workflow Schedule"))(skyvern_schedule_delete)+# -- Script/caching tools (no browser needed) --mcp.tool(tags={"script"}, annotations=_ro("List Workflow Scripts"))(skyvern_script_list_for_workflow)mcp.tool(tags={"script"}, annotations=_ro("Get Script Code"))(size_capped(skyvern_script_get_code))@@ -493,6 +516,15 @@ __all__ = ["skyvern_workflow_run","skyvern_workflow_status","skyvern_workflow_cancel",+ # Schedule management+ "skyvern_schedule_list",+ "skyvern_schedule_list_for_workflow",+ "skyvern_schedule_get",+ "skyvern_schedule_create",+ "skyvern_schedule_update",+ "skyvern_schedule_enable",+ "skyvern_schedule_disable",+ "skyvern_schedule_delete",# Script/caching"skyvern_script_list_for_workflow","skyvern_script_get_code",diff --git a/skyvern/cli/mcp_tools/_validation.py b/skyvern/cli/mcp_tools/_validation.pyindex 6308ece71..473cb338b 100644--- a/skyvern/cli/mcp_tools/_validation.py+++ b/skyvern/cli/mcp_tools/_validation.py@@ -77,6 +77,30 @@ def validate_run_id(run_id: str, action: str) -> dict[str, Any] | None:return None+def validate_schedule_id(workflow_schedule_id: str, action: str) -> dict[str, Any] | None:+ if "/" in workflow_schedule_id or "\\" in workflow_schedule_id:+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ "workflow_schedule_id must not contain path separators",+ "Provide a valid schedule ID (starts with wfs_)",+ ),+ )+ if not workflow_schedule_id.startswith("wfs_"):+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Invalid workflow_schedule_id format: {workflow_schedule_id!r}",+ "Schedule IDs start with wfs_. Use skyvern_schedule_list to find valid IDs.",+ ),+ )+ return None++def validate_script_id(script_id: str, action: str) -> dict[str, Any] | None:if "/" in script_id or "\\" in script_id:return make_result(diff --git a/skyvern/cli/mcp_tools/schedule.py b/skyvern/cli/mcp_tools/schedule.pynew file mode 100644index 000000000..5660d02fe--- /dev/null+++ b/skyvern/cli/mcp_tools/schedule.py@@ -0,0 +1,577 @@+"""Skyvern MCP workflow-schedule tools — CRUD + enable/disable via ``client.schedules.*``."""++from __future__ import annotations++from typing import Annotated, Any++import structlog+from pydantic import Field++from skyvern.client.core.api_error import ApiError++from ._common import ErrorCode, Timer, make_error, make_result+from ._session import get_skyvern+from ._validation import validate_schedule_id, validate_workflow_id++LOG = structlog.get_logger()+++def _serialize_schedule(s: Any) -> dict[str, Any]:+ return {+ "workflow_schedule_id": s.workflow_schedule_id,+ "organization_id": s.organization_id,+ "workflow_permanent_id": s.workflow_permanent_id,+ "cron_expression": s.cron_expression,+ "timezone": s.timezone,+ "enabled": s.enabled,+ "parameters": s.parameters,+ # Re-project the SDK's internal handle to a backend-agnostic public key.+ "backend_schedule_id": getattr(s, "temporal_schedule_id", None),+ "name": s.name,+ "description": s.description,+ "created_at": s.created_at.isoformat() if s.created_at else None,+ "modified_at": s.modified_at.isoformat() if s.modified_at else None,+ }+++def _serialize_schedule_response(resp: Any) -> dict[str, Any]:+ return {+ "schedule": _serialize_schedule(resp.schedule),+ "next_runs": [r.isoformat() for r in (resp.next_runs or [])],+ }+++def _serialize_org_schedule_item(item: Any) -> dict[str, Any]:+ # Intentionally omits backend_schedule_id — see OrganizationScheduleItem schema.+ return {+ "workflow_schedule_id": item.workflow_schedule_id,+ "organization_id": item.organization_id,+ "workflow_permanent_id": item.workflow_permanent_id,+ "workflow_title": item.workflow_title,+ "cron_expression": item.cron_expression,+ "timezone": item.timezone,+ "enabled": item.enabled,+ "parameters": item.parameters,+ "name": item.name,+ "description": item.description,+ "next_run": item.next_run.isoformat() if item.next_run else None,+ "created_at": item.created_at.isoformat() if item.created_at else None,+ "modified_at": item.modified_at.isoformat() if item.modified_at else None,+ }+++def _api_error(+ action: str, exc: Exception, timer: Timer, hint: str = "Check your API key and Skyvern connection"+) -> dict[str, Any]:+ return make_result(+ action,+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(ErrorCode.API_ERROR, str(exc), hint),+ )+++def _input_error(action: str, message: str, hint: str) -> dict[str, Any]:+ return make_result(+ action,+ ok=False,+ error=make_error(ErrorCode.INVALID_INPUT, message, hint),+ )+++async def skyvern_schedule_list(+ page: Annotated[int, Field(description="Page number (1-based)", ge=1)] = 1,+ page_size: Annotated[int, Field(description="Results per page", ge=1, le=100)] = 10,+ status: Annotated[str | None, Field(description="Filter: 'active' or 'paused'")] = None,+ search: Annotated[str | None, Field(description="Search by workflow title or schedule name")] = None,+) -> dict[str, Any]:+ """List all workflow schedules in the organization.++ The org-wide list intentionally omits ``backend_schedule_id`` to match the+ server's ``OrganizationScheduleItem`` contract; call ``skyvern_schedule_get``+ when you need the execution-backend handle. Returns 501 if workflow+ schedules are disabled in this Skyvern build. Status filter values are+ validated server-side.+ """+ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.list_all(+ page=page,+ page_size=page_size,+ status=status, # type: ignore[arg-type]+ search=search,+ )+ timer.mark("sdk")+ except Exception as e:+ return _api_error("skyvern_schedule_list", e, timer)++ return make_result(+ "skyvern_schedule_list",+ data={+ "schedules": [_serialize_org_schedule_item(s) for s in (resp.schedules or [])],+ "total_count": resp.total_count,+ "page": resp.page,+ "page_size": resp.page_size,+ },+ timing_ms=timer.timing_ms,+ )+++async def skyvern_schedule_list_for_workflow(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+) -> dict[str, Any]:+ """List schedules for a single workflow."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_list_for_workflow"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.list(workflow_permanent_id)+ timer.mark("sdk")+ except Exception as e:+ return _api_error("skyvern_schedule_list_for_workflow", e, timer)++ return make_result(+ "skyvern_schedule_list_for_workflow",+ data={"schedules": [_serialize_schedule(s) for s in (resp.schedules or [])]},+ timing_ms=timer.timing_ms,+ )+++async def skyvern_schedule_get(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+) -> dict[str, Any]:+ """Get a single workflow schedule by id."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_get"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_get"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.get(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk")+ except ApiError as e:+ if e.status_code == 404:+ return make_result(+ "skyvern_schedule_get",+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Schedule {workflow_schedule_id!r} not found",+ "Use skyvern_schedule_list to find valid schedule IDs.",+ ),+ )+ return _api_error("skyvern_schedule_get", e, timer)+ except Exception as e:+ return _api_error("skyvern_schedule_get", e, timer)++ return make_result(+ "skyvern_schedule_get",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )+++async def skyvern_schedule_create(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ cron_expression: Annotated[str, Field(description="Cron expression, e.g. '0 9 * * *'")],+ timezone: Annotated[str, Field(description="IANA timezone, e.g. 'UTC' or 'America/New_York'")],+ enabled: Annotated[bool, Field(description="Whether the schedule fires immediately. Defaults to True.")] = True,+ parameters: Annotated[+ dict[str, Any] | None,+ Field(description="Workflow input parameters keyed by parameter name."),+ ] = None,+ name: Annotated[str | None, Field(description="Human-readable schedule name.")] = None,+ description: Annotated[str | None, Field(description="Optional description.")] = None,+) -> dict[str, Any]:+ """Create a recurring schedule for an existing workflow.++ Cron expression and timezone are validated server-side; a 400 is surfaced+ verbatim. Returns 501 if workflow schedules are disabled in this build.+ """+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_create"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.create(+ workflow_permanent_id,+ cron_expression=cron_expression,+ timezone=timezone,+ enabled=enabled,+ parameters=parameters,+ name=name,+ description=description,+ )+ timer.mark("sdk")+ except ApiError as e:+ if e.status_code == 404:+ return make_result(+ "skyvern_schedule_create",+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Workflow {workflow_permanent_id!r} not found",+ "Use skyvern_workflow_list to find valid workflow IDs.",+ ),+ )+ return _api_error(+ "skyvern_schedule_create", e, timer, hint="Check cron expression, timezone, and parameters."+ )+ except Exception as e:+ return _api_error(+ "skyvern_schedule_create", e, timer, hint="Check cron expression, timezone, and parameters."+ )++ return make_result(+ "skyvern_schedule_create",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )+++def _check_update_mutex(+ parameters: dict[str, Any] | None,+ clear_parameters: bool,+ name: str | None,+ clear_name: bool,+ description: str | None,+ clear_description: bool,+) -> dict[str, Any] | None:+ conflicts: list[str] = []+ if parameters is not None and clear_parameters:+ conflicts.append("parameters")+ if name is not None and clear_name:+ conflicts.append("name")+ if description is not None and clear_description:+ conflicts.append("description")+ if conflicts:+ return _input_error(+ "skyvern_schedule_update",+ f"Cannot set and clear the same field at once: {', '.join(conflicts)}",+ "Pass either a value OR the clear flag, not both.",+ )+ return None+++def _check_update_exact_completeness(+ cron_expression: str | None,+ timezone: str | None,+ enabled: bool | None,+ parameters: dict[str, Any] | None,+ clear_parameters: bool,+ name: str | None,+ clear_name: bool,+ description: str | None,+ clear_description: bool,+) -> dict[str, Any] | None:+ """In ``exact=True`` mode, every replacement field must be specified explicitly.++ Without this guard, a body sent with only cron+timezone would inherit the+ route schema defaults (``enabled=True``, ``parameters/name/description=None``)+ and silently flip a paused schedule active or wipe metadata.+ """+ missing: list[str] = []+ if cron_expression is None:+ missing.append("cron_expression")+ if timezone is None:+ missing.append("timezone")+ if enabled is None:+ missing.append("enabled")+ if parameters is None and not clear_parameters:+ missing.append("parameters or clear_parameters")+ if name is None and not clear_name:+ missing.append("name or clear_name")+ if description is None and not clear_description:+ missing.append("description or clear_description")+ if missing:+ return _input_error(+ "skyvern_schedule_update",+ f"exact=True requires explicit values for: {', '.join(missing)}",+ "Pass each missing field, or set the corresponding clear flag for nullable fields.",+ )+ return None+++async def skyvern_schedule_update(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+ cron_expression: Annotated[str | None, Field(description="New cron expression.")] = None,+ timezone: Annotated[str | None, Field(description="New IANA timezone.")] = None,+ enabled: Annotated[bool | None, Field(description="New enabled flag.")] = None,+ parameters: Annotated[dict[str, Any] | None, Field(description="New workflow input parameters.")] = None,+ clear_parameters: Annotated[bool, Field(description="Set parameters to null on the server.")] = False,+ name: Annotated[str | None, Field(description="New schedule name.")] = None,+ clear_name: Annotated[bool, Field(description="Set name to null on the server.")] = False,+ description: Annotated[str | None, Field(description="New description.")] = None,+ clear_description: Annotated[bool, Field(description="Set description to null on the server.")] = False,+ exact: Annotated[+ bool,+ Field(description="If True, skip fetch+merge and require every replacement field explicitly."),+ ] = False,+) -> dict[str, Any]:+ """Update a workflow schedule.++ Two modes:+ - **Partial (default, ``exact=False``)**: GET the schedule, merge supplied+ fields and clear flags, then PUT the full body. Empty patches are+ rejected before any I/O. Note: read-modify-write race window is logged+ via ``modified_at`` of the snapshot.+ - **Exact (``exact=True``)**: caller must supply every replacement field;+ no GET. Prevents accidental ``enabled=True`` / clearing of metadata via+ the route's schema defaults.++ Cannot pass a value AND the corresponding clear flag for the same field.+ """+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_update"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_update"):+ return err++ if err := _check_update_mutex(parameters, clear_parameters, name, clear_name, description, clear_description):+ return err++ any_value_set = any(v is not None for v in (cron_expression, timezone, enabled, parameters, name, description))+ any_clear_set = any((clear_parameters, clear_name, clear_description))+ if not exact and not any_value_set and not any_clear_set:+ return _input_error(+ "skyvern_schedule_update",+ "Empty update — no fields supplied.",+ "Pass at least one field to update, or set exact=true to do a full replace.",+ )++ # Single SDK client for both the optional GET and the PUT — sharing one+ # instance avoids any auth-context drift if get_skyvern() ever returns+ # a fresh client per call.+ skyvern = get_skyvern()++ # One Timer covers the whole operation so timing_ms reports total wall+ # time including the partial-mode fetch (marked sdk_fetch) plus the PUT+ # (marked sdk_update). Timer auto-records "total" on exit.+ with Timer() as timer:+ if exact:+ if err := _check_update_exact_completeness(+ cron_expression,+ timezone,+ enabled,+ parameters,+ clear_parameters,+ name,+ clear_name,+ description,+ clear_description,+ ):+ return err+ # In exact mode, every field is supplied explicitly; clear flags map to None.+ body_cron = cron_expression+ body_tz = timezone+ body_enabled = enabled+ body_params = None if clear_parameters else parameters+ body_name = None if clear_name else name+ body_description = None if clear_description else description+ else:+ try:+ existing_resp = await skyvern.schedules.get(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk_fetch")+ except ApiError as e:+ if e.status_code == 404:+ return make_result(+ "skyvern_schedule_update",+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Schedule {workflow_schedule_id!r} not found",+ "Use skyvern_schedule_list to find valid schedule IDs.",+ ),+ )+ return _api_error("skyvern_schedule_update", e, timer)+ except Exception as e:+ return _api_error("skyvern_schedule_update", e, timer)++ existing = existing_resp.schedule+ # Log the snapshot's modified_at so an audit can reconstruct any window+ # clobbered by a concurrent writer. Callers wanting strict semantics+ # should pass exact=True (skips this fetch).+ LOG.info(+ "Workflow schedule fetch+merge snapshot",+ workflow_permanent_id=workflow_permanent_id,+ workflow_schedule_id=workflow_schedule_id,+ snapshot_modified_at=existing.modified_at.isoformat() if existing.modified_at else None,+ )++ body_cron = cron_expression if cron_expression is not None else existing.cron_expression+ body_tz = timezone if timezone is not None else existing.timezone+ body_enabled = enabled if enabled is not None else existing.enabled+ body_params = None if clear_parameters else (parameters if parameters is not None else existing.parameters)+ body_name = None if clear_name else (name if name is not None else existing.name)+ body_description = (+ None if clear_description else (description if description is not None else existing.description)+ )++ try:+ resp = await skyvern.schedules.update(+ workflow_permanent_id,+ workflow_schedule_id,+ cron_expression=body_cron,+ timezone=body_tz,+ enabled=body_enabled,+ parameters=body_params,+ name=body_name,+ description=body_description,+ )+ timer.mark("sdk_update")+ except ApiError as e:+ if e.status_code == 404:+ return make_result(+ "skyvern_schedule_update",+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Schedule {workflow_schedule_id!r} not found",+ "Use skyvern_schedule_list to find valid schedule IDs.",+ ),+ )+ return _api_error("skyvern_schedule_update", e, timer, hint="Check cron, timezone, and parameter shape.")+ except Exception as e:+ return _api_error("skyvern_schedule_update", e, timer, hint="Check cron, timezone, and parameter shape.")++ return make_result(+ "skyvern_schedule_update",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )+++def _not_found_404(action: str, workflow_schedule_id: str, timer: Timer) -> dict[str, Any]:+ return make_result(+ action,+ ok=False,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Workflow or schedule not found: {workflow_schedule_id!r}",+ "Use skyvern_schedule_list to find valid IDs.",+ ),+ )+++async def skyvern_schedule_enable(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+) -> dict[str, Any]:+ """Enable a paused workflow schedule."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_enable"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_enable"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.enable(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk")+ except ApiError as e:+ if e.status_code == 404:+ return _not_found_404("skyvern_schedule_enable", workflow_schedule_id, timer)+ return _api_error("skyvern_schedule_enable", e, timer)+ except Exception as e:+ return _api_error("skyvern_schedule_enable", e, timer)++ return make_result(+ "skyvern_schedule_enable",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )+++async def skyvern_schedule_disable(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+) -> dict[str, Any]:+ """Disable an active workflow schedule."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_disable"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_disable"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.disable(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk")+ except ApiError as e:+ if e.status_code == 404:+ return _not_found_404("skyvern_schedule_disable", workflow_schedule_id, timer)+ return _api_error("skyvern_schedule_disable", e, timer)+ except Exception as e:+ return _api_error("skyvern_schedule_disable", e, timer)++ return make_result(+ "skyvern_schedule_disable",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )+++async def skyvern_schedule_delete(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+ force: Annotated[+ bool,+ Field(description="Must be true to confirm deletion — prevents accidental deletes."),+ ] = False,+) -> dict[str, Any]:+ """Delete a workflow schedule. Irreversible — schedule stops firing immediately."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_delete"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_delete"):+ return err++ if not force:+ return _input_error(+ "skyvern_schedule_delete",+ f"Deletion of schedule {workflow_schedule_id!r} requires confirmation",+ "Set force=true to confirm deletion. This is irreversible — the schedule will stop firing immediately.",+ )++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ await skyvern.schedules.delete(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk")+ except Exception as e:+ return _api_error("skyvern_schedule_delete", e, timer)++ # Reaching this point means the SDK returned without raising — that is the+ # success signal. DeleteScheduleResponse.ok is informational only.+ return make_result(+ "skyvern_schedule_delete",+ data={+ "workflow_permanent_id": workflow_permanent_id,+ "workflow_schedule_id": workflow_schedule_id,+ "deleted": True,+ },+ timing_ms=timer.timing_ms,+ )+++__all__ = [+ "skyvern_schedule_create",+ "skyvern_schedule_delete",+ "skyvern_schedule_disable",+ "skyvern_schedule_enable",+ "skyvern_schedule_get",+ "skyvern_schedule_list",+ "skyvern_schedule_list_for_workflow",+ "skyvern_schedule_update",+]diff --git a/skyvern/cli/schedule_command.py b/skyvern/cli/schedule_command.pynew file mode 100644index 000000000..c42c3198b--- /dev/null+++ b/skyvern/cli/schedule_command.py@@ -0,0 +1,297 @@+"""Workflow-schedule CLI: ``skyvern schedule list | get | create | update | enable | disable | delete``."""++from __future__ import annotations++import json+from typing import Any++import typer+from click.core import ParameterSource+from dotenv import load_dotenv++from skyvern.config import settings+from skyvern.utils.env_paths import resolve_backend_env_path++from .commands._output import run_tool+from .mcp_tools.schedule import skyvern_schedule_create as tool_schedule_create+from .mcp_tools.schedule import skyvern_schedule_delete as tool_schedule_delete+from .mcp_tools.schedule import skyvern_schedule_disable as tool_schedule_disable+from .mcp_tools.schedule import skyvern_schedule_enable as tool_schedule_enable+from .mcp_tools.schedule import skyvern_schedule_get as tool_schedule_get+from .mcp_tools.schedule import skyvern_schedule_list as tool_schedule_list+from .mcp_tools.schedule import skyvern_schedule_list_for_workflow as tool_schedule_list_for_workflow+from .mcp_tools.schedule import skyvern_schedule_update as tool_schedule_update++schedule_app = typer.Typer(+ help="Manage workflow schedules (list, create, update, enable/disable, delete).",+ no_args_is_help=True,+)+++@schedule_app.callback()+def schedule_callback(+ api_key: str | None = typer.Option(+ None,+ "--api-key",+ envvar="SKYVERN_API_KEY",+ help="Skyvern API key.",+ ),+) -> None:+ load_dotenv(resolve_backend_env_path())+ if api_key:+ settings.SKYVERN_API_KEY = api_key+++def _parse_parameters(value: str | None) -> dict[str, Any] | None:+ if value is None:+ return None+ try:+ parsed = json.loads(value)+ except json.JSONDecodeError as e:+ raise typer.BadParameter(f"--parameters must be valid JSON: {e}") from e+ if not isinstance(parsed, dict):+ raise typer.BadParameter("--parameters must be a JSON object (dict).")+ return parsed+++@schedule_app.command("list")+def schedule_list(+ ctx: typer.Context,+ workflow_id: str | None = typer.Option(+ None,+ "--workflow-id",+ help=(+ "Filter to a single workflow_permanent_id (wpid_…). Omit for org-wide list. "+ "Per-workflow rows include backend_schedule_id; the org-wide list does not — fetch a single schedule with `get` for the backend handle."+ ),+ ),+ status: str | None = typer.Option(+ None,+ "--status",+ help="Filter: 'active' or 'paused'. (Org-wide list only.)",+ ),+ search: str | None = typer.Option(+ None, "--search", help="Search workflow title or schedule name. (Org-wide list only.)"+ ),+ page: int = typer.Option(1, "--page", min=1, help="Page number (1-based). (Org-wide list only.)"),+ page_size: int = typer.Option(10, "--page-size", min=1, max=100, help="Results per page. (Org-wide list only.)"),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """List schedules — org-wide by default, or per-workflow with --workflow-id.++ The per-workflow path is unpaginated and ignores --status/--search; passing+ those alongside --workflow-id is rejected so they don't get silently dropped.+ """+ if workflow_id is not None:+ # Click reports the source for each parameter; reject org-wide-only flags+ # if the user explicitly passed them alongside --workflow-id.+ org_wide_flags: list[str] = []+ for flag_name, click_param_name in (+ ("--status", "status"),+ ("--search", "search"),+ ("--page", "page"),+ ("--page-size", "page_size"),+ ):+ src = ctx.get_parameter_source(click_param_name)+ if src is not None and src not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP):+ org_wide_flags.append(flag_name)+ if org_wide_flags:+ raise typer.BadParameter(+ f"{', '.join(org_wide_flags)} cannot be used with --workflow-id "+ "(per-workflow list is unpaginated and unfiltered). Drop the flag(s) or omit --workflow-id."+ )++ async def _run() -> dict[str, Any]:+ if workflow_id is not None:+ return await tool_schedule_list_for_workflow(workflow_permanent_id=workflow_id)+ return await tool_schedule_list(page=page, page_size=page_size, status=status, search=search)++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check your API key and Skyvern connection.",+ action="skyvern_schedule_list",+ )+++@schedule_app.command("get")+def schedule_get(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Get a single schedule by ID."""++ async def _run() -> dict[str, Any]:+ return await tool_schedule_get(workflow_permanent_id=workflow_id, workflow_schedule_id=schedule_id)++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check the workflow and schedule IDs.",+ action="skyvern_schedule_get",+ )+++@schedule_app.command("create")+def schedule_create(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ cron: str = typer.Option(..., "--cron", help="Cron expression, e.g. '0 9 * * *'."),+ timezone: str = typer.Option("UTC", "--timezone", help="IANA timezone name."),+ enabled: bool = typer.Option(True, "--enabled/--disabled", help="Whether the schedule fires immediately."),+ parameters: str | None = typer.Option(None, "--parameters", help="Workflow input parameters as JSON object."),+ name: str | None = typer.Option(None, "--name", help="Schedule name."),+ description: str | None = typer.Option(None, "--description", help="Schedule description."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Create a schedule for a workflow."""+ params_dict = _parse_parameters(parameters)++ async def _run() -> dict[str, Any]:+ return await tool_schedule_create(+ workflow_permanent_id=workflow_id,+ cron_expression=cron,+ timezone=timezone,+ enabled=enabled,+ parameters=params_dict,+ name=name,+ description=description,+ )++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check cron, timezone, and parameter shape.",+ action="skyvern_schedule_create",+ )+++@schedule_app.command("update")+def schedule_update(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),+ cron: str | None = typer.Option(None, "--cron", help="New cron expression."),+ timezone: str | None = typer.Option(None, "--timezone", help="New IANA timezone."),+ enabled: bool | None = typer.Option(+ None,+ "--enabled/--disabled",+ help="New enabled flag. Omit to leave unchanged in partial mode.",+ ),+ parameters: str | None = typer.Option(None, "--parameters", help="New parameters as JSON object."),+ clear_parameters: bool = typer.Option(False, "--clear-parameters", help="Clear parameters (set to null)."),+ name: str | None = typer.Option(None, "--name", help="New schedule name."),+ clear_name: bool = typer.Option(False, "--clear-name", help="Clear schedule name."),+ description: str | None = typer.Option(None, "--description", help="New schedule description."),+ clear_description: bool = typer.Option(False, "--clear-description", help="Clear description."),+ exact: bool = typer.Option(+ False,+ "--exact",+ help="Skip fetch+merge and require every replacement field explicitly. Prevents silent enable/clear.",+ ),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Update a schedule.++ Partial by default: GET the schedule, merge supplied fields/clear flags, then PUT.+ Pass --exact to skip the GET; in that case every replacement field must be supplied+ explicitly (or via the corresponding --clear-* flag for nullable fields).+ """+ if name is not None and clear_name:+ raise typer.BadParameter("Cannot pass both --name and --clear-name.")+ if description is not None and clear_description:+ raise typer.BadParameter("Cannot pass both --description and --clear-description.")+ if parameters is not None and clear_parameters:+ raise typer.BadParameter("Cannot pass both --parameters and --clear-parameters.")++ params_dict = _parse_parameters(parameters)++ async def _run() -> dict[str, Any]:+ return await tool_schedule_update(+ workflow_permanent_id=workflow_id,+ workflow_schedule_id=schedule_id,+ cron_expression=cron,+ timezone=timezone,+ enabled=enabled,+ parameters=params_dict,+ clear_parameters=clear_parameters,+ name=name,+ clear_name=clear_name,+ description=description,+ clear_description=clear_description,+ exact=exact,+ )++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check cron, timezone, and parameter shape.",+ action="skyvern_schedule_update",+ )+++@schedule_app.command("enable")+def schedule_enable(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Enable a paused schedule."""++ async def _run() -> dict[str, Any]:+ return await tool_schedule_enable(workflow_permanent_id=workflow_id, workflow_schedule_id=schedule_id)++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check the schedule and workflow IDs.",+ action="skyvern_schedule_enable",+ )+++@schedule_app.command("disable")+def schedule_disable(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Disable an active schedule."""++ async def _run() -> dict[str, Any]:+ return await tool_schedule_disable(workflow_permanent_id=workflow_id, workflow_schedule_id=schedule_id)++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check the schedule and workflow IDs.",+ action="skyvern_schedule_disable",+ )+++@schedule_app.command("delete")+def schedule_delete(+ workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),+ schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),+ yes: bool = typer.Option(+ False,+ "--yes",+ help="Required: confirm deletion. The schedule will stop firing immediately.",+ ),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Delete a schedule. Irreversible."""+ if not yes:+ raise typer.BadParameter("Pass --yes to confirm deletion. This is irreversible.")++ async def _run() -> dict[str, Any]:+ return await tool_schedule_delete(+ workflow_permanent_id=workflow_id,+ workflow_schedule_id=schedule_id,+ force=True,+ )++ run_tool(+ _run,+ json_output=json_output,+ hint_on_exception="Check the schedule and workflow IDs.",+ action="skyvern_schedule_delete",+ )diff --git a/tests/unit/test_schedule_cli.py b/tests/unit/test_schedule_cli.pynew file mode 100644index 000000000..753a57f66--- /dev/null+++ b/tests/unit/test_schedule_cli.py@@ -0,0 +1,283 @@+from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock++import pytest+from typer.testing import CliRunner++from skyvern.cli.schedule_command import schedule_app+++def _patch_tools(+ monkeypatch: pytest.MonkeyPatch,+ *,+ list_all_result: dict[str, Any] | None = None,+ list_for_workflow_result: dict[str, Any] | None = None,+ create_result: dict[str, Any] | None = None,+ update_result: dict[str, Any] | None = None,+ delete_result: dict[str, Any] | None = None,+ enable_result: dict[str, Any] | None = None,+ disable_result: dict[str, Any] | None = None,+) -> dict[str, AsyncMock]:+ """Patch the MCP tools imported into schedule_command with AsyncMocks."""+ mocks: dict[str, AsyncMock] = {}+ cases = [+ ("tool_schedule_list", list_all_result),+ ("tool_schedule_list_for_workflow", list_for_workflow_result),+ ("tool_schedule_create", create_result),+ ("tool_schedule_update", update_result),+ ("tool_schedule_delete", delete_result),+ ("tool_schedule_enable", enable_result),+ ("tool_schedule_disable", disable_result),+ ]+ for name, ret in cases:+ m = AsyncMock(return_value=ret or {"ok": True, "data": {"schedules": []}})+ mocks[name] = m+ monkeypatch.setattr(f"skyvern.cli.schedule_command.{name}", m)+ return mocks+++# -- create --+++class TestCliCreate:+ def test_disabled_flag_maps_to_enabled_false(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(+ monkeypatch,+ create_result={"ok": True, "data": {"schedule": {"workflow_schedule_id": "wfs_test_1"}}},+ )+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "create",+ "--workflow-id",+ "wpid_test_1",+ "--cron",+ "0 9 * * *",+ "--timezone",+ "UTC",+ "--disabled",+ ],+ )+ assert result.exit_code == 0, result.output+ kwargs = mocks["tool_schedule_create"].call_args.kwargs+ assert kwargs["enabled"] is False++ def test_parameters_invalid_json_friendly_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(monkeypatch)+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "create",+ "--workflow-id",+ "wpid_test_1",+ "--cron",+ "0 9 * * *",+ "--timezone",+ "UTC",+ "--parameters",+ "not valid json {",+ ],+ )+ assert result.exit_code != 0+ # MCP tool must not be invoked when parsing fails.+ mocks["tool_schedule_create"].assert_not_called()++ def test_parameters_must_be_object(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(monkeypatch)+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "create",+ "--workflow-id",+ "wpid_test_1",+ "--cron",+ "0 9 * * *",+ "--timezone",+ "UTC",+ "--parameters",+ '["a", "b"]',+ ],+ )+ assert result.exit_code != 0+ mocks["tool_schedule_create"].assert_not_called()+++# -- update --+++class TestCliUpdate:+ def test_mutex_flags_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(monkeypatch)+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "update",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ "--name",+ "x",+ "--clear-name",+ ],+ )+ assert result.exit_code != 0+ mocks["tool_schedule_update"].assert_not_called()++ def test_no_flags_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # No fields, no clear flags, no --exact → MCP tool returns INVALID_INPUT+ # and the CLI exits non-zero.+ mocks = _patch_tools(+ monkeypatch,+ update_result={+ "ok": False,+ "error": {"code": "INVALID_INPUT", "message": "Empty update — no fields supplied.", "hint": "..."},+ },+ )+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "update",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ "--json",+ ],+ )+ assert result.exit_code != 0+ # MCP tool IS called (CLI doesn't pre-check); the tool itself rejects.+ mocks["tool_schedule_update"].assert_called_once()++ def test_exact_missing_field_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # In --exact mode without --enabled, the MCP tool must reject.+ mocks = _patch_tools(+ monkeypatch,+ update_result={+ "ok": False,+ "error": {+ "code": "INVALID_INPUT",+ "message": "exact=True requires explicit values for: enabled",+ "hint": "...",+ },+ },+ )+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "update",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ "--cron",+ "0 9 * * *",+ "--timezone",+ "UTC",+ "--exact",+ "--json",+ ],+ )+ assert result.exit_code != 0+ # The CLI forwards exact=True; the tool itself does the completeness check.+ kwargs = mocks["tool_schedule_update"].call_args.kwargs+ assert kwargs["exact"] is True+ assert kwargs["enabled"] is None+++# -- delete --+++class TestCliDelete:+ def test_without_yes_aborts(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(monkeypatch)+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "delete",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ ],+ )+ assert result.exit_code != 0+ mocks["tool_schedule_delete"].assert_not_called()++ def test_with_yes_forwards_force(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(+ monkeypatch,+ delete_result={"ok": True, "data": {"deleted": True}},+ )+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ [+ "delete",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ "--yes",+ ],+ )+ assert result.exit_code == 0, result.output+ kwargs = mocks["tool_schedule_delete"].call_args.kwargs+ assert kwargs["force"] is True+++# -- list --+++class TestCliList:+ def test_workflow_id_routes_to_per_workflow_path(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(+ monkeypatch,+ list_for_workflow_result={"ok": True, "data": {"schedules": []}},+ )+ runner = CliRunner()+ result = runner.invoke(+ schedule_app,+ ["list", "--workflow-id", "wpid_test_1"],+ )+ assert result.exit_code == 0, result.output+ mocks["tool_schedule_list_for_workflow"].assert_called_once()+ mocks["tool_schedule_list"].assert_not_called()++ def test_no_workflow_id_routes_to_org_wide(self, monkeypatch: pytest.MonkeyPatch) -> None:+ mocks = _patch_tools(+ monkeypatch,+ list_all_result={+ "ok": True,+ "data": {"schedules": [], "total_count": 0, "page": 1, "page_size": 10},+ },+ )+ runner = CliRunner()+ result = runner.invoke(schedule_app, ["list"])+ assert result.exit_code == 0, result.output+ mocks["tool_schedule_list"].assert_called_once()+ mocks["tool_schedule_list_for_workflow"].assert_not_called()+++# -- capabilities surface --+++class TestCliCapabilities:+ def test_capabilities_schedule_lists_subcommands(self) -> None:+ from skyvern.cli.commands import cli_app++ runner = CliRunner()+ result = runner.invoke(cli_app, ["capabilities", "schedule"])+ assert result.exit_code == 0, result.output+ # Output is JSON by default (--json/--no-json default True per the capabilities cmd).+ for sub in ("list", "get", "create", "update", "enable", "disable", "delete"):+ assert sub in result.output, f"missing subcommand {sub} in: {result.output}"diff --git a/tests/unit/test_schedule_mcp_tools.py b/tests/unit/test_schedule_mcp_tools.pynew file mode 100644index 000000000..58e104ec6--- /dev/null+++ b/tests/unit/test_schedule_mcp_tools.py@@ -0,0 +1,502 @@+from __future__ import annotations++import asyncio+import datetime as dt+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.cli.mcp_tools._validation import validate_schedule_id, validate_workflow_id+from skyvern.cli.mcp_tools.schedule import (+ _serialize_org_schedule_item,+ _serialize_schedule,+ _serialize_schedule_response,+ skyvern_schedule_create,+ skyvern_schedule_delete,+ skyvern_schedule_list,+ skyvern_schedule_update,+)+from skyvern.client.types.organization_schedule_item import OrganizationScheduleItem+from skyvern.client.types.workflow_schedule import WorkflowSchedule+from skyvern.client.types.workflow_schedule_response import WorkflowScheduleResponse++# -- Test fixtures (Fern types — NOT the backend Pydantic schema) --+++def _make_fern_schedule(+ *,+ workflow_schedule_id: str = "wfs_test_1",+ organization_id: str = "o_test",+ workflow_permanent_id: str = "wpid_test_1",+ cron_expression: str = "0 9 * * *",+ timezone: str = "UTC",+ enabled: bool = True,+ parameters: dict[str, Any] | None = None,+ temporal_schedule_id: str | None = "ts_abc",+ name: str | None = "probe",+ description: str | None = "test",+ created_at: dt.datetime = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc),+ modified_at: dt.datetime = dt.datetime(2026, 1, 2, 12, 0, 0, tzinfo=dt.timezone.utc),+) -> WorkflowSchedule:+ return WorkflowSchedule(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ cron_expression=cron_expression,+ timezone=timezone,+ enabled=enabled,+ parameters=parameters,+ temporal_schedule_id=temporal_schedule_id,+ name=name,+ description=description,+ created_at=created_at,+ modified_at=modified_at,+ )+++def _make_fern_schedule_response(+ schedule: WorkflowSchedule | None = None,+ next_runs: list[dt.datetime] | None = None,+) -> WorkflowScheduleResponse:+ return WorkflowScheduleResponse(+ schedule=schedule or _make_fern_schedule(),+ next_runs=next_runs+ or [+ dt.datetime(2026, 4, 28, 9, 0, 0, tzinfo=dt.timezone.utc),+ dt.datetime(2026, 4, 29, 9, 0, 0, tzinfo=dt.timezone.utc),+ ],+ )+++def _patch_schedules_client(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ """Patch get_skyvern() so each tool sees a fresh Mock with .schedules.*."""+ sched_client = MagicMock()+ sched_client.list_all = AsyncMock()+ sched_client.list = AsyncMock()+ sched_client.get = AsyncMock()+ sched_client.create = AsyncMock()+ sched_client.update = AsyncMock()+ sched_client.delete = AsyncMock()+ sched_client.enable = AsyncMock()+ sched_client.disable = AsyncMock()++ skyvern_mock = MagicMock()+ skyvern_mock.schedules = sched_client++ monkeypatch.setattr(+ "skyvern.cli.mcp_tools.schedule.get_skyvern",+ lambda: skyvern_mock,+ )+ return sched_client+++# -- ID validation --+++class TestValidation:+ def test_validate_schedule_id_accepts_wfs_prefix_only(self) -> None:+ assert validate_schedule_id("wfs_123abc", "test") is None++ def test_validate_schedule_id_rejects_wsched_prefix(self) -> None:+ # The original plan had wsched_; the real prefix is wfs_. Locks in CORR-1.+ result = validate_schedule_id("wsched_123", "test")+ assert result is not None+ assert not result["ok"]+ assert "wfs_" in result["error"]["hint"]++ def test_validate_schedule_id_rejects_wpid_prefix(self) -> None:+ result = validate_schedule_id("wpid_123", "test")+ assert result is not None+ assert not result["ok"]++ def test_validate_schedule_id_rejects_path_separators(self) -> None:+ result = validate_schedule_id("wfs_../bad", "test")+ assert result is not None+ assert not result["ok"]++ def test_validate_schedule_id_rejects_empty(self) -> None:+ result = validate_schedule_id("", "test")+ assert result is not None++ def test_validate_workflow_id_accepts_wpid_prefix_only(self) -> None:+ assert validate_workflow_id("wpid_123", "test") is None+ bad = validate_workflow_id("wfs_123", "test")+ assert bad is not None and not bad["ok"]+++# -- Serializers --+++class TestSerializeSchedule:+ def test_serialize_schedule_includes_backend_id(self) -> None:+ # Fern type's attribute is literally `temporal_schedule_id`. We re-project it.+ s = _make_fern_schedule(temporal_schedule_id="ts_abc")+ out = _serialize_schedule(s)+ assert out["backend_schedule_id"] == "ts_abc"+ assert "temporal_schedule_id" not in out++ def test_serialize_schedule_handles_missing_temporal_id(self) -> None:+ s = _make_fern_schedule(temporal_schedule_id=None)+ out = _serialize_schedule(s)+ assert out["backend_schedule_id"] is None++ def test_serialize_schedule_returns_iso_datetimes(self) -> None:+ s = _make_fern_schedule()+ out = _serialize_schedule(s)+ assert isinstance(out["created_at"], str)+ assert "T" in out["created_at"] # ISO format+ assert isinstance(out["modified_at"], str)++ def test_serialize_schedule_response_emits_iso_next_runs(self) -> None:+ resp = _make_fern_schedule_response()+ out = _serialize_schedule_response(resp)+ assert "schedule" in out and "next_runs" in out+ assert all(isinstance(r, str) and "T" in r for r in out["next_runs"])++ def test_serialize_org_schedule_item_omits_backend_id(self) -> None:+ item = OrganizationScheduleItem(+ workflow_schedule_id="wfs_test_1",+ organization_id="o_test",+ workflow_permanent_id="wpid_test_1",+ workflow_title="Probe Workflow",+ cron_expression="0 9 * * *",+ timezone="UTC",+ enabled=True,+ parameters=None,+ name="probe",+ description="test",+ next_run=dt.datetime(2026, 4, 28, 9, 0, 0, tzinfo=dt.timezone.utc),+ created_at=dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc),+ modified_at=dt.datetime(2026, 1, 2, 12, 0, 0, tzinfo=dt.timezone.utc),+ )+ out = _serialize_org_schedule_item(item)+ assert "backend_schedule_id" not in out+ assert "workflow_title" in out+ assert isinstance(out["next_run"], str) and "T" in out["next_run"]+++# -- Create --+++class TestScheduleCreate:+ def test_rejects_invalid_workflow_id(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ result = asyncio.run(+ skyvern_schedule_create(+ workflow_permanent_id="not_a_wpid",+ cron_expression="0 9 * * *",+ timezone="UTC",+ )+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"+ sched_client.create.assert_not_called()++ def test_404_maps_to_invalid_input(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.client.core.api_error import ApiError++ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.create.side_effect = ApiError(status_code=404, body={"detail": "workflow not found"})+ result = asyncio.run(+ skyvern_schedule_create(+ workflow_permanent_id="wpid_test_1",+ cron_expression="0 9 * * *",+ timezone="UTC",+ )+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"+ assert "wpid_test_1" in result["error"]["message"]++ def test_happy_path_serializes_response(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.create.return_value = _make_fern_schedule_response()+ result = asyncio.run(+ skyvern_schedule_create(+ workflow_permanent_id="wpid_test_1",+ cron_expression="0 9 * * *",+ timezone="UTC",+ parameters={"k": "v"},+ name="probe",+ description="test",+ )+ )+ assert result["ok"]+ assert result["data"]["schedule"]["workflow_schedule_id"] == "wfs_test_1"+ sched_client.create.assert_called_once()+++# -- List --+++class TestScheduleList:+ def test_paging_metadata_echoed(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ resp = MagicMock()+ resp.schedules = []+ resp.total_count = 7+ resp.page = 2+ resp.page_size = 25+ sched_client.list_all.return_value = resp++ result = asyncio.run(skyvern_schedule_list(page=2, page_size=25))+ assert result["ok"]+ assert result["data"]["total_count"] == 7+ assert result["data"]["page"] == 2+ assert result["data"]["page_size"] == 25++ def test_status_filter_passed_through_to_sdk(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # Validation is server-side; the client just forwards the value.+ sched_client = _patch_schedules_client(monkeypatch)+ resp = MagicMock()+ resp.schedules = []+ resp.total_count = 0+ resp.page = 1+ resp.page_size = 10+ sched_client.list_all.return_value = resp+ asyncio.run(skyvern_schedule_list(status="active"))+ sched_client.list_all.assert_called_once()+ kwargs = sched_client.list_all.call_args.kwargs+ assert kwargs["status"] == "active"+++# -- Update — mutex / empty-patch / partial fetch+merge --+++class TestScheduleUpdateGuards:+ def test_rejects_empty_patch(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ result = asyncio.run(+ skyvern_schedule_update(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ )+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"+ # No I/O: neither GET nor PUT should fire.+ sched_client.get.assert_not_called()+ sched_client.update.assert_not_called()++ def test_mutex_name_and_clear_name(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ result = asyncio.run(+ skyvern_schedule_update(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ name="x",+ clear_name=True,+ )+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"+ sched_client.update.assert_not_called()+++class TestScheduleUpdatePartial:+ def test_partial_preserves_existing_cron_and_timezone(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ existing = _make_fern_schedule(+ cron_expression="*/15 * * * *",+ timezone="America/New_York",+ enabled=True,+ parameters={"old": "params"},+ name="old_name",+ description="old_desc",+ )+ sched_client.get.return_value = _make_fern_schedule_response(schedule=existing)+ sched_client.update.return_value = _make_fern_schedule_response()++ # Only update the name; everything else must come from the snapshot.+ asyncio.run(+ skyvern_schedule_update(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ name="new_name",+ )+ )++ sched_client.get.assert_called_once_with("wpid_test_1", "wfs_test_1")+ kwargs = sched_client.update.call_args.kwargs+ assert kwargs["cron_expression"] == "*/15 * * * *"+ assert kwargs["timezone"] == "America/New_York"+ assert kwargs["enabled"] is True+ assert kwargs["parameters"] == {"old": "params"}+ assert kwargs["name"] == "new_name"+ assert kwargs["description"] == "old_desc"++ def test_clear_name_sends_null(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.get.return_value = _make_fern_schedule_response()+ sched_client.update.return_value = _make_fern_schedule_response()++ asyncio.run(+ skyvern_schedule_update(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ clear_name=True,+ )+ )+ kwargs = sched_client.update.call_args.kwargs+ assert kwargs["name"] is None+++# -- Update --exact path: completeness guards --+++class TestScheduleUpdateExact:+ @pytest.fixture+ def base_kwargs(self) -> dict[str, Any]:+ return {+ "workflow_permanent_id": "wpid_test_1",+ "workflow_schedule_id": "wfs_test_1",+ "cron_expression": "0 9 * * *",+ "timezone": "UTC",+ "enabled": False,+ "parameters": {"k": "v"},+ "name": "n",+ "description": "d",+ "exact": True,+ }++ def test_exact_skips_fetch(self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.update.return_value = _make_fern_schedule_response()+ asyncio.run(skyvern_schedule_update(**base_kwargs))+ sched_client.get.assert_not_called()+ sched_client.update.assert_called_once()++ def test_exact_full_body_includes_all_six_fields_in_put(+ self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.update.return_value = _make_fern_schedule_response()+ asyncio.run(skyvern_schedule_update(**base_kwargs))+ kwargs = sched_client.update.call_args.kwargs+ # Every replacement field must be in the SDK call (no OMIT slipping through).+ for field in ("cron_expression", "timezone", "enabled", "parameters", "name", "description"):+ assert field in kwargs, f"exact mode dropped {field}"+ assert kwargs["enabled"] is False+ assert kwargs["parameters"] == {"k": "v"}++ def test_exact_rejects_missing_enabled(self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ base_kwargs["enabled"] = None+ result = asyncio.run(skyvern_schedule_update(**base_kwargs))+ assert not result["ok"]+ assert "enabled" in result["error"]["message"]+ sched_client.update.assert_not_called()++ def test_exact_rejects_missing_parameters(+ self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ base_kwargs["parameters"] = None+ # clear_parameters defaults False, so this should fail.+ result = asyncio.run(skyvern_schedule_update(**base_kwargs))+ assert not result["ok"]+ assert "parameters" in result["error"]["message"]+ sched_client.update.assert_not_called()++ def test_exact_rejects_missing_name(self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ base_kwargs["name"] = None+ result = asyncio.run(skyvern_schedule_update(**base_kwargs))+ assert not result["ok"]+ assert "name" in result["error"]["message"]+ sched_client.update.assert_not_called()++ def test_exact_rejects_missing_description(+ self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ base_kwargs["description"] = None+ result = asyncio.run(skyvern_schedule_update(**base_kwargs))+ assert not result["ok"]+ assert "description" in result["error"]["message"]+ sched_client.update.assert_not_called()++ def test_exact_with_clear_flags_for_nullable_fields_is_accepted(+ self, monkeypatch: pytest.MonkeyPatch, base_kwargs: dict[str, Any]+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.update.return_value = _make_fern_schedule_response()+ # Drop the explicit values for parameters/name/description; pass clear flags instead.+ base_kwargs.pop("parameters")+ base_kwargs.pop("name")+ base_kwargs.pop("description")+ base_kwargs["clear_parameters"] = True+ base_kwargs["clear_name"] = True+ base_kwargs["clear_description"] = True+ result = asyncio.run(skyvern_schedule_update(**base_kwargs))+ assert result["ok"]+ kwargs = sched_client.update.call_args.kwargs+ assert kwargs["parameters"] is None+ assert kwargs["name"] is None+ assert kwargs["description"] is None+++# -- Delete --+++class TestScheduleDelete:+ def test_requires_force(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ result = asyncio.run(+ skyvern_schedule_delete(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ )+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"+ sched_client.delete.assert_not_called()++ def test_with_force_calls_sdk(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ delete_resp = MagicMock()+ delete_resp.ok = True+ sched_client.delete.return_value = delete_resp+ result = asyncio.run(+ skyvern_schedule_delete(+ workflow_permanent_id="wpid_test_1",+ workflow_schedule_id="wfs_test_1",+ force=True,+ )+ )+ assert result["ok"]+ assert result["data"]["deleted"] is True+++# -- 404 → INVALID_INPUT mapping for write tools --+++class TestSchedule404Mapping:+ @staticmethod+ def _setup_404(monkeypatch: pytest.MonkeyPatch, sdk_attr: str) -> MagicMock:+ from skyvern.client.core.api_error import ApiError++ sched_client = _patch_schedules_client(monkeypatch)+ getattr(sched_client, sdk_attr).side_effect = ApiError(status_code=404, body={"detail": "not found"})+ return sched_client++ def test_enable_404_maps_to_invalid_input(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.schedule import skyvern_schedule_enable++ self._setup_404(monkeypatch, "enable")+ result = asyncio.run(+ skyvern_schedule_enable(workflow_permanent_id="wpid_test_1", workflow_schedule_id="wfs_test_1")+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"++ def test_disable_404_maps_to_invalid_input(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.schedule import skyvern_schedule_disable++ self._setup_404(monkeypatch, "disable")+ result = asyncio.run(+ skyvern_schedule_disable(workflow_permanent_id="wpid_test_1", workflow_schedule_id="wfs_test_1")+ )+ assert not result["ok"]+ assert result["error"]["code"] == "INVALID_INPUT"