Skip to content

Automate browser based workflows with AI

feat: add CLI telemetry to close PostHog blind spot (#5491)

Marc Kelechavaad297714511e
diff --git a/skyvern/__main__.py b/skyvern/__main__.py
index 127657ce4..b8e744187 100644
--- a/skyvern/__main__.py
+++ b/skyvern/__main__.py
@@ -3,6 +3,9 @@ def main() -> None:
configure_cli_bootstrap_logging()
from skyvern.cli.commands import cli_app # noqa: PLC0415
+ from skyvern.cli.core.telemetry import register_cli_telemetry_flush # noqa: PLC0415
+
+ register_cli_telemetry_flush()
cli_app() # type: ignore
diff --git a/skyvern/cli/commands/__main__.py b/skyvern/cli/commands/__main__.py
index ca79ac561..21d4ab260 100644
--- a/skyvern/cli/commands/__main__.py
+++ b/skyvern/cli/commands/__main__.py
@@ -9,6 +9,11 @@ def main() -> None:
from . import cli_app # noqa: PLC0415
load_dotenv(resolve_backend_env_path())
+
+ from skyvern.cli.core.telemetry import register_cli_telemetry_flush # noqa: PLC0415
+
+ register_cli_telemetry_flush()
+
cli_app()
diff --git a/skyvern/cli/commands/_output.py b/skyvern/cli/commands/_output.py
index 37e68d9ee..bac5bcddd 100644
--- a/skyvern/cli/commands/_output.py
+++ b/skyvern/cli/commands/_output.py
@@ -10,6 +10,8 @@ import typer
from rich.console import Console
from rich.table import Table
+from skyvern.cli.core.telemetry import capture_cli_tool_call
+
console = Console()
ENVELOPE_SCHEMA_VERSION = "1.0"
@@ -79,8 +81,17 @@ def output_error(
raise SystemExit(exit_code)
-def emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
+def emit_tool_result(
+ result: dict[str, Any],
+ *,
+ json_output: bool,
+ action: str | None = None,
+ telemetry_tool_name: str | None = None,
+) -> None:
"""Emit an MCP tool result, preserving the full MCP envelope shape in JSON mode."""
+ if telemetry_tool_name is not None:
+ capture_cli_tool_call(telemetry_tool_name, ok=bool(result.get("ok", False)))
+
if json_output:
envelope = {**result}
envelope.setdefault("schema_version", ENVELOPE_SCHEMA_VERSION)
@@ -95,14 +106,14 @@ def emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
return
if result.get("ok", False):
- output(result.get("data"), action=str(result.get("action", "")), json_mode=False)
+ output(result.get("data"), action=action or str(result.get("action", "")), json_mode=False)
return
err = result.get("error") or {}
output_error(
str(err.get("message") or "Unknown error"),
hint=str(err.get("hint") or ""),
- action=str(result.get("action") or ""),
+ action=action or str(result.get("action") or ""),
json_mode=False,
)
@@ -113,14 +124,17 @@ def run_tool(
json_output: bool,
hint_on_exception: str,
action: str = "",
+ telemetry_tool_name: str | None = None,
) -> None:
"""Run an async MCP tool and emit the result."""
try:
result: dict[str, Any] = asyncio.run(runner())
- emit_tool_result(result, json_output=json_output)
+ emit_tool_result(result, json_output=json_output, telemetry_tool_name=telemetry_tool_name)
except typer.BadParameter:
raise
except Exception as e:
+ if telemetry_tool_name is not None:
+ capture_cli_tool_call(telemetry_tool_name, ok=False, error=e)
output_error(str(e), hint=hint_on_exception, action=action, json_mode=json_output)
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.py
index b2bca8fb6..bf375dca8 100644
--- a/skyvern/cli/commands/browser.py
+++ b/skyvern/cli/commands/browser.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import json
import subprocess
-import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -14,7 +13,14 @@ if TYPE_CHECKING:
import typer
-from skyvern.cli.commands._output import console, output, output_error
+from skyvern.cli.commands._output import (
+ console,
+)
+from skyvern.cli.commands._output import emit_tool_result as shared_emit_tool_result
+from skyvern.cli.commands._output import (
+ output,
+ output_error,
+)
from skyvern.cli.commands._state import CLIState, clear_state, load_state, save_state
from skyvern.cli.core.artifacts import save_artifact
from skyvern.cli.core.browser_ops import (
@@ -46,6 +52,7 @@ from skyvern.cli.core.guards import (
)
from skyvern.cli.core.ngrok import check_ngrok_auth, detect_ngrok, offer_install_ngrok, offer_setup_auth
from skyvern.cli.core.session_ops import do_session_close, do_session_create, do_session_list
+from skyvern.cli.core.telemetry import capture_cli_tool_call
from skyvern.cli.mcp_tools.browser import skyvern_login as tool_login
from skyvern.cli.mcp_tools.browser import skyvern_run_task as tool_run_task
from skyvern.cli.mcp_tools.inspection import skyvern_har_start, skyvern_har_stop
@@ -149,20 +156,28 @@ def _validate_wait_state(state: str) -> None:
raise GuardError(f"Invalid state: {state}", "Use visible, hidden, attached, or detached")
-def _emit_tool_result(result: dict[str, Any], *, json_output: bool, action: str) -> None:
- if json_output:
- json.dump(result, sys.stdout, indent=2, default=str)
- sys.stdout.write("\n")
- if not result.get("ok", False):
- raise SystemExit(1)
- return
+def _emit_tool_result(
+ result: dict[str, Any],
+ *,
+ json_output: bool,
+ action: str,
+ telemetry_tool_name: str | None = None,
+) -> None:
+ shared_emit_tool_result(
+ result,
+ json_output=json_output,
+ action=action,
+ telemetry_tool_name=telemetry_tool_name,
+ )
- if result.get("ok", False):
- output(result.get("data"), action=action, json_mode=False)
- return
- err = result.get("error") or {}
- output_error(str(err.get("message") or "Unknown error"), hint=str(err.get("hint") or ""), json_mode=False)
+def _handle_tool_error(e: Exception, *, tool: str, hint: str, json_output: bool) -> None:
+ """Common error handler for CLI commands: emit telemetry + output error."""
+ capture_cli_tool_call(tool, ok=False, error=e)
+ if isinstance(e, GuardError):
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ else:
+ output_error(str(e), hint=hint, json_mode=json_output)
# ---------------------------------------------------------------------------
@@ -202,13 +217,17 @@ def session_create(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_browser_session_create", ok=True)
output(data, action="session_create", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check your API key and network connection.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_browser_session_create",
+ hint="Check your API key and network connection.",
+ json_output=json_output,
+ )
@session_app.command("close")
@@ -235,11 +254,17 @@ def session_close(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_browser_session_close", ok=True)
output(data, action="session_close", json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Verify the session ID or CDP URL is correct.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_browser_session_close",
+ hint="Verify the session ID or CDP URL is correct.",
+ json_output=json_output,
+ )
@session_app.command("connect")
@@ -266,11 +291,17 @@ def session_connect(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_browser_session_connect", ok=True)
output(data, action="session_connect", json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Verify the session ID or CDP URL is reachable.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_browser_session_connect",
+ hint="Verify the session ID or CDP URL is reachable.",
+ json_output=json_output,
+ )
@session_app.command("list")
@@ -286,9 +317,17 @@ def session_list(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_browser_session_list", ok=True)
output(data, action="session_list", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), hint="Check your API key and network connection.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_browser_session_list",
+ hint="Check your API key and network connection.",
+ json_output=json_output,
+ )
@session_app.command("get")
@@ -315,9 +354,17 @@ def session_get(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_browser_session_get", ok=True)
output(data, action="session_get", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), hint="Verify the session ID exists and is accessible.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_browser_session_get",
+ hint="Verify the session ID exists and is accessible.",
+ json_output=json_output,
+ )
# ---------------------------------------------------------------------------
@@ -352,8 +399,16 @@ def network_requests_cmd(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="network_requests")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="network_requests",
+ telemetry_tool_name="skyvern_network_requests",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_network_requests", ok=False, error=e)
output_error(str(e), hint="Ensure a browser session is active.", json_mode=json_output)
@@ -378,8 +433,16 @@ def network_detail_cmd(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="network_detail")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="network_detail",
+ telemetry_tool_name="skyvern_network_request_detail",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_network_request_detail", ok=False, error=e)
output_error(str(e), hint="Ensure a browser session is active.", json_mode=json_output)
@@ -416,8 +479,16 @@ def network_route_cmd(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="network_route")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="network_route",
+ telemetry_tool_name="skyvern_network_route",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_network_route", ok=False, error=e)
output_error(str(e), hint="Ensure a browser session is active.", json_mode=json_output)
@@ -442,8 +513,16 @@ def network_unroute_cmd(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="network_unroute")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="network_unroute",
+ telemetry_tool_name="skyvern_network_unroute",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_network_unroute", ok=False, error=e)
output_error(str(e), hint="Ensure a browser session is active.", json_mode=json_output)
@@ -462,9 +541,13 @@ def navigate(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Navigate to a URL in the browser session."""
+ try:
+ validate_wait_until(wait_until)
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
- validate_wait_until(wait_until)
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -479,13 +562,17 @@ def navigate(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_navigate", ok=True)
output(data, action="navigate", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check the URL is valid and the session is active.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_navigate",
+ hint="Check the URL is valid and the session is active.",
+ json_output=json_output,
+ )
@browser_app.command("screenshot")
@@ -524,13 +611,17 @@ def screenshot(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_screenshot", ok=True)
output(data, action="screenshot", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Ensure the session is active and the page has loaded.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_screenshot",
+ hint="Ensure the session is active and the page has loaded.",
+ json_output=json_output,
+ )
@browser_app.command("evaluate")
@@ -541,9 +632,13 @@ def evaluate(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Run JavaScript on the current page."""
+ try:
+ check_js_password(expression)
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
- check_js_password(expression)
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -553,13 +648,14 @@ def evaluate(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_evaluate", ok=True)
output(data, action="evaluate", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check JavaScript syntax and page state.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_evaluate", hint="Check JavaScript syntax and page state.", json_output=json_output
+ )
@browser_app.command("click")
@@ -574,10 +670,14 @@ def click(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Click an element using selector, intent, or both."""
-
- async def _run() -> dict:
+ try:
validate_button(button)
ai_mode = _resolve_ai_target(selector, intent, operation="click")
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
+
+ async def _run() -> dict:
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -602,13 +702,17 @@ def click(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_click", ok=True)
output(data, action="click", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Element may be hidden, disabled, or not yet available.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_click",
+ hint="Element may be hidden, disabled, or not yet available.",
+ json_output=json_output,
+ )
@browser_app.command("hover")
@@ -621,9 +725,13 @@ def hover(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Hover over an element using selector, intent, or both."""
+ try:
+ ai_mode = _resolve_ai_target(selector, intent, operation="hover")
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
- ai_mode = _resolve_ai_target(selector, intent, operation="hover")
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -639,13 +747,14 @@ def hover(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_hover", ok=True)
output(data, action="hover", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Element may be hidden or not interactable.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_hover", hint="Element may be hidden or not interactable.", json_output=json_output
+ )
@browser_app.command("type")
@@ -661,16 +770,19 @@ def type_text(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Type into an input field using selector, intent, or both."""
-
- async def _run() -> dict:
+ try:
target_text = f"{intent or ''} {selector or ''}"
if PASSWORD_PATTERN.search(target_text):
raise GuardError(
"Cannot type into password fields — credentials must not be passed through tool calls",
CREDENTIAL_HINT,
)
-
ai_mode = _resolve_ai_target(selector, intent, operation="type")
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
+
+ async def _run() -> dict:
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -711,13 +823,14 @@ def type_text(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_type", ok=True)
output(data, action="type", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Element may not be editable or may be obscured.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_type", hint="Element may not be editable or may be obscured.", json_output=json_output
+ )
@browser_app.command("scroll")
@@ -731,12 +844,15 @@ def scroll(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Scroll the page or scroll a targeted element into view."""
-
- async def _run() -> dict:
+ try:
valid_directions = ("up", "down", "left", "right")
if not intent and direction not in valid_directions:
raise GuardError(f"Invalid direction: {direction}", "Use up, down, left, or right")
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
+ async def _run() -> dict:
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -761,13 +877,14 @@ def scroll(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_scroll", ok=True)
output(data, action="scroll", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Scroll failed; check selector and page readiness.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_scroll", hint="Scroll failed; check selector and page readiness.", json_output=json_output
+ )
@browser_app.command("select")
@@ -782,9 +899,13 @@ def select(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Select an option from a dropdown."""
+ try:
+ ai_mode = _resolve_ai_target(selector, intent, operation="select")
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
- ai_mode = _resolve_ai_target(selector, intent, operation="select")
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -803,13 +924,17 @@ def select(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_select_option", ok=True)
output(data, action="select", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check dropdown selector and available options.", json_mode=json_output)
+ _handle_tool_error(
+ e,
+ tool="skyvern_select_option",
+ hint="Check dropdown selector and available options.",
+ json_output=json_output,
+ )
@browser_app.command("press-key")
@@ -822,6 +947,18 @@ def press_key(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Press a keyboard key."""
+ ai_mode: str | None = None
+ try:
+ if intent or selector:
+ ai_mode, err = resolve_ai_mode(selector, intent)
+ if err:
+ raise GuardError(
+ "Must provide intent, selector, or both",
+ "Use intent='describe where to press' or selector='#css-selector'",
+ )
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
connection = _resolve_connection(session, cdp)
@@ -830,12 +967,6 @@ def press_key(
await _apply_cli_frame_state(page)
if intent or selector:
- ai_mode, err = resolve_ai_mode(selector, intent)
- if err:
- raise GuardError(
- "Must provide intent, selector, or both",
- "Use intent='describe where to press' or selector='#css-selector'",
- )
if ai_mode is not None:
locator = page.locator(selector=selector, prompt=intent, ai=ai_mode) # type: ignore[arg-type]
else:
@@ -849,13 +980,14 @@ def press_key(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_press_key", ok=True)
output(data, action="press_key", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check key name and focused target.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_press_key", hint="Check key name and focused target.", json_output=json_output
+ )
@browser_app.command("wait")
@@ -871,15 +1003,18 @@ def wait(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Wait for time, selector state, or AI condition."""
-
- async def _run() -> dict:
+ try:
_validate_wait_state(state)
if time_ms is None and not selector and not intent:
raise GuardError(
"Must provide intent, selector, or time_ms",
"Use --time, --selector, or --intent to specify what to wait for",
)
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
+ async def _run() -> dict:
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -918,13 +1053,14 @@ def wait(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_wait", ok=True)
output(data, action="wait", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Condition was not met within timeout.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_wait", hint="Condition was not met within timeout.", json_output=json_output
+ )
@browser_app.command("act")
@@ -935,9 +1071,13 @@ def act(
json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Perform a natural language action on the current page."""
+ try:
+ check_password_prompt(prompt)
+ except GuardError as e:
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ return
async def _run() -> dict:
- check_password_prompt(prompt)
connection = _resolve_connection(session, cdp)
browser = await _connect_browser(connection)
page = await browser.get_working_page()
@@ -947,13 +1087,14 @@ def act(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_act", ok=True)
output(data, action="act", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Simplify the prompt or break into steps.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_act", hint="Simplify the prompt or break into steps.", json_output=json_output
+ )
@browser_app.command("extract")
@@ -976,13 +1117,14 @@ def extract(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_extract", ok=True)
output(data, action="extract", json_mode=json_output)
- except GuardError as e:
- output_error(str(e), hint=e.hint, json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Simplify the prompt or provide a JSON schema.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_extract", hint="Simplify the prompt or provide a JSON schema.", json_output=json_output
+ )
@browser_app.command("validate")
@@ -1004,11 +1146,14 @@ def validate(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_validate", ok=True)
output(data, action="validate", json_mode=json_output)
except typer.BadParameter:
raise
except Exception as e:
- output_error(str(e), hint="Check the page state and validation prompt.", json_mode=json_output)
+ _handle_tool_error(
+ e, tool="skyvern_validate", hint="Check the page state and validation prompt.", json_output=json_output
+ )
@browser_app.command("run-task")
@@ -1043,10 +1188,16 @@ def run_task(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="run_task")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="run_task",
+ telemetry_tool_name="skyvern_run_task",
+ )
except typer.BadParameter:
raise
except Exception as e:
+ capture_cli_tool_call("skyvern_run_task", ok=False, error=e)
output_error(str(e), hint="Check the prompt, active connection, and timeout settings.", json_mode=json_output)
@@ -1109,10 +1260,16 @@ def login(
try:
result = asyncio.run(_run())
- _emit_tool_result(result, json_output=json_output, action="login")
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="login",
+ telemetry_tool_name="skyvern_login",
+ )
except typer.BadParameter:
raise
except Exception as e:
+ capture_cli_tool_call("skyvern_login", ok=False, error=e)
output_error(
str(e), hint="Check credential inputs, active connection, and timeout settings.", json_mode=json_output
)
@@ -1604,11 +1761,18 @@ def frame_switch(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_frame_switch", ok=True)
output(data, action="frame_switch", json_mode=json_output)
- except (ValueError, GuardError) as e:
- output_error(str(e), hint="Use 'skyvern browser frame list' to find frames.", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ capture_cli_tool_call("skyvern_frame_switch", ok=False, error=e)
+ if isinstance(e, GuardError):
+ output_error(str(e), hint=e.hint, json_mode=json_output)
+ elif isinstance(e, ValueError):
+ output_error(str(e), hint="Use 'skyvern browser frame list' to find frames.", json_mode=json_output)
+ else:
+ output_error(str(e), json_mode=json_output)
@frame_app.command("main")
@@ -1634,9 +1798,12 @@ def frame_main_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_frame_main", ok=True)
output(data, action="frame_main", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_frame_main", hint="", json_output=json_output)
@frame_app.command("list")
@@ -1656,9 +1823,12 @@ def frame_list_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_frame_list", ok=True)
output(data, action="frame_list", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_frame_list", hint="", json_output=json_output)
# ── State persistence commands ──────────────────────────────────────
@@ -1690,9 +1860,12 @@ def state_save_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_state_save", ok=True)
output(data, action="state_save", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_state_save", hint="", json_output=json_output)
@state_app.command("load")
@@ -1724,9 +1897,12 @@ def state_load_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_state_load", ok=True)
output(data, action="state_load", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_state_load", hint="", json_output=json_output)
# ── Web storage commands ────────────────────────────────────────────
@@ -1757,9 +1933,12 @@ def storage_get_session_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_get_session_storage", ok=True)
output(data, action="get_session_storage", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_get_session_storage", hint="", json_output=json_output)
@storage_app.command("set-session")
@@ -1781,9 +1960,12 @@ def storage_set_session_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_set_session_storage", ok=True)
output(data, action="set_session_storage", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_set_session_storage", hint="", json_output=json_output)
@storage_app.command("clear-session")
@@ -1805,9 +1987,12 @@ def storage_clear_session_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_clear_session_storage", ok=True)
output(data, action="clear_session_storage", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_clear_session_storage", hint="", json_output=json_output)
@storage_app.command("clear-local")
@@ -1829,9 +2014,12 @@ def storage_clear_local_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_clear_local_storage", ok=True)
output(data, action="clear_local_storage", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_clear_local_storage", hint="", json_output=json_output)
# ── Page JS errors command ───────────────────────────────────────────
@@ -1853,11 +2041,16 @@ def get_errors_cmd(
try:
result = asyncio.run(_run())
- if result.get("ok"):
- output(result["data"], action="get_errors", json_mode=json_output)
- else:
- output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="get_errors",
+ telemetry_tool_name="skyvern_get_errors",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_get_errors", ok=False, error=e)
output_error(str(e), json_mode=json_output)
@@ -1877,11 +2070,16 @@ def har_start_cmd(
try:
result = asyncio.run(_run())
- if result.get("ok"):
- output(result["data"], action="har_start", json_mode=json_output)
- else:
- output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="har_start",
+ telemetry_tool_name="skyvern_har_start",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_har_start", ok=False, error=e)
output_error(str(e), json_mode=json_output)
@@ -1898,11 +2096,16 @@ def har_stop_cmd(
try:
result = asyncio.run(_run())
- if result.get("ok"):
- output(result["data"], action="har_stop", json_mode=json_output)
- else:
- output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="har_stop",
+ telemetry_tool_name="skyvern_har_stop",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_har_stop", ok=False, error=e)
output_error(str(e), json_mode=json_output)
@@ -1928,9 +2131,12 @@ def get_html_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_get_html", ok=True)
output(data, action="get_html", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_get_html", hint="", json_output=json_output)
@browser_app.command("get-value")
@@ -1951,9 +2157,12 @@ def get_value_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_get_value", ok=True)
output(data, action="get_value", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_get_value", hint="", json_output=json_output)
@browser_app.command("get-styles")
@@ -1975,9 +2184,12 @@ def get_styles_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_get_styles", ok=True)
output(data, action="get_styles", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_get_styles", hint="", json_output=json_output)
# -- Semantic locator command --
@@ -2009,9 +2221,12 @@ def find_cmd(
try:
data = asyncio.run(_run())
+ capture_cli_tool_call("skyvern_find", ok=True)
output(data, action="find", json_mode=json_output)
+ except typer.BadParameter:
+ raise
except Exception as e:
- output_error(str(e), json_mode=json_output)
+ _handle_tool_error(e, tool="skyvern_find", hint="", json_output=json_output)
# ---------------------------------------------------------------------------
@@ -2031,11 +2246,16 @@ def clipboard_read_cmd(
try:
result = asyncio.run(_run())
- if result.get("ok"):
- output(result["data"], action="clipboard_read", json_mode=json_output)
- else:
- output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="clipboard_read",
+ telemetry_tool_name="skyvern_clipboard_read",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_clipboard_read", ok=False, error=e)
output_error(str(e), json_mode=json_output)
@@ -2054,9 +2274,14 @@ def clipboard_write_cmd(
try:
result = asyncio.run(_run())
- if result.get("ok"):
- output(result["data"], action="clipboard_write", json_mode=json_output)
- else:
- output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)
+ _emit_tool_result(
+ result,
+ json_output=json_output,
+ action="clipboard_write",
+ telemetry_tool_name="skyvern_clipboard_write",
+ )
+ except typer.BadParameter:
+ raise
except Exception as e:
+ capture_cli_tool_call("skyvern_clipboard_write", ok=False, error=e)
output_error(str(e), json_mode=json_output)
diff --git a/skyvern/cli/core/telemetry.py b/skyvern/cli/core/telemetry.py
new file mode 100644
index 000000000..c7bf0047a
--- /dev/null
+++ b/skyvern/cli/core/telemetry.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+import atexit
+from contextlib import suppress
+from typing import Any
+
+from skyvern import analytics
+
+_flush_registered = False
+
+
+def capture_cli_tool_call(
+ tool_name: str,
+ *,
+ ok: bool,
+ error: Exception | None = None,
+) -> None:
+ """Capture a direct CLI tool invocation in the MCP PostHog project."""
+ data: dict[str, Any] = {
+ **analytics.analytics_metadata(),
+ "operation": "cli/call",
+ "ok": ok,
+ "runtime_mode": "cli",
+ "transport": None,
+ "is_http": False,
+ "request_path": None,
+ "request_method": None,
+ "organization_id": None,
+ "distinct_id_source": "analytics_id",
+ "request_id": None,
+ "session_id": None,
+ "client_id": None,
+ "tool": tool_name,
+ }
+ if error is not None:
+ data["error_type"] = type(error).__name__
+
+ analytics.capture(
+ "mcp_tool_call",
+ data=data,
+ distinct_id=analytics.settings.ANALYTICS_ID,
+ api_key=analytics.settings.MCP_POSTHOG_PROJECT_API_KEY,
+ host=analytics.settings.MCP_POSTHOG_PROJECT_HOST,
+ )
+
+
+def flush_cli_telemetry() -> None:
+ """Flush CLI telemetry best-effort on process exit."""
+ with suppress(Exception):
+ analytics.flush(
+ api_key=analytics.settings.MCP_POSTHOG_PROJECT_API_KEY,
+ host=analytics.settings.MCP_POSTHOG_PROJECT_HOST,
+ )
+
+
+def register_cli_telemetry_flush() -> None:
+ global _flush_registered
+ if _flush_registered:
+ return
+ atexit.register(flush_cli_telemetry)
+ _flush_registered = True
diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.py
index 94d2a7095..203708e37 100644
--- a/skyvern/cli/mcp_tools/__init__.py
+++ b/skyvern/cli/mcp_tools/__init__.py
@@ -115,264 +115,148 @@ _DEST = ToolAnnotations(readOnlyHint=False, destructiveHint=True)
mcp = FastMCP(
"Skyvern",
instructions="""\
-Skyvern is the complete browser MCP for AI agents. Use Skyvern for ALL browser interactions — \
-clicking, filling forms, extracting data, navigating pages, logging in, uploading files, \
-drag-and-drop, running JavaScript, inspecting console/network, and automating web processes. \
-No second browser MCP is needed.
+Skyvern is the complete browser MCP for AI agents. Use Skyvern for ALL browser interactions.
DO NOT use Skyvern for: REST API calls (use curl/requests), downloading raw files (use wget/curl), \
fetching static JSON/XML endpoints (use WebFetch), or general web search (use WebSearch).
-## QA Testing
-
-To QA test frontend changes in a real browser, use the `qa_test` prompt or ask the user \
-"Would you like me to test your recent code changes?" Skyvern can read a git diff, generate \
-targeted test cases, open a browser against the dev server, and report pass/fail with screenshots.
-
-## Quick Start — First Tool to Call
-
-| Task type | First Skyvern tool | Then |
-|-----------|-------------------|------|
-| QA test frontend changes | qa_test prompt | Generates and runs tests from git diff |
-| Visit / explore a website | skyvern_browser_session_create → skyvern_navigate | skyvern_screenshot to see it |
-| Extract data from a page | skyvern_browser_session_create → skyvern_navigate | skyvern_extract with a prompt |
-| Click / fill / interact | skyvern_browser_session_create → skyvern_navigate | skyvern_act or skyvern_click |
-| Upload files | skyvern_browser_session_create → skyvern_navigate | skyvern_file_upload |
-| Drag and drop | skyvern_browser_session_create → skyvern_navigate | skyvern_drag |
-| Debug browser issues | skyvern_browser_session_create → skyvern_navigate | skyvern_console_messages / skyvern_network_requests |
-| Build a reusable automation | skyvern_workflow_create (no session needed) | skyvern_workflow_run to test |
-| Run an existing automation | skyvern_workflow_run (no session needed) | skyvern_workflow_status to check |
-| View cached scripts | skyvern_script_list_for_workflow (no session needed) | skyvern_script_get_code to see code |
-| Check why AI fallback happened | skyvern_script_fallback_episodes (no session needed) | skyvern_script_versions for history |
-| One-off autonomous task | skyvern_run_task (no session needed) | Check result in response |
-| Work with multiple tabs | skyvern_tab_list → skyvern_tab_switch | skyvern_tab_new to open more |
-| Wait for popup / new tab | skyvern_tab_wait_for_new | skyvern_tab_switch to activate it |
-
-## Tool Selection
-
-| User says | Use | Why |
-|-----------|-----|-----|
-| "QA my changes" / "Test my frontend" | qa_test prompt | Reads git diff, generates + runs browser tests |
-| "Go to [url]" / "Visit [site]" | skyvern_navigate | Opens page in real browser |
-| "What's on this page?" | skyvern_screenshot | Visual understanding |
-| "Get / extract / pull data from [site]" | skyvern_extract | AI-powered structured extraction |
-| "Search for X on [site]" / "Look up X" | skyvern_act | Natural language actions |
-| "Verify / check / confirm something on [site]" | skyvern_validate | AI assertion |
-| "Fill out / submit a form" | skyvern_act | Multi-step form interaction |
-| "Read clipboard" / "Paste from clipboard" | skyvern_clipboard_read | Read text from the browser clipboard |
-| "Copy to clipboard" / "Write clipboard" | skyvern_clipboard_write | Write text to the browser clipboard |
-| "Click [element]" / "Type [text]" | skyvern_click / skyvern_type | Precision targeting |
-| "Hover over [menu]" | skyvern_hover | Reveal dropdowns |
-| "Drag [element] to [target]" | skyvern_drag | AI or selector-based drag-and-drop |
-| "Upload a file" | skyvern_file_upload | Triggers file chooser and sets files |
-| "Run JavaScript" / "Run JS with await" | skyvern_evaluate | DOM state, async fetch, computed values |
-| "Check console errors" / "What API calls?" | skyvern_console_messages / skyvern_network_requests | Browser inspection |
-| "Log into [site]" | skyvern_login | Secure credential-based login |
-| "What credentials do I have?" | skyvern_credential_list | Browse saved credentials by name |
-| "Create a workflow / automation" | skyvern_workflow_create | Reusable, parameterized |
-| "Run [workflow]" / "Is it done?" | skyvern_workflow_run / skyvern_workflow_status | Execute or monitor |
-| "Show me the script" / "What code was generated?" | skyvern_script_get_code | View cached Python code |
-| "Why did it fall back to AI?" | skyvern_script_fallback_episodes | Inspect AI fallback details |
-| "Run this with AI agent" / "Force agent mode" | skyvern_workflow_run(run_with="agent") | Override cached script |
-| "Edit / update the script" | skyvern_script_deploy | Deploy new script version |
-| "List tabs" / "What tabs are open?" | skyvern_tab_list | See all open tabs |
-| "Open a new tab" / "New tab" | skyvern_tab_new | Opens tab, optionally navigates |
-| "Switch to [tab]" / "Go to tab [N]" | skyvern_tab_switch | Change active tab |
-| "Close tab" / "Close this tab" | skyvern_tab_close | Close tab by ID or index |
-| "Wait for popup" / "A new tab should open" | skyvern_tab_wait_for_new | Waits for popup/new tab |
-| "Save login state" / "Remember this session" | skyvern_state_save | Persists cookies + storage to file |
-| "Restore login" / "Load saved state" | skyvern_state_load | Restores cookies + storage from file |
-| "Find button" / "Locate element by role/text" | skyvern_find | Semantic locator: find by role, text, label, placeholder, alt, testid |
-
-## Critical Rules
-1. Use Skyvern for all browser tasks. curl/wget/requests are fine for APIs and file downloads.
-2. Create a session (skyvern_browser_session_create) before browser tools. Workflow tools do NOT need a session.
-3. NEVER scrape by guessing API endpoints — use skyvern_navigate + skyvern_extract.
-4. After page-changing actions, use skyvern_screenshot to verify.
-5. NEVER type passwords — use skyvern_login with stored credentials.
-6. NEVER create single-block workflows with long prompts — split into multiple blocks (one per logical step).
-7. Prefer cloud sessions by default. Use local=true when running in embedded/self-hosted mode or when the user asks.
-
-## Capabilities
-
-- **No snapshot step needed** — Skyvern accepts natural language intent (e.g., intent="the Submit button"). \
-No need for browser_snapshot to get element refs first.
-- **AI-powered extraction** — skyvern_extract returns structured JSON from any page using a prompt.
-- **Natural language actions** — skyvern_act: describe what to do in English.
-- **AI validation** — skyvern_validate checks conditions in natural language.
-- **Drag and drop** — skyvern_drag supports AI intent, CSS/XPath selectors, or both for source and target.
-- **File uploads** — skyvern_file_upload handles file chooser dialogs. Local file paths work for both local and cloud browsers.
-- **JavaScript with async/await** — skyvern_evaluate auto-wraps await expressions in async IIFE.
-- **Console & network inspection** — skyvern_console_messages and skyvern_network_requests capture browser events.
-- **Dialog handling** — skyvern_handle_dialog reads alert/confirm/prompt history (auto-dismissed by default).
-- **Reusable workflows** — skyvern_workflow_create saves automations as versioned, parameterized workflows.
-- **Cloud browsers with proxies** — skyvern_browser_session_create launches cloud browsers with geographic proxy support.
-
-## Tab Management (multi-tab)
-- **skyvern_tab_list** — List all open tabs with IDs, URLs, titles, and active status
-- **skyvern_tab_new** — Open a new tab (optionally navigate to a URL). New tab becomes active.
-- **skyvern_tab_switch** — Switch active tab by tab_id or index. All subsequent tools operate on this tab.
-- **skyvern_tab_close** — Close a tab. If last tab is closed, a blank tab is created automatically.
-- **skyvern_tab_wait_for_new** — Wait for a popup or new tab to open (e.g., after clicking a target=_blank link).
-
-Typical multi-tab flow: skyvern_tab_list → skyvern_tab_new or click a link that opens a popup → \
-skyvern_tab_wait_for_new → skyvern_tab_switch → work on the new tab → skyvern_tab_switch back.
-
-## Tool Modes (precision tools)
-skyvern_click, skyvern_hover, skyvern_type, skyvern_select_option, skyvern_scroll, skyvern_press_key, \
-skyvern_wait, skyvern_drag support three modes. When unsure, use intent. For multiple actions, prefer skyvern_act.
-
-1. **Intent mode**: `skyvern_click(intent="the Submit button")`
-2. **Hybrid mode**: `skyvern_click(selector="#submit-btn", intent="the Submit button")`
-3. **Selector mode**: `skyvern_click(selector="#submit-btn")`
-
-## Cross-Tool Dependencies
-- Workflow tools (list, create, run, status) do NOT need a browser session
-- Credential tools (list, get, delete) do NOT need a browser session
-- skyvern_login requires a session AND a credential_id
-- skyvern_extract and skyvern_validate read the CURRENT page — navigate first
-- skyvern_file_upload requires a session AND a navigated page with an upload element
-- skyvern_drag requires a session AND a navigated page with draggable elements
-- skyvern_console_messages / skyvern_network_requests capture events from session start — call anytime
-- skyvern_run_task is one-off — for reusable automations, use skyvern_workflow_create
-- Script tools (list, get_code, versions, fallback_episodes, deploy) do NOT need a browser session
-- Use skyvern_script_list_for_workflow as the entry point to discover script IDs for a workflow
-
-## Engine Selection
-
-Workflow blocks and skyvern_run_task use different engines. The `engine` field only applies to \
-workflow block definitions — skyvern_run_task always uses engine 2.0 internally and has no engine parameter.
-
-| Context | Engine | Set how |
-|---------|--------|---------|
-| Workflow blocks — single clear goal ("fill this form", "click Submit") | `skyvern-1.0` (default) | Omit `engine` field — 1.0 is the default |
-| Workflow blocks — complex multi-goal ("navigate a wizard with dynamic branching, handle popups, then extract results") | `skyvern-2.0` | Set `"engine": "skyvern-2.0"` on the navigation block |
-| skyvern_run_task | Always `skyvern-2.0` | Cannot be changed — for simple tasks, use a workflow with 1.0 blocks instead |
-
-**How to decide 1.0 vs 2.0 on a navigation block:**
-- Is the path known upfront — all fields, values, and actions are specified in the prompt? → 1.0
-- Does the goal require the AI to plan dynamically — discovering what to do at runtime? → 2.0
-- When in doubt, prefer splitting into multiple 1.0 blocks over using one 2.0 block (cheaper, more observable)
-
-Other engines (`openai-cua`, `anthropic-cua`, `ui-tars`) are available for advanced use cases but are not recommended as defaults.
-
-## Caching & Script Execution
-
-Skyvern workflows support two execution modes controlled by `run_with`:
-
-| `run_with` value | Behavior |
-|------------------|----------|
-| `"code"` (default for MCP-created workflows) | Runs a cached Python script generated from a previous successful AI run. \
-10-100x faster, no LLM calls. Falls back to AI if the script fails. |
-| `"agent"` | Always runs with the AI agent (LLM-driven navigation). Use for first-run exploration or when the site changed. |
-| `null` / omitted | Inherits from the workflow definition. MCP defaults to `"code"`. |
-
-### How Caching Works
-
-1. **First run** — The AI agent navigates the site, recording every action.
-2. **Script generation** — After a successful run, a deterministic Python script is generated from the recorded actions.
-3. **Subsequent runs** — The script replays actions directly (no LLM calls). If a selector fails, AI takes over for that step.
-4. **Script evolution** — Each AI fallback improves the script. Over time, fallbacks decrease.
-
-MCP-created workflows automatically set `code_version=2` and `run_with="code"` unless you explicitly override them.
-
-### When to Override
-
-- Set `run_with="agent"` in skyvern_workflow_run when: testing a new workflow for the first time, debugging a cached \
-script, or when the target site redesigned its UI.
-- Set `run_with="code"` (or omit — it's the default) when: the workflow has run successfully before and you want \
-maximum speed.
-
-### Script Tools
-
-- **skyvern_script_list_for_workflow** — Entry point: find scripts for a workflow (wpid → script IDs)
-- **skyvern_script_get_code** — View the generated Python code for a script version
-- **skyvern_script_versions** — List version history showing how the script evolved
-- **skyvern_script_fallback_episodes** — See when and why the AI agent took over from the cached script
-- **skyvern_script_deploy** — Deploy an updated script version
-
-## Getting Started
-
-**Exploring a website**: skyvern_browser_session_create → skyvern_navigate → skyvern_screenshot → \
-skyvern_act/skyvern_extract → skyvern_browser_session_close
-
-**Uploading files**: skyvern_browser_session_create → skyvern_navigate → \
-skyvern_file_upload(file_paths=[...], intent="the upload button")
-
-**Drag and drop**: skyvern_browser_session_create → skyvern_navigate → \
-skyvern_drag(source_intent="the task card", target_intent="the Done column")
-
-**Debugging**: skyvern_browser_session_create → skyvern_navigate → perform actions → \
-skyvern_console_messages(level="error") to check for JS errors
+## Task Classification — ALWAYS classify before choosing a tool
+
+| Classification | Signal | Tool | Cost | What Happens |
+|---|---|---|---|---|
+| Quick check (yes/no) | "is the user logged in?" | skyvern_validate | 1 LLM + screenshots | Lightweight validation (2 steps max), returns boolean. Cheapest AI option. |
+| Quick inspection | "what does the page show?" | skyvern_extract | 1 LLM + screenshots | Dedicated extraction LLM + schema validation + caching. Better than screenshot+read. |
+| Single action (known target) | "click #submit" | skyvern_click / skyvern_type | 0 LLM | Deterministic Playwright. No AI. Fastest. |
+| Single action (unknown target) | "click the submit button" | skyvern_act | 2-3 LLM, no screenshots | No screenshots in reasoning. Economy a11y tree. For visual targets, use observe first. |
+| 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. |
+| Multi-step (complex) | "navigate a multi-page wizard" | skyvern_run_task | N LLM + screenshots | Full ForgeAgent: screenshot + DOM + Skyvern LLM + execute + verify + loop. Reliable. |
+| Repeated/production | "automate this weekly" | skyvern_workflow_create | Varies | Caching converts AI runs into deterministic scripts over time. |
+
+## Quick Start by Classification
+
+**Quick check:** skyvern_validate(prompt="Is the user logged in?")
+
+**Quick inspection:** skyvern_extract(prompt="Extract all prices", schema='{"type":"object","properties":{...}}')
+
+**Single action (known):** skyvern_click(selector="#submit") or skyvern_type(selector="#email", text="[email protected]")
+
+**Single action (unknown):** skyvern_act(prompt="Click the Sign In button")
+
+**Multi-step (simple) — PREFERRED for forms and standard UI:**
+1. skyvern_observe() -- returns element refs (e0, e1, ...)
+2. Your LLM plans which refs to interact with
+3. skyvern_execute(steps=[{"tool":"click","params":{"ref":"e0"}}, {"tool":"type","params":{"ref":"e1","text":"hello"}}])
+
+**Multi-step (complex) — for visual complexity, multi-page flows:**
+skyvern_run_task(prompt="Complete the checkout flow", url="https://example.com/cart")
+
+**Repeated/production:**
+skyvern_workflow_create(...) -> skyvern_workflow_run(workflow_id="wpid_...") -> skyvern_workflow_status(run_id="wr_...")
+
+**QA testing:** Use the qa_test prompt to test frontend changes — reads git diff, generates + runs browser tests.
+
+## Key Warnings
+
+1. **act has NO screenshots** in its LLM reasoning. It uses an economy accessibility tree. \
+Fine for well-labeled elements. For visually complex targets, use skyvern_observe then skyvern_click with the ref.
+2. **observe+execute is DIFFERENT from run_task.** observe+execute uses the accessibility tree and YOUR LLM plans \
+(no Skyvern LLM calls, fast/cheap). run_task uses the full ForgeAgent with screenshots + visual reasoning (slow/reliable).
+3. **validate is the cheapest AI option** for yes/no — prefer it over extract or act for boolean checks.
+4. **extract DOES use screenshots** (unlike act) with a dedicated extraction LLM. Better than screenshot then read.
+5. **NEVER type passwords** through skyvern_type or skyvern_act. Use skyvern_login with stored credentials.
+
+## Tool Tiers
+
+### Tier 1: AI Tools (use when you have a goal but don't know exact selectors)
+These use AI and cost tokens, but cached results enable free re-execution.
+- **skyvern_act**(prompt) — single-page action. No screenshots. 2-3 LLM calls.
+- **skyvern_extract**(prompt, schema?) — structured data WITH screenshots + dedicated extraction LLM.
+- **skyvern_validate**(prompt) — boolean check WITH screenshots. Cheapest AI.
+- **skyvern_observe**() — a11y tree snapshot with element refs (e0, e1...). No LLM calls.
+- **skyvern_execute**(steps) — batch primitives using refs from observe. No Skyvern LLM calls.
+- **skyvern_run_task**(prompt) — full autonomous agent. Screenshots + visual reasoning + verification loop.
+- **skyvern_login**(credential_id) — AI-powered login with stored credentials.
+
+### Tier 2: Browser Primitives (use when you know the exact selector)
+Zero AI cost. Deterministic. Support intent, selector, or hybrid targeting.
+- **Interaction:** click, type, hover, scroll, select_option, press_key, wait, drag, file_upload, find
+- **Navigation:** navigate, screenshot, evaluate
+- **Tabs:** tab_list, tab_new, tab_switch, tab_close, tab_wait_for_new
+- **Inspection:** console_messages, network_requests, network_request_detail, get_errors, \
+get_html, get_value, get_styles
+- **Network:** network_route, network_unroute, har_start, har_stop
+- **Frames:** frame_list, frame_switch, frame_main
+- **Storage:** state_save, state_load, get/set/clear_session_storage, clear_local_storage
+- **Other:** clipboard_read, clipboard_write, handle_dialog
+
+Precision tools support three targeting modes:
+1. **Intent mode**: skyvern_click(intent="the Submit button") — AI finds element
+2. **Selector mode**: skyvern_click(selector="#submit-btn") — deterministic
+3. **Hybrid mode**: skyvern_click(selector="#submit-btn", intent="the Submit button") — selector narrows, AI confirms
+
+### Tier 3: Management (no browser session needed)
+- **Sessions:** browser_session_create/close/list/get/connect
+- **Workflows:** workflow_create/run/status/get/list/update/delete/cancel/update_folder
+- **Scripts:** script_list_for_workflow, script_get_code, script_versions, script_fallback_episodes, script_deploy
+- **Credentials:** credential_list/get/delete
+- **Folders:** folder_list/get/create/update/delete
+- **Blocks:** block_schema, block_validate
+
+### Dependencies
+- extract and validate read the CURRENT page — navigate first.
+- 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.
+
+## Session Lifecycle
+
+Create session -> navigate -> work -> close. Session state persists between calls.
+skyvern_browser_session_create(timeout=30) -> skyvern_navigate(url="...") -> [work] -> skyvern_browser_session_close()
+Prefer cloud sessions by default. Use local=true for localhost URLs or self-hosted mode.
+Use skyvern_browser_session_connect(cdp_url="...") to attach to an existing browser.
+
+Multi-tab flow: tab_list -> tab_new or click link -> tab_wait_for_new -> tab_switch -> work -> tab_switch back.
+
+## Workflows
+
+Split into multiple blocks — one intent per block. Use **navigation** blocks for actions, **extraction** for data.
+Call skyvern_block_schema() for available types. Validate with skyvern_block_validate() before creating.
+Do NOT use deprecated "task" or "task_v2" block types — use "navigation" for actions, "extraction" for data.
+Use {{parameter_key}} to reference workflow parameters. Blocks share a browser session automatically.
+
+GOOD (4 blocks, clear single responsibility):
+ Block 1 (navigation): "Select Sole Proprietor and click Continue"
+ Block 2 (navigation): "Fill in the business name and click Continue"
+ Block 3 (navigation): "Enter owner info, click Continue"
+ Block 4 (extraction): "Extract the confirmation number"
-**Logging in securely**:
-1. User creates credentials via CLI: `skyvern credentials add --name "Amazon" --username "[email protected]"`
-2. Find the credential: skyvern_credential_list
-3. Create a session: skyvern_browser_session_create
-4. Navigate to login page: skyvern_navigate
-5. Log in: skyvern_login(credential_id="cred_...") — AI handles the full login flow
-6. Verify: skyvern_screenshot
+BAD: One giant block trying to do everything at once.
-## Building Workflows
+### Engine Selection
+- Known path (all fields/actions specified in prompt) -> skyvern-1.0 (default, omit engine field)
+- Dynamic planning (discover what to do at runtime) -> skyvern-2.0
+- skyvern_run_task always uses 2.0 (cannot change)
+- When in doubt, split into multiple 1.0 blocks (cheaper, more observable)
-Before creating a workflow, call skyvern_block_schema() to discover available block types and their JSON schemas.
-Validate blocks with skyvern_block_validate() before submitting.
+### Caching
+MCP-created workflows default to run_with="code". First run uses AI agent; subsequent runs replay \
+a cached script (10-100x faster, no LLM calls). Set run_with="agent" for first-time testing, \
+debugging, or when the target site redesigned. Use script tools to inspect: \
+script_list_for_workflow -> script_get_code -> script_versions -> script_fallback_episodes.
-Split workflows into multiple blocks — one block per logical step — rather than cramming everything into a single block.
-Use **navigation** blocks for actions (filling forms, clicking buttons) and **extraction** blocks for pulling data.
-Do NOT use the deprecated "task" or "task_v2" block types — use "navigation" for actions and "extraction" for data extraction.
-For **text_prompt** blocks, default to Skyvern Optimized by omitting both `model` and `llm_key`. If an explicit model is required, use `model: {"model_name": "<value from /models>"}`. Do not invent internal `llm_key` strings.
+### Block Types
+navigation (most common), extraction, for_loop, conditional, code, text_prompt, action, goto_url, \
+wait, login, validation, http_request, send_email, file_download, file_upload. \
+Call skyvern_block_schema() for full schemas.
-GOOD (4 blocks, each with clear single responsibility):
- Block 1 (navigation): "Select Sole Proprietor and click Continue"
- Block 2 (navigation): "Fill in the business name and click Continue"
- Block 3 (navigation): "Enter owner info and SSN, click Continue"
- Block 4 (extraction): "Extract the confirmation number from the results page"
-
-BAD (1 giant block trying to do everything):
- Block 1: "Go to the IRS site, select sole proprietor, fill in name, enter SSN, review, submit, and extract the EIN"
-
-Use `{{parameter_key}}` to reference workflow input parameters in any block field.
-Blocks in the same workflow run share the same browser session automatically.
-To inspect a real workflow for reference, use skyvern_workflow_get.
-Workflows created via MCP default to code execution mode (code_version=2, run_with="code"). \
-The first run uses the AI agent to learn the navigation; subsequent runs replay a cached script. \
-To force AI agent mode on a specific run, pass run_with="agent" to skyvern_workflow_run.
-
-### Block Types Reference
-- **navigation** — fill forms, click buttons, navigate multi-step flows (most common)
-- **extraction** — extract structured data from the current page
-- **for_loop** — iterate over a list of items
-- **conditional** — branch based on conditions
-- **code** — run Python code for data transformation
-- **text_prompt** — LLM text generation (no browser)
-- **action** — single focused action on the current page
-- **goto_url** — navigate directly to a URL
-- **wait** — pause for a condition or time
-- **login** — log into a site using stored credentials
-- **validation** — assert a condition on the page
-- **http_request** — call an external API
-- **send_email** — send a notification email
-- **file_download** / **file_upload** — download or upload files
-
-For full schemas and descriptions, call skyvern_block_schema().
-
-## Testing Feasibility (try before you build)
-
-Walk through the site interactively — use skyvern_act on each page and skyvern_screenshot to verify results.
-Once you've confirmed each step works, compose them into a workflow with skyvern_workflow_create.
-
-## Writing Scripts (ONLY when user explicitly asks)
-Use the Skyvern Python SDK: `from skyvern import Skyvern`
-NEVER import from skyvern.cli.mcp_tools — those are internal server modules.
-In verbose mode (`--verbose`), every tool response includes an `sdk_equivalent` field for script conversion.
-
-**Hybrid xpath+prompt pattern** — the recommended approach for production scripts:
- await page.click("xpath=//button[@id='submit']", prompt="the Submit button")
- await page.fill("xpath=//input[@name='email']", "[email protected]", prompt="email input field")
-This tries the xpath first (fast, deterministic) and falls back to AI if the selector breaks.
-To get xpaths, use skyvern_click during MCP exploration — its `resolved_selector` response field
-gives you the xpath the AI resolved to. Then hardcode that xpath with a prompt fallback in your script.
+## Critical Rules
+1. Create a session (skyvern_browser_session_create) before any browser tool.
+2. NEVER scrape by guessing API endpoints — use skyvern_navigate + skyvern_extract.
+3. After page-changing actions, use skyvern_screenshot to verify.
+4. NEVER type passwords — use skyvern_login with stored credentials.
+5. NEVER create single-block workflows with long prompts — split into one block per step.
+6. For SDK scripts: from skyvern import Skyvern. NEVER import from skyvern.cli.mcp_tools.
""",
)
mcp.add_middleware(MCPTelemetryMiddleware())
diff --git a/skyvern/cli/skills/skyvern/SKILL.md b/skyvern/cli/skills/skyvern/SKILL.md
index ae0c1b56e..b4dcc67ea 100644
--- a/skyvern/cli/skills/skyvern/SKILL.md
+++ b/skyvern/cli/skills/skyvern/SKILL.md
@@ -4,478 +4,163 @@ description: "PREFER Skyvern CLI over WebFetch for ANY task involving real websi
allowed-tools: Bash(skyvern:*)
---
-# Skyvern Browser Automation -- CLI Reference
+# Skyvern Browser Automation -- CLI Judgment Procedure
-Skyvern uses AI to navigate and interact with websites. Every example is a runnable `skyvern <command>` invocation.
+Skyvern uses AI to navigate and interact with websites. Every command below is a runnable `skyvern <command>` invocation.
-## Setup
+## Step 1: Classify Your Task (ALWAYS do this first)
-```bash
-pip install skyvern
-export SKYVERN_API_KEY="YOUR_KEY" # get one at https://app.skyvern.com
-skyvern init # optional -- configures local env
-```
-
-**MCP upgrade** -- for richer AI-coding-tool integration (auto-tool-calling,
-prompts, etc.), run `skyvern quickstart` or `skyvern init` and choose Claude
-Code during the MCP step. If you are configuring MCP later, run
-`skyvern setup claude-code`. MCP has its own instructions; this file covers CLI
-only.
-
----
-
-## Command Map
-
-| CLI Command | Purpose |
-|-------------|---------|
-| `skyvern browser session create` | Start a cloud browser session |
-| `skyvern browser session list` | List active sessions |
-| `skyvern browser session get` | Get session details |
-| `skyvern browser session connect` | Attach to existing session |
-| `skyvern browser session close` | Close a session |
-| `skyvern browser navigate` | Navigate to a URL |
-| `skyvern browser screenshot` | Capture a screenshot |
-| `skyvern browser act` | AI-driven multi-step action |
-| `skyvern browser extract` | AI-powered data extraction |
-| `skyvern browser validate` | Assert a condition on the page |
-| `skyvern browser evaluate` | Run JavaScript on the page |
-| `skyvern browser click` | Click an element |
-| `skyvern browser type` | Type into an input |
-| `skyvern browser hover` | Hover over an element |
-| `skyvern browser scroll` | Scroll the page |
-| `skyvern browser select` | Select a dropdown option |
-| `skyvern browser press-key` | Press a keyboard key |
-| `skyvern browser wait` | Wait for condition/time |
-| `skyvern browser run-task` | One-off autonomous task |
-| `skyvern browser login` | Log in with stored credentials |
-| `skyvern workflow list` | List workflows |
-| `skyvern workflow get` | Get workflow definition |
-| `skyvern workflow create` | Create a workflow |
-| `skyvern workflow update` | Update a workflow |
-| `skyvern workflow delete` | Delete a workflow |
-| `skyvern workflow run` | Execute a workflow |
-| `skyvern workflow status` | Check run status |
-| `skyvern workflow cancel` | Cancel a running workflow |
-| `skyvern credential list` | List credentials (metadata) |
-| `skyvern credential get` | Get credential metadata |
-| `skyvern credential delete` | Delete a credential |
-| `skyvern credentials add` | Create a credential (env vars or interactive) |
-| `skyvern block schema` | Get block type schema |
-| `skyvern block validate` | Validate a block definition |
-| `skyvern capabilities` | Discover all commands (agent-first) |
-
-All commands accept `--json` for structured output with a consistent envelope.
-**Agent mode:** `skyvern capabilities --json` for discovery, `SKYVERN_NON_INTERACTIVE=1`
-to prevent prompts, `--yes`/`--force` to skip confirmations. See `references/agent-mode.md`.
-
----
+| Classification | Signal | CLI Command | Cost | What Happens |
+|---|---|---|---|---|
+| Quick check (yes/no) | "is the user logged in?" | `skyvern browser validate` | 1 LLM + screenshots | Lightweight validation (2 steps max), returns boolean. Cheapest AI option. |
+| Quick inspection | "what does the page show?" | `skyvern browser extract` | 1 LLM + screenshots | Dedicated extraction LLM + schema validation + caching. |
+| Single action (known target) | "click #submit" | `skyvern browser click/type` | 0 LLM | Deterministic Playwright. No AI. Fastest. |
+| Single action (unknown target) | "click the submit button" | `skyvern browser act` | 2-3 LLM, no screenshots | No screenshots in reasoning. Economy a11y tree. For visual targets, use hybrid mode (selector + intent). |
+| Multi-step (simple, fast) | "fill the form and submit" | MCP: `observe + execute` | 0 Skyvern LLM | A11y tree + YOUR LLM plans from refs. Not available as CLI commands -- use MCP or `act`. |
+| Multi-step (complex) | "navigate a multi-page wizard" | `skyvern browser run-task` | N LLM + screenshots | Full ForgeAgent: screenshot + DOM + Skyvern LLM + execute + verify + loop. Reliable. |
+| Repeated/production | "automate this weekly" | `skyvern workflow create` | Varies | Caching converts AI runs into deterministic scripts over time. |
-## Pattern 1: Session Lifecycle
+## Step 2: Create a Session
-Every browser automation follows: create -> navigate -> work -> close.
+Every browser command needs a session. Create one first:
```bash
-# 1. Create a cloud session (timeout in minutes, default 60)
+# Cloud session (default -- works for public URLs)
skyvern browser session create --timeout 30
-# 2. Navigate (uses the active session automatically)
-skyvern browser navigate --url "https://example.com"
-
-# 3. Do work (act, extract, click, etc.)
-skyvern browser act --prompt "Click the Sign In button"
-
-# 4. Verify with screenshot
-skyvern browser screenshot
-
-# 5. Close when done
-skyvern browser session close
-```
-
-Session state persists between commands. After `session create`, subsequent
-commands auto-attach to the active session. Override with `--session pbs_...`.
+# Local session (for localhost URLs or self-hosted mode)
+skyvern browser session create --local --timeout 30
-### Session management
-
-```bash
-# List all sessions
-skyvern browser session list
-
-# Get details for a specific session
-skyvern browser session get --session pbs_123
-
-# Connect to an existing session (cloud or CDP)
-skyvern browser session connect --session pbs_123
+# Connect to existing browser via CDP
skyvern browser session connect --cdp "ws://localhost:9222"
-
-# Close a specific session
-skyvern browser session close --session pbs_123
```
----
+Session state persists between commands. After `session create`, subsequent commands auto-attach.
+Override with `--session pbs_...`. Close when done: `skyvern browser session close`.
-## Pattern 2: One-Off Task
+## Step 3: Execute by Classification
-Run an autonomous agent that navigates, acts, and extracts in a single call.
-Requires an active session (create one first).
+### Quick check (yes/no)
```bash
-# 1. Create a session
-skyvern browser session create
-
-# 2. Run the task (uses active session automatically)
-skyvern browser run-task \
- --prompt "Go to the pricing page and extract all plan names and prices" \
- --url "https://example.com" \
- --schema '{"type":"object","properties":{"plans":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"string"}}}}}}'
-
-# 3. Close session when done
-skyvern browser session close
+skyvern browser validate --prompt "Is the user logged in? Look for a dashboard or avatar."
```
-Key flags:
-- `--prompt` (required): natural language task description
-- `--url`: starting URL (navigates before running the agent)
-- `--schema` (alias `--data-extraction-schema`): JSON schema for structured output
-- `--max-steps`: limit agent steps (default unlimited)
-- `--timeout`: seconds (default 180, max 1800)
-
-Use `run-task` for quick tests. Use workflows for anything reusable.
-
----
+Returns true/false. Cheapest AI option -- prefer over extract or act for boolean checks.
-## Pattern 3: Data Extraction
+### Quick inspection
```bash
-# Navigate to the source page
-skyvern browser navigate --url "https://example.com/products"
-
-# Extract structured data with a JSON schema
skyvern browser extract \
- --prompt "Extract all product names and prices from the listing" \
- --schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"string"}},"required":["name"]}}},"required":["items"]}'
-```
-
-Without `--schema`, extraction returns freeform data based on the prompt.
-
-### Schema design tips
-- Start with the smallest useful schema
-- Use `"type":"string"` for prices/dates unless format is guaranteed
-- Keep `required` to truly essential fields
-- Add provenance fields where needed (`source_url`, timestamp)
-
-### Pagination loop
-
-```bash
-# Page 1
-skyvern browser extract --prompt "Extract all product rows"
-# Check for next page
-skyvern browser validate --prompt "Is there a Next page button that is not disabled?"
-# If true, advance
-skyvern browser act --prompt "Click the Next page button"
-# Repeat extraction
+ --prompt "Extract all product names and prices" \
+ --schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"string"}}}}}}'
```
-Stop when: no next button, duplicate first row, or max page limit.
-
----
-
-## Pattern 4: Form Filling with Act
-
-`act` performs AI-driven multi-step actions described in natural language:
-
-```bash
-skyvern browser act \
- --prompt "Fill the contact form: first name John, last name Doe, email [email protected], then click Submit"
-```
+Uses screenshots + dedicated extraction LLM. Better than screenshot+read because Skyvern's LLM interprets the page.
-For precision control, use individual commands:
+### Single action (known target)
```bash
-# Type into a field (by intent)
-skyvern browser type --text "John" --intent "the first name input"
-
-# Type into a field (by selector)
-skyvern browser type --text "[email protected]" --selector "#email"
-
-# Click a button (by intent)
-skyvern browser click --intent "the Submit button"
-
-# Select a dropdown option
+skyvern browser click --selector "#submit-btn"
+skyvern browser type --text "[email protected]" --selector "#email"
skyvern browser select --value "US" --intent "the country dropdown"
-skyvern browser select --value "California" --selector "#state" --by-label
-
-# Press a key
-skyvern browser press-key --key "Enter"
-
-# Hover to reveal a menu
-skyvern browser hover --intent "the Account menu"
```
-### Targeting modes
-
-Precision commands (`click`, `type`, `hover`, `select`, `scroll`, `press-key`,
-`wait`) support three targeting modes:
-
-1. **Intent mode**: `--intent "the Submit button"` (AI finds element)
-2. **Selector mode**: `--selector "#submit-btn"` (CSS/XPath)
-3. **Hybrid mode**: both `--selector` and `--intent` (selector narrows, AI confirms)
+Deterministic. No AI. Three targeting modes:
+1. **Intent**: `--intent "the Submit button"` (AI finds element)
+2. **Selector**: `--selector "#submit-btn"` (CSS/XPath, deterministic)
+3. **Hybrid**: both (selector narrows, AI confirms)
-When unsure, use intent. For deterministic control, use selector.
-
----
-
-## Pattern 5: Auth with Login + Credentials
-
-Credentials are created interactively (secrets never flow through CLI args):
+### Single action (unknown target)
```bash
-# Create a credential (prompts for password securely via stdin)
-skyvern credentials add --name "prod-salesforce" --type password --username "[email protected]"
+skyvern browser act --prompt "Click the Sign In button"
+skyvern browser act --prompt "Close the cookie banner, then click Sign In"
```
-Then use it in a browser session:
-
-```bash
-# List credentials to find the ID
-skyvern credential list
-
-# Create session and navigate to login page
-skyvern browser session create
-skyvern browser navigate --url "https://login.salesforce.com"
+**Warning:** act has NO screenshots in its LLM reasoning. It uses an economy accessibility tree.
+Fine for well-labeled elements. For visually complex targets, use MCP observe+click or hybrid mode.
-# Log in with stored credentials (AI handles the full login flow)
-skyvern browser login --url "https://login.salesforce.com" --credential-id cred_123
+### Multi-step (simple, fast) -- MCP only
-# Verify login succeeded
-skyvern browser validate --prompt "Is the user logged in? Look for a dashboard or user avatar."
-skyvern browser screenshot
-```
+The `observe + execute` pattern uses the accessibility tree and YOUR LLM to plan, with no Skyvern
+LLM calls. This is MCP-only (not available as CLI commands). For CLI, use `act` with clear prompts
+or break into multiple click/type commands.
-### Credential types
+### Multi-step (complex, reliable)
```bash
-# Password credential
-skyvern credentials add --name "my-login" --type password --username "user"
-
-# Credit card credential
-skyvern credentials add --name "my-card" --type credit_card
-
-# Secret credential (API key, token, etc.)
-skyvern credentials add --name "my-secret" --type secret
+skyvern browser run-task \
+ --prompt "Go to the pricing page and extract all plan names and prices" \
+ --url "https://example.com" \
+ --schema '{"type":"object","properties":{"plans":{"type":"array"}}}'
```
-Other credential providers: `--credential-type bitwarden --bitwarden-item-id "..."`,
-`--credential-type 1password --onepassword-vault-id "..." --onepassword-item-id "..."`,
-`--credential-type azure_vault --azure-vault-name "..." --azure-vault-username-key "..."`.
+Full ForgeAgent: screenshots + visual reasoning + verification + retry loop. Always uses engine 2.0.
+Flags: `--prompt` (required), `--url`, `--schema`, `--max-steps`, `--timeout` (default 180s).
-### Security rules
-- NEVER type passwords through `skyvern browser type`. Always use `skyvern browser login`.
-- Use `skyvern credentials add` to create credentials (interactive stdin input).
-- Reuse authenticated sessions for multi-step jobs on the same site.
-
----
-
-## Pattern 6: Workflows
-
-Workflows are reusable, parameterized multi-step automations.
-
-### Create from file
+### Repeated/production
```bash
-# Create from a YAML or JSON file
skyvern workflow create --definition @workflow.yaml
-
-# Create from inline JSON
-skyvern workflow create --definition '{"title":"My Workflow","workflow_definition":{"parameters":[],"blocks":[{"block_type":"navigation","label":"step1","url":"https://example.com","navigation_goal":"Click the pricing link"}]}}'
-
-# Specify format explicitly
-skyvern workflow create --definition @workflow.json --format json
-```
-
-### Run a workflow
-
-```bash
-# Basic run
-skyvern workflow run --id wpid_123
-
-# With parameters (inline JSON or @file)
-skyvern workflow run --id wpid_123 --params '{"email":"[email protected]","name":"John"}'
-skyvern workflow run --id wpid_123 --params @params.json
-
-# Wait for completion
-skyvern workflow run --id wpid_123 --wait --timeout 600
-
-# With proxy and webhook
-skyvern workflow run --id wpid_123 --proxy RESIDENTIAL --webhook "https://hooks.example.com/done"
-
-# Reuse an existing browser session
-skyvern workflow run --id wpid_123 --session pbs_456
-```
-
-### Monitor and manage
-
-```bash
-# Check run status
+skyvern workflow run --id wpid_123 --params '{"email":"[email protected]"}'
skyvern workflow status --run-id wr_789
-
-# Cancel a run
-skyvern workflow cancel --run-id wr_789
-
-# List workflows (with search and pagination)
-skyvern workflow list --search "invoice" --page 1 --page-size 20
-skyvern workflow list --only-workflows # exclude saved tasks
-
-# Get workflow definition
-skyvern workflow get --id wpid_123 --version 2
-
-# Update a workflow
-skyvern workflow update --id wpid_123 --definition @updated.yaml
-
-# Delete a workflow
-skyvern workflow delete --id wpid_123 --force
```
-### Run status lifecycle
+Split into one block per step. Use **navigation** blocks for actions, **extraction** for data.
+First run uses AI; subsequent runs replay a cached script (10-100x faster).
+Set `--run-with agent` to force AI mode for debugging.
-```
-created -> queued -> running -> completed | failed | canceled | terminated | timed_out
-```
-
-### Block types
+## Step 4: Verify
-Use `skyvern block schema` to discover available types:
+Always verify after page-changing actions:
```bash
-# List all block types
-skyvern block schema
-
-# Get schema for a specific type
-skyvern block schema --type navigation
-
-# Validate a block definition
-skyvern block validate --block-json '{"block_type":"navigation","label":"step1","url":"https://example.com","navigation_goal":"Click pricing"}'
-skyvern block validate --block-json @block.json
+skyvern browser screenshot # visual check
+skyvern browser validate --prompt "Was the form submitted successfully?" # boolean assertion
+skyvern browser evaluate --expression "document.title" # JS state check
```
-Core block types:
-- **navigation** -- fill forms, click buttons, navigate flows (most common)
-- **extraction** -- extract structured data from the current page
-- **login** -- log into a site using stored credentials
-- **for_loop** -- iterate over a list of items
-- **conditional** -- branch based on conditions
-- **code** -- run Python for data transformation
-- **text_prompt** -- LLM generation (no browser)
-- **action** -- single focused action
-- **wait** -- pause for condition/time
-- **goto_url** -- navigate directly to a URL
-- **validation** -- assert page condition
-- **http_request** -- call an external API
-- **send_email** -- send notification
-- **file_download** / **file_upload** -- file operations
-
-### Workflow design principles
-- One intent per block. Split multi-step goals into separate blocks.
-- Use `{{parameter_key}}` to reference workflow parameters.
-- Prefer `navigation` blocks for actions, `extraction` for data pulling.
-- All blocks in a workflow share the same browser session automatically.
-- Test feasibility interactively first (session + act + screenshot), then codify into a workflow.
-
-### Engine selection
-
-| Context | Engine | Notes |
-|---------|--------|-------|
-| Known path -- all fields and actions specified in prompt | `skyvern-1.0` (default) | Omit `engine` field |
-| Dynamic planning -- discover what to do at runtime | `skyvern-2.0` | Set `"engine": "skyvern-2.0"` |
-
-Long prompts with many fields are still 1.0. "Complexity" means dynamic
-planning, not field count. When in doubt, split into multiple 1.0 blocks.
+## Step 5: Error Recovery
----
+| Problem | Fix |
+|---------|-----|
+| Action clicked wrong element | Add context to prompt. Use hybrid mode (selector + intent). |
+| Extraction returns empty | Wait for content. Relax required fields. Check row count first. |
+| Login passes but next step fails | Ensure same session. Add post-login validate check. |
+| Element not found | Add wait: `skyvern browser wait --selector "#el" --state visible` |
+| Overloaded prompt | Split into smaller goals -- one intent per command. |
-## Pattern 7: Debugging
+## Credentials
-### Screenshot + validate loop
+NEVER type passwords through `skyvern browser type` or `act`. Always use stored credentials:
```bash
-# Capture current state
-skyvern browser screenshot
-skyvern browser screenshot --full-page
-skyvern browser screenshot --selector "#main-content" --output debug.png
-
-# Check a condition
-skyvern browser validate --prompt "Is the login form visible?"
-skyvern browser validate --prompt "Does the page show an error message?"
-
-# Run JavaScript to inspect state
-skyvern browser evaluate --expression "document.title"
-skyvern browser evaluate --expression "document.querySelectorAll('table tr').length"
+skyvern credentials add --name "my-login" --type password --username "[email protected]"
+skyvern credential list # find the credential ID
+skyvern browser login --url "https://login.example.com" --credential-id cred_123
```
-### Wait for conditions
-
-```bash
-# Wait for time
-skyvern browser wait --time 3000
+Types: `password`, `credit_card`, `secret`. Also supports bitwarden, 1password, and azure_vault providers.
-# Wait for a selector
-skyvern browser wait --selector "#results-table" --state visible --timeout 10000
+## Workflow Quick Reference
-# Wait for an AI condition (polls until true)
-skyvern browser wait --intent "The loading spinner has disappeared" --timeout 15000
-
-# Scroll to find content
-skyvern browser scroll --direction down --amount 500
-skyvern browser scroll --direction down --intent "the pricing section" # AI scroll-into-view
+```bash
+skyvern workflow create --definition @workflow.yaml # create
+skyvern workflow run --id wpid_123 --wait # run and wait
+skyvern workflow status --run-id wr_789 # check status
+skyvern workflow list --search "invoice" # find workflows
+skyvern block schema --type navigation # discover block types
+skyvern block validate --block-json @block.json # validate before creating
```
-### Common failure patterns
-
-**Action clicked wrong element:**
-Fix: add stronger context in prompt. Use hybrid mode (selector + intent).
+Engine: known path = 1.0 (default). Dynamic planning = 2.0. Split into multiple 1.0 blocks when in doubt.
+Status lifecycle: `created -> queued -> running -> completed | failed | canceled | terminated | timed_out`
-**Extraction returns empty:**
-Fix: wait for content-ready condition. Relax required fields. Validate visible
-row count before extracting.
+## Agent Mode
-**Login passes but next step fails as logged out:**
-Fix: ensure same session across steps. Add post-login `validate` check.
-
-### Stabilization moves
-- Replace brittle selectors with intent-based actions
-- Add explicit wait conditions before next action
-- Narrow extraction schema to required fields first
-- Split overloaded prompts into smaller goals
-
----
-
-## Writing Good Prompts
-
-State the business outcome first, then constraints. Include explicit success
-criteria and keep one objective per invocation. Good: "Extract plan name and
-monthly price for each tier on the pricing page." Bad: "Click around and get
-data." Prefer natural language intents over brittle selectors.
-
-See `references/prompt-writing.md` for templates and anti-patterns.
-
----
-
-## AI vs Precision: Decision Rules
-
-**Use AI actions** (`act`, `extract`, `validate`) when:
-- Page labels are human-readable and stable
-- The goal is navigational or exploratory
-- You want resilience to minor layout changes
-
-**Use precision commands** (`click`, `type`, `select`) when:
-- Element identity is deterministic and stable
-- AI action picked the wrong element
-- You need guaranteed exact input
-
-**Use hybrid mode** (selector + intent together) when:
-- Pages are noisy or crowded
-- Selector narrows to a region, intent picks the exact element
-
----
+All commands accept `--json` for structured output. Set `SKYVERN_NON_INTERACTIVE=1` to prevent prompts.
+Use `skyvern capabilities --json` for full command discovery. See `references/agent-mode.md`.
## Deep-Dive References
diff --git a/skyvern/cli/workflow.py b/skyvern/cli/workflow.py
index af545f699..99bea9e31 100644
--- a/skyvern/cli/workflow.py
+++ b/skyvern/cli/workflow.py
@@ -69,6 +69,7 @@ def workflow_list(
json_output=json_output,
hint_on_exception="Check your API key and workflow list filters.",
action="skyvern_workflow_list",
+ telemetry_tool_name="skyvern_workflow_list",
)
@@ -88,6 +89,7 @@ def workflow_get(
json_output=json_output,
hint_on_exception="Check your API key and workflow ID.",
action="skyvern_workflow_get",
+ telemetry_tool_name="skyvern_workflow_get",
)
@@ -121,6 +123,7 @@ def workflow_create(
json_output=json_output,
hint_on_exception="Check the workflow definition syntax.",
action="skyvern_workflow_create",
+ telemetry_tool_name="skyvern_workflow_create",
)
@@ -154,6 +157,7 @@ def workflow_update(
json_output=json_output,
hint_on_exception="Check the workflow ID and definition syntax.",
action="skyvern_workflow_update",
+ telemetry_tool_name="skyvern_workflow_update",
)
@@ -173,6 +177,7 @@ def workflow_delete(
json_output=json_output,
hint_on_exception="Check the workflow ID and your permissions.",
action="skyvern_workflow_delete",
+ telemetry_tool_name="skyvern_workflow_delete",
)
@@ -220,6 +225,7 @@ def workflow_run(
json_output=json_output,
hint_on_exception="Check the workflow ID and run parameters.",
action="skyvern_workflow_run",
+ telemetry_tool_name="skyvern_workflow_run",
)
@@ -238,6 +244,7 @@ def workflow_status(
json_output=json_output,
hint_on_exception="Check the run ID and API key.",
action="skyvern_workflow_status",
+ telemetry_tool_name="skyvern_workflow_status",
)
@@ -256,4 +263,5 @@ def workflow_cancel(
json_output=json_output,
hint_on_exception="Check the run ID and API key.",
action="skyvern_workflow_cancel",
+ telemetry_tool_name="skyvern_workflow_cancel",
)
diff --git a/tests/unit/test_cli_agent_aware.py b/tests/unit/test_cli_agent_aware.py
index 54a2d0607..0feda230d 100644
--- a/tests/unit/test_cli_agent_aware.py
+++ b/tests/unit/test_cli_agent_aware.py
@@ -117,6 +117,17 @@ class TestEmitToolResult:
emit_tool_result(error_result, json_output=True)
assert exc_info.value.code == 1
+ def test_captures_cli_telemetry_when_tool_name_provided(self):
+ result = {"ok": True, "action": "test", "data": {}, "error": None}
+ buf = io.StringIO()
+ with (
+ patch("sys.stdout", buf),
+ patch("skyvern.cli.commands._output.capture_cli_tool_call") as capture_mock,
+ ):
+ emit_tool_result(result, json_output=True, telemetry_tool_name="skyvern_test")
+
+ capture_mock.assert_called_once_with("skyvern_test", ok=True)
+
# ---------------------------------------------------------------------------
# run_tool tests
@@ -140,11 +151,24 @@ class TestRunTool:
raise RuntimeError("network error")
buf = io.StringIO()
- with patch("sys.stdout", buf), pytest.raises(SystemExit):
- run_tool(failing, json_output=True, hint_on_exception="check connection", action="workflow.create")
+ with (
+ patch("sys.stdout", buf),
+ patch("skyvern.cli.commands._output.capture_cli_tool_call") as capture_mock,
+ pytest.raises(SystemExit),
+ ):
+ run_tool(
+ failing,
+ json_output=True,
+ hint_on_exception="check connection",
+ action="workflow.create",
+ telemetry_tool_name="skyvern_workflow_create",
+ )
envelope = json.loads(buf.getvalue())
assert envelope["ok"] is False
assert envelope["action"] == "workflow.create"
+ capture_mock.assert_called_once()
+ assert capture_mock.call_args.args[0] == "skyvern_workflow_create"
+ assert capture_mock.call_args.kwargs["ok"] is False
def test_passes_bad_parameter_through(self):
import typer
@@ -152,8 +176,17 @@ class TestRunTool:
async def bad_param():
raise typer.BadParameter("invalid value")
- with pytest.raises(typer.BadParameter):
- run_tool(bad_param, json_output=False, hint_on_exception="")
+ with (
+ patch("skyvern.cli.commands._output.capture_cli_tool_call") as capture_mock,
+ pytest.raises(typer.BadParameter),
+ ):
+ run_tool(
+ bad_param,
+ json_output=False,
+ hint_on_exception="",
+ telemetry_tool_name="skyvern_workflow_create",
+ )
+ capture_mock.assert_not_called()
# ---------------------------------------------------------------------------
diff --git a/tests/unit/test_cli_commands.py b/tests/unit/test_cli_commands.py
index b05a6f419..db94b4ce6 100644
--- a/tests/unit/test_cli_commands.py
+++ b/tests/unit/test_cli_commands.py
@@ -224,6 +224,8 @@ class TestBrowserCommands:
) -> None:
from skyvern.cli.commands import browser as browser_cmd
+ capture_mock = MagicMock()
+ monkeypatch.setattr(browser_cmd, "capture_cli_tool_call", capture_mock)
monkeypatch.setattr(
browser_cmd,
"_resolve_connection",
@@ -245,6 +247,7 @@ class TestBrowserCommands:
parsed = json.loads(capsys.readouterr().out)
assert parsed["ok"] is False
assert "Must provide intent, selector, or both" in parsed["error"]["message"]
+ capture_mock.assert_not_called()
def test_click_with_intent_uses_proactive_ai_mode(
self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
@@ -261,6 +264,8 @@ class TestBrowserCommands:
lambda _session, _cdp: browser_cmd.ConnectionTarget(mode="cloud", session_id="pbs_123"),
)
monkeypatch.setattr(browser_cmd, "_connect_browser", AsyncMock(return_value=browser))
+ capture_mock = MagicMock()
+ monkeypatch.setattr(browser_cmd, "capture_cli_tool_call", capture_mock)
browser_cmd.click(
intent="the Submit button",
@@ -278,6 +283,7 @@ class TestBrowserCommands:
assert parsed["action"] == "click"
assert parsed["data"]["ai_mode"] == "proactive"
assert parsed["data"]["resolved_selector"] == "xpath=//button[@id='submit']"
+ capture_mock.assert_called_once_with("skyvern_click", ok=True)
def test_wait_rejects_invalid_state_before_connection(
self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
@@ -853,6 +859,7 @@ class TestBrowserPRCCommands:
def test_login_json_error_exits_nonzero(
self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
) -> None:
+ from skyvern.cli.commands import _output as output_mod
from skyvern.cli.commands import browser as browser_cmd
monkeypatch.setattr(
@@ -878,6 +885,8 @@ class TestBrowserPRCCommands:
}
)
monkeypatch.setattr(browser_cmd, "tool_login", tool)
+ capture_mock = MagicMock()
+ monkeypatch.setattr(output_mod, "capture_cli_tool_call", capture_mock)
with pytest.raises(SystemExit, match="1"):
browser_cmd.login(
@@ -894,6 +903,26 @@ class TestBrowserPRCCommands:
parsed = json.loads(capsys.readouterr().out)
assert parsed["ok"] is False
assert "Missing required fields" in parsed["error"]["message"]
+ capture_mock.assert_called_once_with("skyvern_login", ok=False)
+
+ def test_workflow_create_missing_definition_file_does_not_emit_cli_telemetry(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ from skyvern.cli import workflow as workflow_cmd
+
+ capture_mock = MagicMock()
+ monkeypatch.setattr("skyvern.cli.commands._output.capture_cli_tool_call", capture_mock)
+
+ with pytest.raises(typer.BadParameter):
+ workflow_cmd.workflow_create(
+ definition="@/does/not/exist.json",
+ definition_format="json",
+ folder_id=None,
+ json_output=False,
+ )
+
+ capture_mock.assert_not_called()
class TestParityErrorFormatting:
@@ -954,17 +983,25 @@ class TestParityErrorFormatting:
assert captured == {"message": "Unknown error", "hint": "", "json_mode": False}
def test_browser_emit_tool_result_handles_none_message_and_hint(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.cli.commands import _output as output_mod
from skyvern.cli.commands import browser as browser_cmd
captured: dict[str, str | bool] = {}
- def _fake_output_error(message: str, *, hint: str = "", json_mode: bool = False, exit_code: int = 1) -> None:
+ def _fake_output_error(
+ message: str,
+ *,
+ hint: str = "",
+ action: str = "",
+ json_mode: bool = False,
+ exit_code: int = 1,
+ ) -> None:
captured["message"] = message
captured["hint"] = hint
captured["json_mode"] = json_mode
raise SystemExit(exit_code)
- monkeypatch.setattr(browser_cmd, "output_error", _fake_output_error)
+ monkeypatch.setattr(output_mod, "output_error", _fake_output_error)
with pytest.raises(SystemExit, match="1"):
browser_cmd._emit_tool_result(
diff --git a/tests/unit/test_cli_telemetry.py b/tests/unit/test_cli_telemetry.py
new file mode 100644
index 000000000..d21b90876
--- /dev/null
+++ b/tests/unit/test_cli_telemetry.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from unittest.mock import Mock, patch
+
+from skyvern import analytics
+from skyvern.cli.core import telemetry
+
+
+def test_capture_cli_tool_call_uses_mcp_posthog_project() -> None:
+ fake_capture = Mock()
+
+ with patch.object(analytics, "capture", fake_capture):
+ telemetry.capture_cli_tool_call("skyvern_navigate", ok=True)
+
+ fake_capture.assert_called_once()
+ event_name = fake_capture.call_args.args[0]
+ kwargs = fake_capture.call_args.kwargs
+ assert event_name == "mcp_tool_call"
+ assert kwargs["data"]["tool"] == "skyvern_navigate"
+ assert kwargs["data"]["ok"] is True
+ assert kwargs["data"]["operation"] == "cli/call"
+ assert kwargs["data"]["runtime_mode"] == "cli"
+ assert kwargs["data"]["distinct_id_source"] == "analytics_id"
+ assert kwargs["distinct_id"] == analytics.settings.ANALYTICS_ID
+ assert kwargs["api_key"] == analytics.settings.MCP_POSTHOG_PROJECT_API_KEY
+ assert kwargs["host"] == analytics.settings.MCP_POSTHOG_PROJECT_HOST
+
+
+def test_capture_cli_tool_call_error_omits_error_message() -> None:
+ fake_capture = Mock()
+
+ with patch.object(analytics, "capture", fake_capture):
+ telemetry.capture_cli_tool_call("skyvern_click", ok=False, error=ValueError("do not leak this"))
+
+ payload = fake_capture.call_args.kwargs["data"]
+ assert payload["error_type"] == "ValueError"
+ assert "error_message" not in payload
+
+
+def test_flush_cli_telemetry_uses_mcp_posthog_project() -> None:
+ fake_flush = Mock()
+
+ with patch.object(analytics, "flush", fake_flush):
+ telemetry.flush_cli_telemetry()
+
+ fake_flush.assert_called_once_with(
+ api_key=analytics.settings.MCP_POSTHOG_PROJECT_API_KEY,
+ host=analytics.settings.MCP_POSTHOG_PROJECT_HOST,
+ )
+
+
+def test_register_cli_telemetry_flush_is_idempotent() -> None:
+ fake_register = Mock()
+ original = telemetry._flush_registered
+
+ try:
+ with patch("skyvern.cli.core.telemetry.atexit.register", fake_register):
+ telemetry._flush_registered = False
+ telemetry.register_cli_telemetry_flush()
+ telemetry.register_cli_telemetry_flush()
+
+ fake_register.assert_called_once_with(telemetry.flush_cli_telemetry)
+ finally:
+ telemetry._flush_registered = original
diff --git a/tests/unit/test_mcp_workflow_guidance.py b/tests/unit/test_mcp_workflow_guidance.py
index cec0a27d4..d3a089b0c 100644
--- a/tests/unit/test_mcp_workflow_guidance.py
+++ b/tests/unit/test_mcp_workflow_guidance.py
@@ -15,9 +15,12 @@ def test_build_workflow_prompt_guides_text_prompt_defaults() -> None:
def test_mcp_instructions_guide_text_prompt_defaults() -> None:
- assert "For **text_prompt** blocks, default to Skyvern Optimized by omitting both `model` and `llm_key`." in (
- mcp.instructions
- )
+ # text_prompt guidance moved to build_workflow prompt; instructions now focus on task classification.
+ assert "Task Classification" in mcp.instructions
+ assert "skyvern_validate" in mcp.instructions
+ assert "skyvern_extract" in mcp.instructions
+ assert "skyvern_act" in mcp.instructions
+ assert "skyvern_observe" in mcp.instructions
@pytest.mark.asyncio