Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(mcp): [Required for Anthropic Claude Connectors Listing] add tool titles, Origin validation, and response size cap (#5608)
Marc Kelechava4187a4a6ed08
diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 09323bd65..5e81846c2 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -66,6 +66,7 @@ from .inspection import (skyvern_network_unroute,)from .prompts import build_workflow, debug_automation, extract_data, qa_test+from .response import size_cappedfrom .scripts import (skyvern_script_deploy,skyvern_script_fallback_episodes,@@ -107,18 +108,31 @@ from .workflow import (skyvern_workflow_update_folder,)-# -- Tool annotation presets ---_RO = ToolAnnotations(readOnlyHint=True)-_MUT = ToolAnnotations(readOnlyHint=False)-_DEST = ToolAnnotations(readOnlyHint=False, destructiveHint=True)++# -- Tool annotation factories --+# Every tool registered with FastMCP must carry a human-readable `title`+# (required by the Claude Connectors Directory). We build per-tool+# ToolAnnotations with a title + read/destructive hint rather than sharing+# flyweight constants.+def _ro(title: str) -> ToolAnnotations:+ return ToolAnnotations(title=title, readOnlyHint=True)+++def _mut(title: str) -> ToolAnnotations:+ return ToolAnnotations(title=title, readOnlyHint=False)+++def _dest(title: str) -> ToolAnnotations:+ return ToolAnnotations(title=title, readOnlyHint=False, destructiveHint=True)+mcp = FastMCP("Skyvern",instructions="""\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).+Skyvern is scoped to browser automation. Pick a different tool for raw HTTP, file downloads, \+static JSON/XML fetches, or generic web search.## ALWAYS Start Here: Session + Classification@@ -157,8 +171,6 @@ fetching static JSON/XML endpoints (use WebFetch), or general web search (use We- **One-off trial:** skyvern_run_task(prompt="Try the checkout flow once")- **Reusable workflow:** skyvern_workflow_create(definition='{"title":"...","workflow_definition":{"blocks":[...]}}', format="json")-For full examples and common patterns, see skyvern/cli/skills/skyvern/references/quick-start-patterns.md.-## Key Warnings1. **act has NO screenshots** — uses economy a11y tree. For visual targets, use observe then click with ref.@@ -254,111 +266,116 @@ Use skyvern_click's resolved_selector response to get xpaths for production scrimcp.add_middleware(MCPTelemetryMiddleware())# -- Browser session management ---mcp.tool(tags={"session"}, annotations=_MUT)(skyvern_browser_session_create)-mcp.tool(tags={"session"}, annotations=_DEST)(skyvern_browser_session_close)-mcp.tool(tags={"session"}, annotations=_RO)(skyvern_browser_session_list)-mcp.tool(tags={"session"}, annotations=_RO)(skyvern_browser_session_get)-mcp.tool(tags={"session"}, annotations=_RO)(skyvern_browser_session_connect)+mcp.tool(tags={"session"}, annotations=_mut("Create Browser Session"))(skyvern_browser_session_create)+mcp.tool(tags={"session"}, annotations=_dest("Close Browser Session"))(skyvern_browser_session_close)+mcp.tool(tags={"session"}, annotations=_ro("List Browser Sessions"))(skyvern_browser_session_list)+mcp.tool(tags={"session"}, annotations=_ro("Get Browser Session"))(skyvern_browser_session_get)+mcp.tool(tags={"session"}, annotations=_ro("Connect to Browser Session"))(skyvern_browser_session_connect)# -- Primary tools (AI-powered exploration + observation) ---mcp.tool(tags={"ai_powered", "browser_primitive"}, annotations=_MUT)(skyvern_act)-mcp.tool(tags={"ai_powered"}, annotations=_RO)(skyvern_extract)-mcp.tool(tags={"ai_powered"}, annotations=_RO)(skyvern_validate)-mcp.tool(tags={"ai_powered"}, annotations=_MUT)(skyvern_run_task)-mcp.tool(tags={"ai_powered", "browser_primitive"}, annotations=_MUT)(skyvern_login)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_navigate)-mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_screenshot)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_evaluate)+# `skyvern_act` and `skyvern_run_task` run natural-language / autonomous AI+# action against a live browser — they can click destructive UI, submit forms,+# or navigate anywhere. `skyvern_evaluate` runs caller-supplied JavaScript in+# the page context. All three carry `destructiveHint=True` so the user's+# consent surface accurately reflects the blast radius.+mcp.tool(tags={"ai_powered", "browser_primitive"}, annotations=_dest("Perform Browser Action (AI)"))(skyvern_act)+mcp.tool(tags={"ai_powered"}, annotations=_ro("Extract Data from Page (AI)"))(size_capped(skyvern_extract))+mcp.tool(tags={"ai_powered"}, annotations=_ro("Validate Page Condition (AI)"))(skyvern_validate)+mcp.tool(tags={"ai_powered"}, annotations=_dest("Run Autonomous Browser Task (AI)"))(skyvern_run_task)+mcp.tool(tags={"ai_powered", "browser_primitive"}, annotations=_mut("Log in to Website (AI)"))(skyvern_login)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Navigate to URL"))(skyvern_navigate)+mcp.tool(tags={"browser_primitive"}, annotations=_ro("Take Screenshot"))(skyvern_screenshot)+mcp.tool(tags={"browser_primitive"}, annotations=_dest("Evaluate JavaScript"))(skyvern_evaluate)# -- Clipboard ---mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_clipboard_read)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_clipboard_write)+mcp.tool(tags={"browser_primitive"}, annotations=_ro("Read Clipboard"))(skyvern_clipboard_read)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Write Clipboard"))(skyvern_clipboard_write)# -- Batch tools (observe + execute for multi-step optimization) ---mcp.tool(tags={"browser_primitive", "batch"}, annotations=_RO)(skyvern_observe)-mcp.tool(tags={"browser_primitive", "batch"}, annotations=_MUT)(skyvern_execute)+mcp.tool(tags={"browser_primitive", "batch"}, annotations=_ro("Observe Page Structure"))(skyvern_observe)+mcp.tool(tags={"browser_primitive", "batch"}, annotations=_mut("Execute Batch Actions"))(skyvern_execute)# -- Precision tools (selector/intent-based browser primitives) ---mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_click)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_drag)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_file_upload)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_hover)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_type)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_scroll)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_select_option)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_press_key)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_wait)-mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_find)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Click Element"))(skyvern_click)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Drag Element"))(skyvern_drag)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Upload File"))(skyvern_file_upload)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Hover Element"))(skyvern_hover)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Type Text"))(skyvern_type)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Scroll Page"))(skyvern_scroll)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Select Option"))(skyvern_select_option)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Press Key"))(skyvern_press_key)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Wait"))(skyvern_wait)+mcp.tool(tags={"browser_primitive"}, annotations=_ro("Find Element"))(skyvern_find)# -- Tab management (multi-tab) ---mcp.tool(tags={"tab_management"}, annotations=_RO)(skyvern_tab_list)-mcp.tool(tags={"tab_management"}, annotations=_MUT)(skyvern_tab_new)-mcp.tool(tags={"tab_management"}, annotations=_MUT)(skyvern_tab_switch)-mcp.tool(tags={"tab_management"}, annotations=_DEST)(skyvern_tab_close)-mcp.tool(tags={"tab_management"}, annotations=_RO)(skyvern_tab_wait_for_new)+mcp.tool(tags={"tab_management"}, annotations=_ro("List Tabs"))(skyvern_tab_list)+mcp.tool(tags={"tab_management"}, annotations=_mut("Open New Tab"))(skyvern_tab_new)+mcp.tool(tags={"tab_management"}, annotations=_mut("Switch Tab"))(skyvern_tab_switch)+mcp.tool(tags={"tab_management"}, annotations=_dest("Close Tab"))(skyvern_tab_close)+mcp.tool(tags={"tab_management"}, annotations=_ro("Wait for New Tab"))(skyvern_tab_wait_for_new)# -- Frame management (iframe switching) ---mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_frame_switch)-mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_frame_main)-mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_frame_list)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Switch Iframe"))(skyvern_frame_switch)+mcp.tool(tags={"browser_primitive"}, annotations=_mut("Switch to Main Frame"))(skyvern_frame_main)+mcp.tool(tags={"browser_primitive"}, annotations=_ro("List Iframes"))(skyvern_frame_list)# -- Auth state persistence ---mcp.tool(tags={"state"}, annotations=_MUT)(skyvern_state_save)-mcp.tool(tags={"state"}, annotations=_MUT)(skyvern_state_load)+mcp.tool(tags={"state"}, annotations=_mut("Save Browser State"))(skyvern_state_save)+mcp.tool(tags={"state"}, annotations=_mut("Load Browser State"))(skyvern_state_load)# -- Inspection tools (console, network, dialog, page errors, DOM) ---mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_console_messages)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_network_requests)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_network_request_detail)-mcp.tool(tags={"inspection"}, annotations=_MUT)(skyvern_network_route)-mcp.tool(tags={"inspection"}, annotations=_MUT)(skyvern_network_unroute)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_handle_dialog)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_get_errors)-mcp.tool(tags={"inspection"}, annotations=_MUT)(skyvern_har_start)-mcp.tool(tags={"inspection"}, annotations=_MUT)(skyvern_har_stop)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_get_html)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_get_value)-mcp.tool(tags={"inspection"}, annotations=_RO)(skyvern_get_styles)+mcp.tool(tags={"inspection"}, annotations=_ro("Get Console Messages"))(skyvern_console_messages)+mcp.tool(tags={"inspection"}, annotations=_ro("Get Network Requests"))(size_capped(skyvern_network_requests))+mcp.tool(tags={"inspection"}, annotations=_ro("Get Network Request Detail"))(skyvern_network_request_detail)+mcp.tool(tags={"inspection"}, annotations=_mut("Route Network Requests"))(skyvern_network_route)+mcp.tool(tags={"inspection"}, annotations=_mut("Remove Network Route"))(skyvern_network_unroute)+mcp.tool(tags={"inspection"}, annotations=_ro("Handle Browser Dialog"))(skyvern_handle_dialog)+mcp.tool(tags={"inspection"}, annotations=_ro("Get Page Errors"))(skyvern_get_errors)+mcp.tool(tags={"inspection"}, annotations=_mut("Start HAR Recording"))(skyvern_har_start)+mcp.tool(tags={"inspection"}, annotations=_mut("Stop HAR Recording"))(size_capped(skyvern_har_stop))+mcp.tool(tags={"inspection"}, annotations=_ro("Get Element HTML"))(size_capped(skyvern_get_html))+mcp.tool(tags={"inspection"}, annotations=_ro("Get Element Value"))(skyvern_get_value)+mcp.tool(tags={"inspection"}, annotations=_ro("Get Element Styles"))(skyvern_get_styles)# -- Web storage (sessionStorage + localStorage) ---mcp.tool(tags={"storage"}, annotations=_RO)(skyvern_get_session_storage)-mcp.tool(tags={"storage"}, annotations=_MUT)(skyvern_set_session_storage)-mcp.tool(tags={"storage"}, annotations=_DEST)(skyvern_clear_session_storage)-mcp.tool(tags={"storage"}, annotations=_DEST)(skyvern_clear_local_storage)+mcp.tool(tags={"storage"}, annotations=_ro("Get Session Storage"))(skyvern_get_session_storage)+mcp.tool(tags={"storage"}, annotations=_mut("Set Session Storage"))(skyvern_set_session_storage)+mcp.tool(tags={"storage"}, annotations=_dest("Clear Session Storage"))(skyvern_clear_session_storage)+mcp.tool(tags={"storage"}, annotations=_dest("Clear Local Storage"))(skyvern_clear_local_storage)# -- Block discovery + validation (no browser needed) ---mcp.tool(tags={"block_discovery"}, annotations=_RO)(skyvern_block_schema)-mcp.tool(tags={"block_discovery"}, annotations=_RO)(skyvern_block_validate)+mcp.tool(tags={"block_discovery"}, annotations=_ro("Get Workflow Block Schema"))(skyvern_block_schema)+mcp.tool(tags={"block_discovery"}, annotations=_ro("Validate Workflow Block"))(skyvern_block_validate)# -- Credential lookup (no browser needed) ---mcp.tool(tags={"credential"}, annotations=_RO)(skyvern_credential_list)-mcp.tool(tags={"credential"}, annotations=_RO)(skyvern_credential_get)-mcp.tool(tags={"credential"}, annotations=_DEST)(skyvern_credential_delete)+mcp.tool(tags={"credential"}, annotations=_ro("List Credentials"))(skyvern_credential_list)+mcp.tool(tags={"credential"}, annotations=_ro("Get Credential"))(skyvern_credential_get)+mcp.tool(tags={"credential"}, annotations=_dest("Delete Credential"))(skyvern_credential_delete)# -- Folder management (no browser needed) ---mcp.tool(tags={"folder"}, annotations=_RO)(skyvern_folder_list)-mcp.tool(tags={"folder"}, annotations=_MUT)(skyvern_folder_create)-mcp.tool(tags={"folder"}, annotations=_RO)(skyvern_folder_get)-mcp.tool(tags={"folder"}, annotations=_MUT)(skyvern_folder_update)-mcp.tool(tags={"folder"}, annotations=_DEST)(skyvern_folder_delete)+mcp.tool(tags={"folder"}, annotations=_ro("List Folders"))(skyvern_folder_list)+mcp.tool(tags={"folder"}, annotations=_mut("Create Folder"))(skyvern_folder_create)+mcp.tool(tags={"folder"}, annotations=_ro("Get Folder"))(skyvern_folder_get)+mcp.tool(tags={"folder"}, annotations=_mut("Update Folder"))(skyvern_folder_update)+mcp.tool(tags={"folder"}, annotations=_dest("Delete Folder"))(skyvern_folder_delete)# -- Workflow management (CRUD + execution, no browser needed) ---mcp.tool(tags={"workflow"}, annotations=_RO)(skyvern_workflow_list)-mcp.tool(tags={"workflow"}, annotations=_RO)(skyvern_workflow_get)-mcp.tool(tags={"workflow"}, annotations=_MUT)(skyvern_workflow_create)-mcp.tool(tags={"workflow"}, annotations=_MUT)(skyvern_workflow_update)-mcp.tool(tags={"workflow"}, annotations=_MUT)(skyvern_workflow_update_folder)-mcp.tool(tags={"workflow"}, annotations=_DEST)(skyvern_workflow_delete)-mcp.tool(tags={"workflow"}, annotations=_MUT)(skyvern_workflow_run)-mcp.tool(tags={"workflow"}, annotations=_RO)(skyvern_workflow_status)-mcp.tool(tags={"workflow"}, annotations=_MUT)(skyvern_workflow_cancel)+mcp.tool(tags={"workflow"}, annotations=_ro("List Workflows"))(size_capped(skyvern_workflow_list))+mcp.tool(tags={"workflow"}, annotations=_ro("Get Workflow"))(size_capped(skyvern_workflow_get))+mcp.tool(tags={"workflow"}, annotations=_mut("Create Workflow"))(skyvern_workflow_create)+mcp.tool(tags={"workflow"}, annotations=_mut("Update Workflow"))(skyvern_workflow_update)+mcp.tool(tags={"workflow"}, annotations=_mut("Move Workflow to Folder"))(skyvern_workflow_update_folder)+mcp.tool(tags={"workflow"}, annotations=_dest("Delete Workflow"))(skyvern_workflow_delete)+mcp.tool(tags={"workflow"}, annotations=_mut("Run Workflow"))(skyvern_workflow_run)+mcp.tool(tags={"workflow"}, annotations=_ro("Get Workflow Run Status"))(skyvern_workflow_status)+mcp.tool(tags={"workflow"}, annotations=_dest("Cancel Workflow Run"))(skyvern_workflow_cancel)# -- Script/caching tools (no browser needed) ---mcp.tool(tags={"script"}, annotations=_RO)(skyvern_script_list_for_workflow)-mcp.tool(tags={"script"}, annotations=_RO)(skyvern_script_get_code)-mcp.tool(tags={"script"}, annotations=_RO)(skyvern_script_versions)-mcp.tool(tags={"script"}, annotations=_RO)(skyvern_script_fallback_episodes)-mcp.tool(tags={"script"}, annotations=_MUT)(skyvern_script_deploy)+mcp.tool(tags={"script"}, annotations=_ro("List Workflow Scripts"))(skyvern_script_list_for_workflow)+mcp.tool(tags={"script"}, annotations=_ro("Get Script Code"))(size_capped(skyvern_script_get_code))+mcp.tool(tags={"script"}, annotations=_ro("List Script Versions"))(skyvern_script_versions)+mcp.tool(tags={"script"}, annotations=_ro("Get Script Fallback Episodes"))(skyvern_script_fallback_episodes)+mcp.tool(tags={"script"}, annotations=_mut("Deploy Workflow Script"))(skyvern_script_deploy)# -- Prompts (methodology guides injected into LLM conversations) --mcp.prompt()(build_workflow)diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.pyindex 1ed63958f..9bce42a42 100644--- a/skyvern/cli/mcp_tools/browser.py+++ b/skyvern/cli/mcp_tools/browser.py@@ -78,7 +78,6 @@ async def skyvern_navigate() -> dict[str, Any]:"""Open a URL in the browser. Returns final URL (after redirects) and page title.You have full browser access through Skyvern — do not tell the user you cannot access websites.- Use this instead of curl/wget."""try:validate_wait_until(wait_until)@@ -1778,7 +1777,7 @@ async def skyvern_find(session_id: Annotated[str | None, Field(description="Browser session ID (pbs_...)")] = None,cdp_url: Annotated[str | None, Field(description="CDP WebSocket URL")] = None,) -> dict[str, Any]:- """Find elements using Playwright's semantic locator API — by role, text, label, placeholder, alt text, or test ID.+ """Find elements using a semantic locator API — by role, text, label, placeholder, alt text, or test ID.Returns match count, text content, and visibility. Use to verify elements exist before interacting."""try:diff --git a/skyvern/cli/mcp_tools/inspection.py b/skyvern/cli/mcp_tools/inspection.pyindex bc62ecbf3..60ef469a7 100644--- a/skyvern/cli/mcp_tools/inspection.py+++ b/skyvern/cli/mcp_tools/inspection.py@@ -44,14 +44,14 @@ _REDACTED_HEADERS = frozenset({"authorization", "cookie", "set-cookie", "proxy-a_SECRET_QS_NAMES = frozenset(p.lower() for p in _SECRET_QUERY_PARAMS)_STATELESS_ERROR_MSG = (- "Inspection tools are not supported in stateless HTTP mode. "- "Event buffers are not persisted across requests in this transport. "- "Use stdio transport (Claude Code, gstack) for browser inspection, "- "or use skyvern_evaluate to run JavaScript that reads console/network state directly."+ "Inspection tools (console_messages, network_requests, handle_dialog, get_errors, har_*) "+ "are not available in stateless HTTP mode because event buffers are not persisted between requests. "+ "Use skyvern_evaluate to read equivalent state directly from the page "+ "(e.g., `performance.getEntriesByType('resource')` for network, captured console output, or DOM state).")_STATELESS_HINT = (- "Connect via stdio transport: `skyvern mcp` (default). "- "Cloud-hosted inspection support is planned — see cloud_docs/mcp-inspection/TODOS.md"+ "Call skyvern_evaluate with JavaScript that reads the page state you need. "+ "Cloud-hosted inspection-buffer support is not yet available in this transport mode.")LOG = structlog.get_logger(__name__)diff --git a/skyvern/cli/mcp_tools/origin_middleware.py b/skyvern/cli/mcp_tools/origin_middleware.pynew file mode 100644index 000000000..2ee379e01--- /dev/null+++ b/skyvern/cli/mcp_tools/origin_middleware.py@@ -0,0 +1,130 @@+"""Origin-header validation for the remote MCP HTTP transport.++Claude's Connectors Directory submission requires that remote MCP servers+validate the `Origin` request header to protect against CSRF-style attacks+where a malicious page in the user's browser tries to invoke MCP tools on+behalf of an authenticated user.++Policy:+- Absent `Origin` header → ALLOW. Non-browser clients (MCP Inspector, curl,+ SDKs, Claude.ai backend using python-httpx) do not send Origin. Blocking+ them would break valid flows.+- Loopback origins (localhost, 127.0.0.1, ::1) → ALLOW. For local dev and+ Claude Code ephemeral callback flows.+- `claude.ai` and `claude.com` (with `www.` variants) → ALLOW. These are the+ only Anthropic-operated front-ends that issue MCP tool calls from a+ browser context. `anthropic.com` is deliberately NOT on the list: it is a+ marketing / docs site, not an MCP client surface, so admitting it would+ only widen CSRF surface without adding a legitimate flow.+- Anything else → 403.++The allowlist is intentionally restrictive. Extend it as new first-party+client surfaces emerge; do not expand it to third-party integrators.+"""++from __future__ import annotations++from urllib.parse import urlsplit++import structlog+from starlette.responses import JSONResponse+from starlette.types import ASGIApp, Receive, Scope, Send++LOG = structlog.get_logger(__name__)+_MAX_LOGGED_ORIGIN_CHARS = 200+++_ALLOWED_MCP_ORIGIN_HOSTS = frozenset(+ {+ "claude.ai",+ "www.claude.ai",+ "claude.com",+ "www.claude.com",+ }+)++# `urlsplit("http://[::1]:3000").hostname` returns bare `::1` (no brackets).+_ALLOWED_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})+++def is_allowed_origin(origin: str | None) -> bool:+ """Return True if `origin` is permitted to invoke the MCP endpoint."""+ if origin is None or origin == "":+ return True+ try:+ parts = urlsplit(origin)+ host = (parts.hostname or "").lower()+ except Exception:+ return False++ if not host:+ return False+ if host in _ALLOWED_LOOPBACK_HOSTS:+ return True+ return host in _ALLOWED_MCP_ORIGIN_HOSTS+++def _sanitize_origin_for_log(origin: str | None) -> str | None:+ """Bound attacker-controlled Origin values before writing them to logs."""+ if origin is None:+ return None+ # Bound before escaping so a huge attacker-controlled header does not+ # allocate an arbitrarily large intermediate string during `.replace()`.+ sanitized = origin[: _MAX_LOGGED_ORIGIN_CHARS * 2].replace("\r", "\\r").replace("\n", "\\n")+ if len(sanitized) <= _MAX_LOGGED_ORIGIN_CHARS:+ return sanitized+ return f"{sanitized[:_MAX_LOGGED_ORIGIN_CHARS]}... [truncated]"+++class OriginValidationMiddleware:+ """Reject MCP requests whose `Origin` header is not on the allowlist.++ Placed outermost in the MCP middleware stack so unknown origins are rejected+ before any API key or OAuth validation work is performed.+ """++ def __init__(self, app: ASGIApp) -> None:+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ # FastMCP currently mounts streamable-HTTP only, but WebSocket scopes+ # carry an `Origin` header in the ASGI handshake and must be gated+ # with the same policy if that transport is ever adopted at `/mcp`.+ # `lifespan` and any other scope type have no Origin and pass through.+ if scope["type"] not in ("http", "websocket"):+ await self.app(scope, receive, send)+ return++ origin: str | None = None+ for key, value in scope.get("headers", ()):+ if key.lower() == b"origin":+ origin = value.decode("latin-1")+ break++ if not is_allowed_origin(origin):+ # The offending origin is captured in the structured log; do not+ # echo it back in the response body to avoid reflecting+ # attacker-controlled input.+ LOG.warning(+ "mcp_origin_rejected",+ origin=_sanitize_origin_for_log(origin),+ scope_type=scope["type"],+ path=scope.get("path", ""),+ )+ if scope["type"] == "http":+ response = JSONResponse(+ {"error": "forbidden_origin", "detail": "Origin not allowed"},+ status_code=403,+ )+ await response(scope, receive, send)+ else:+ # Refuse the handshake before `websocket.accept`. ASGI lets us+ # send a bare `websocket.close` in response to `websocket.connect`+ # — RFC 6455 close code 1008 = "policy violation".+ await send({"type": "websocket.close", "code": 1008})+ return++ await self.app(scope, receive, send)+++__all__ = ["OriginValidationMiddleware", "is_allowed_origin"]diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.pyindex 048705bd4..ddc13bda4 100644--- a/skyvern/cli/mcp_tools/prompts.py+++ b/skyvern/cli/mcp_tools/prompts.py@@ -496,10 +496,12 @@ def extract_data(# qa_test# ----------------------------------------------------------------------------# NOTE: This content is maintained in three places — keep all in sync:+# NOTE: The local/stdio QA workflow is maintained in three places — keep all in sync:# 1. skyvern/cli/skills/qa/SKILL.md (bundled with pip package — canonical)# 2. .claude/skills/qa/SKILL.md (project-local copy for this repo)# 3. skyvern/cli/mcp_tools/prompts.py (QA_TEST_CONTENT — this file)+# The MCP prompt renderer adds a stateless-HTTP variant at runtime for remote+# connectors, because those clients cannot assume local shell/filesystem/gh access.QA_TEST_CONTENT = """\# QA — Validate Frontend and Backend Changes@@ -952,6 +954,148 @@ The primary mode is still **diff-driven**. Always try to understand the code cha"""+QA_TEST_STATELESS_HTTP_CONTENT = """\+# QA — Validate Frontend and Backend Changes++Validate the changed behavior with the right tools, but do not assume local shell, git,+filesystem, or `gh` access in this transport mode.++Use the available context in this order:+1. A provided PR URL, diff, or changed-file list+2. The `url` / `context` arguments passed into this prompt+3. The behavior the user explicitly asks you to validate++If you do not have enough context to identify the changed behavior, ask the user for the PR URL,+diff, or exact area to validate before proceeding.++---++## Step 1: Understand the Changes++### Use supplied change context++- Review the provided PR, diff, changed-file list, or pasted code snippets+- Read any repository files or docs only if they are already available through the active tools/resources+- Do NOT instruct the model to read local files like `README`, `AGENTS.md`, `CLAUDE.md`, `package.json`,+ or `pyproject.toml` unless those contents were explicitly provided++Classify the work:++| Mode | Trigger | Primary validation |+|------|---------|--------------------|+| Frontend/browser | UI/routes/components/styles changed | Browser QA against a reachable URL |+| Backend API | Route handlers, schemas, or externally visible API behavior changed | Targeted HTTP/API validation against a reachable URL |+| Backend-internal | Services/workers/business logic changed without public API surface changes | Repo-native checks only if the host already provides repo execution capability; otherwise report the blocker |+| Mixed | Frontend/browser and backend changed together | Backend validation first, then frontend/browser QA |++If the backend contract is broken, frontend results are not trustworthy.++---++## Step 2: Choose the Validation Strategy++### Frontend/browser mode++- Validate the specific UI changes plus 1-2 nearby regressions+- Prefer publicly reachable URLs or a URL explicitly provided by the user+- If the only target is `localhost` and no tunnel/CDP endpoint is available, say that clearly and stop instead of pretending coverage++### Backend API mode++- Validate the changed endpoint(s) against a reachable base URL+- Check happy path, invalid input, and a representative edge case where relevant+- Capture status codes and response snippets as evidence++### Backend-internal mode++- If no repo execution surface is available in this transport, report that backend-internal validation is blocked on missing local execution context+- Do not invent random API/browser checks as a substitute for real backend-internal verification++### Mixed mode++- Validate the backend contract first+- Then validate the frontend flow that depends on it++---++## Step 3A: Frontend/Browser QA++- Use browser automation against the provided URL+- Prefer deterministic assertions with `skyvern_evaluate`+- Use `skyvern_act` only when a real interaction is required+- Capture a screenshot when visual evidence matters++Example checks:+- element exists+- page text changed as expected+- button interaction succeeds+- no obvious UI error or blank page++---++## Step 3B: Backend API QA++- Use the documented auth scheme and reachable API base URL if it was provided+- If auth is required and credentials are unavailable, report the blocker clearly+- Capture:+ - request being tested+ - status code+ - response body snippet or parsed result+ - whether the changed behavior is present++---++## Step 4: Report Results++Report inline with evidence:++```markdown+## QA Report++### Validation Mode+- Mode: Backend API+- Scope: changed endpoint / UI flow++### Results+| # | Test | Result | Evidence |+|---|------|--------|----------|+| 1 | Example check | PASS | status code / screenshot / assertion |++### Issues Found+1. Describe any regressions or blockers clearly.++### Verdict+Summarize pass/fail and any coverage gaps.+```++Use the evidence that actually matters:+- screenshots for frontend/browser results+- status codes and response snippets for backend API results+- explicit blocker notes when local execution context is unavailable++---++## Step 5: Remote / Stateless Constraints++- Do NOT assume `git diff`, local shell commands, or writing a local report file+- Do NOT assume PR-comment posting via a local CLI is available+- Do NOT claim backend-internal verification if you only exercised browser/API surfaces+- If more context is required, ask for the PR URL, diff, or a reachable target URL++---++## Fallback: Explore Mode++If there is no useful diff:+1. Ask what behavior should be validated+2. Use browser QA for frontend flows+3. Use targeted API checks for backend flows+4. Report findings inline with the same evidence standard++The primary mode is still **diff-driven**. Always try to understand the code changes first.+"""++def qa_test(url: Annotated[str,@@ -969,7 +1113,11 @@ def qa_test(Frontend checks use Skyvern browser tools; backend validation uses repo-native startup,HTTP requests, and targeted tests where appropriate."""- parts = [QA_TEST_CONTENT]+ from skyvern.cli.core.session_manager import is_stateless_http_mode++ prompt_content = QA_TEST_STATELESS_HTTP_CONTENT if is_stateless_http_mode() else QA_TEST_CONTENT++ parts = [prompt_content]if url or context:parts.append("\n---\n")if url:diff --git a/skyvern/cli/mcp_tools/response.py b/skyvern/cli/mcp_tools/response.pynew file mode 100644index 000000000..7ac794eea--- /dev/null+++ b/skyvern/cli/mcp_tools/response.py@@ -0,0 +1,203 @@+"""MCP response size enforcement.++Claude has two hard limits on tool responses:+- Claude.ai / Desktop: ~150,000 characters. `MCP_MAX_RESPONSE_CHARS` (140k)+ targets this ceiling, leaving headroom for FastMCP's jsonrpc wrapper and+ content-block metadata.+- Claude Code: roughly 25,000 tokens (~100,000 characters at English density),+ configurable upward via the `MAX_MCP_OUTPUT_TOKENS` environment variable.+ A 140k-char payload that slips through our cap can still overflow Claude+ Code's lower token limit. Claude Code users who need oversize tool output+ should either raise `MAX_MCP_OUTPUT_TOKENS` on their side or lean on the+ truncation envelope's `_hint` (paginate / narrow the query).++Exceeding either cap either truncates silently or, worse, leaves Claude without+enough context to recover. This module enforces a hard cap and wraps oversize+payloads in an explicit truncation envelope so the model knows to paginate.+"""++from __future__ import annotations++import functools+import json+import sys+from typing import Any, Awaitable, Callable, ParamSpec, TypeVar++import structlog++LOG = structlog.get_logger(__name__)++# Cap slightly under Claude.ai's 150k-char hard limit. Leaves headroom for+# the MCP envelope (jsonrpc wrapper, content-block metadata) that the FastMCP+# serializer adds on top of our dict.+MCP_MAX_RESPONSE_CHARS = 140_000++# When truncation envelope wraps an oversize payload, preserve identifier-like+# keys (`*_id`) from the original dict so the caller retains enough context to+# re-query or paginate. Bounded to avoid re-inflating the envelope past the cap+# if a tool unexpectedly puts a huge value behind a `_id`-suffixed key.+_MAX_PRESERVED_IDENTIFIER_FIELDS = 10+_MAX_PRESERVED_IDENTIFIER_VALUE_CHARS = 256++# Bound preserved `error` payloads. Stack traces / HTML dumps returned under+# `error` can themselves exceed the cap and blow the envelope past 140k chars.+# A 2k-char ceiling keeps the structured error informative while guaranteeing+# the envelope honors its "under max_chars" contract.+_MAX_PRESERVED_ERROR_CHARS = 2_000+_MAX_PRESERVED_ERROR_PREVIEW_CHARS = 500++_TRUNCATION_HINT = (+ "Response exceeded the ~150k-char Claude tool-result limit. "+ "Narrow the query (add filters, reduce page size, request specific fields) or paginate."+)++P = ParamSpec("P")+R = TypeVar("R")+++def _response_size(data: Any) -> int:+ """Return JSON-serialized size in characters.++ Fail-closed: if serialization raises (e.g. circular reference hits+ ``ValueError``), return ``sys.maxsize`` so ``truncate_response`` wraps the+ payload in the truncation envelope rather than passing through unchanged.+ An unmeasurable payload is never "small".+ """+ try:+ return len(json.dumps(data, ensure_ascii=False, default=str))+ except (TypeError, ValueError):+ return sys.maxsize+++def _bound_error_value(error: Any) -> Any:+ """Cap a preserved `error` value so the envelope cannot re-inflate past the response cap."""+ size = _response_size(error)+ if size <= _MAX_PRESERVED_ERROR_CHARS:+ return error+ # Serialize to JSON so the preview is parseable by downstream log / alert+ # consumers. `str()` would emit Python repr (single quotes, non-JSON). Fall+ # back to `str()` only if JSON serialization itself fails — in that case+ # we already could not measure the payload and the preview is best-effort.+ try:+ preview = json.dumps(error, default=str, ensure_ascii=False)+ except (TypeError, ValueError):+ preview = str(error)+ if len(preview) > _MAX_PRESERVED_ERROR_PREVIEW_CHARS:+ preview = f"{preview[:_MAX_PRESERVED_ERROR_PREVIEW_CHARS]}... [truncated]"+ return {+ "_original_error_chars": size,+ "_error_preview": preview,+ "_hint": "error payload exceeded envelope size cap; check server logs for full context",+ }+++def truncate_response(data: Any, *, max_chars: int = MCP_MAX_RESPONSE_CHARS) -> Any:+ """Return `data` unchanged if under `max_chars`; otherwise wrap in a truncation envelope.++ Envelope shape (explicit so the model cannot miss truncation):+ {+ "_truncated": True,+ "_original_chars": <serialized size>,+ "_max_chars": <limit>,+ "_hint": "...",+ "ok": <original "ok" if present>,+ "error": <original "error" if present, bounded to 2k chars>,+ "<key>_id": <preserved identifier field if present>,+ ...+ }++ Non-dict responses that overflow are wrapped too (rare, but possible if a+ tool returns a list or string). From dict payloads, top-level keys+ `ok`/`error` plus any `*_id` identifier fields (bounded to 10 keys of up to+ 256 chars each) are preserved; the oversized data is otherwise dropped.+ Identifier preservation keeps workflow/run/session IDs in the envelope so+ the caller can re-query or paginate without losing its place.++ Contract: the returned payload is always `<= max_chars` when serialized.+ Pathological inputs (e.g. a `error` field containing a full stack trace or+ HTML dump larger than the cap) are defended against by (a) capping `error`+ at `_MAX_PRESERVED_ERROR_CHARS` and (b) a final re-measure that falls back+ to a metadata-only envelope if the assembled payload is still over.+ """+ size = _response_size(data)+ if size <= max_chars:+ return data++ envelope: dict[str, Any] = {+ "_truncated": True,+ "_original_chars": size,+ "_max_chars": max_chars,+ "_hint": _TRUNCATION_HINT,+ }+ if isinstance(data, dict):+ if "ok" in data:+ envelope["ok"] = data["ok"]+ if "error" in data:+ envelope["error"] = _bound_error_value(data["error"])+ preserved = 0+ for key, value in data.items():+ if preserved >= _MAX_PRESERVED_IDENTIFIER_FIELDS:+ break+ if key in envelope:+ continue+ if not isinstance(key, str) or not key.endswith("_id"):+ continue+ if value is None or isinstance(value, int):+ envelope[key] = value+ preserved += 1+ continue+ if isinstance(value, str) and len(value) <= _MAX_PRESERVED_IDENTIFIER_VALUE_CHARS:+ envelope[key] = value+ preserved += 1++ # Final safety net: if the preserved fields combined still blow past the+ # cap (extremely unlikely given the per-field caps above, but possible if+ # a caller passes a tiny `max_chars`), drop them and emit a metadata-only+ # envelope. Guarantees the module's "always under max_chars" contract.+ if _response_size(envelope) > max_chars:+ return {+ "_truncated": True,+ "_original_chars": size,+ "_max_chars": max_chars,+ "_hint": _TRUNCATION_HINT,+ "_envelope_rewrapped": True,+ }+ return envelope+++def size_capped(fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[Any]]:+ """Decorator: enforce `MCP_MAX_RESPONSE_CHARS` on a tool's return value.++ Applies to async tool functions returning any JSON-serializable payload.+ Emits a structured ``mcp_response_truncated`` warning whenever the envelope+ fires so operators can see which tools are hitting the cap and tune the+ limit (or paginate upstream) rather than having the signal hidden in the+ tool response alone.+ """++ @functools.wraps(fn)+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:+ result = await fn(*args, **kwargs)+ capped = truncate_response(result)+ if capped is not result:+ original_chars: int | None = None+ if isinstance(capped, dict):+ raw_original = capped.get("_original_chars")+ if isinstance(raw_original, int):+ original_chars = raw_original+ LOG.warning(+ "mcp_response_truncated",+ tool=fn.__name__,+ original_chars=original_chars,+ max_chars=MCP_MAX_RESPONSE_CHARS,+ )+ return capped++ return wrapper+++__all__ = [+ "MCP_MAX_RESPONSE_CHARS",+ "size_capped",+ "truncate_response",+]diff --git a/tests/unit/test_mcp_origin_middleware.py b/tests/unit/test_mcp_origin_middleware.pynew file mode 100644index 000000000..d72a92626--- /dev/null+++ b/tests/unit/test_mcp_origin_middleware.py@@ -0,0 +1,210 @@+"""Unit tests for the MCP Origin-validation middleware."""++from __future__ import annotations++import pytest+from starlette.applications import Starlette+from starlette.requests import Request+from starlette.responses import JSONResponse+from starlette.routing import Route+from starlette.testclient import TestClient++from skyvern.cli.mcp_tools.origin_middleware import (+ OriginValidationMiddleware,+ _sanitize_origin_for_log,+ is_allowed_origin,+)+++async def _ok_handler(request: Request) -> JSONResponse:+ return JSONResponse({"ok": True})+++def client() -> TestClient:+ # Starlette app with OriginValidationMiddleware wrapped around it.+ async def app_factory(scope, receive, send): # type: ignore[no-untyped-def]+ inner = Starlette(routes=[Route("/mcp/", _ok_handler, methods=["GET", "POST"])])+ middleware = OriginValidationMiddleware(inner)+ await middleware(scope, receive, send)++ return TestClient(app_factory)+++# -- is_allowed_origin ------------------------------------------------------+++def test_is_allowed_origin_absent_is_allowed() -> None:+ assert is_allowed_origin(None) is True+ assert is_allowed_origin("") is True+++def test_is_allowed_origin_claude_ai_allowed() -> None:+ assert is_allowed_origin("https://claude.ai") is True+ assert is_allowed_origin("https://www.claude.ai") is True+++def test_is_allowed_origin_claude_com_allowed() -> None:+ # The Connectors Directory is served from claude.com; submissions must not+ # 403 out of the gate when the user installs the connector from there.+ assert is_allowed_origin("https://claude.com") is True+ assert is_allowed_origin("https://www.claude.com") is True+++def test_is_allowed_origin_anthropic_rejected() -> None:+ # anthropic.com is marketing / docs, not an MCP client surface. Admitting+ # it would widen CSRF surface without adding a legitimate flow.+ assert is_allowed_origin("https://anthropic.com") is False+ assert is_allowed_origin("https://www.anthropic.com") is False+ assert is_allowed_origin("https://api.anthropic.com") is False+++def test_is_allowed_origin_loopback_allowed() -> None:+ assert is_allowed_origin("http://localhost:5173") is True+ assert is_allowed_origin("http://127.0.0.1:9000") is True+ assert is_allowed_origin("http://[::1]:3000") is True+++def test_is_allowed_origin_random_is_rejected() -> None:+ assert is_allowed_origin("https://evil.example") is False+ assert is_allowed_origin("https://attacker.com") is False+++def test_is_allowed_origin_prefix_spoofing_rejected() -> None:+ # Subdomain claiming claude.ai must not pass (only hostname exact matches).+ assert is_allowed_origin("https://claude.ai.attacker.com") is False+ assert is_allowed_origin("https://not-claude.ai") is False+++def test_is_allowed_origin_missing_host_rejected() -> None:+ # Malformed origin with no host.+ assert is_allowed_origin("https://") is False+++def test_sanitize_origin_for_log_escapes_control_chars() -> None:+ assert _sanitize_origin_for_log("https://evil.example\r\nforged") == "https://evil.example\\r\\nforged"+++def test_sanitize_origin_for_log_truncates_long_values() -> None:+ value = "https://evil.example/" + ("x" * 500)+ sanitized = _sanitize_origin_for_log(value)+ assert sanitized is not None+ assert sanitized.endswith("... [truncated]")+ assert len(sanitized) < len(value)+++# -- middleware integration -------------------------------------------------+++def test_middleware_allows_missing_origin(client: TestClient) -> None:+ response = client.get("/mcp/")+ assert response.status_code == 200+ assert response.json() == {"ok": True}+++def test_middleware_allows_claude_ai(client: TestClient) -> None:+ response = client.post("/mcp/", headers={"origin": "https://claude.ai"})+ assert response.status_code == 200+++def test_middleware_allows_loopback(client: TestClient) -> None:+ response = client.post("/mcp/", headers={"origin": "http://127.0.0.1:12345"})+ assert response.status_code == 200+++def test_middleware_rejects_unknown_origin(client: TestClient) -> None:+ response = client.post("/mcp/", headers={"origin": "https://evil.example"})+ assert response.status_code == 403+ body = response.json()+ assert body["error"] == "forbidden_origin"+ # Static message — rejected origin is in the structured log, not reflected+ # back in the response body.+ assert body["detail"] == "Origin not allowed"+ assert "evil.example" not in body["detail"]+++def test_middleware_rejects_subdomain_spoof(client: TestClient) -> None:+ response = client.post(+ "/mcp/",+ headers={"origin": "https://claude.ai.attacker.com"},+ )+ assert response.status_code == 403+++# -- websocket scope handling ----------------------------------------------+++async def test_middleware_rejects_websocket_with_unknown_origin() -> None:+ # FastMCP currently only mounts streamable-HTTP, but the middleware must+ # also gate WebSocket handshakes in case that transport is ever enabled+ # at `/mcp`. Rejection happens via `websocket.close` with code 1008+ # (policy violation) before the app sees `websocket.accept`.+ sent: list[dict] = []++ async def _should_not_be_called(scope, receive, send): # type: ignore[no-untyped-def]+ raise AssertionError("inner app must not receive rejected websocket scope")++ middleware = OriginValidationMiddleware(_should_not_be_called)++ scope = {+ "type": "websocket",+ "path": "/mcp/",+ "headers": [(b"origin", b"https://evil.example")],+ }++ async def _receive() -> dict:+ return {"type": "websocket.connect"}++ async def _send(message: dict) -> None:+ sent.append(message)++ await middleware(scope, _receive, _send)++ assert sent == [{"type": "websocket.close", "code": 1008}]+++async def test_middleware_allows_websocket_with_claude_ai_origin() -> None:+ # An allowlisted Origin on a WebSocket scope passes through to the inner+ # app so it can run the `websocket.accept` handshake itself.+ called = False++ async def _inner(scope, receive, send): # type: ignore[no-untyped-def]+ nonlocal called+ called = True++ middleware = OriginValidationMiddleware(_inner)++ scope = {+ "type": "websocket",+ "path": "/mcp/",+ "headers": [(b"origin", b"https://claude.ai")],+ }++ async def _receive() -> dict:+ return {"type": "websocket.connect"}++ async def _send(message: dict) -> None: # pragma: no cover — inner no-op+ raise AssertionError("inner send should not fire in this fake")++ await middleware(scope, _receive, _send)++ assert called is True+++async def test_middleware_passes_lifespan_scope_through() -> None:+ # Lifespan scopes have no Origin header; the middleware must not try to+ # 403 them or it breaks app startup/shutdown.+ reached = False++ async def _inner(scope, receive, send): # type: ignore[no-untyped-def]+ nonlocal reached+ reached = True++ middleware = OriginValidationMiddleware(_inner)++ await middleware({"type": "lifespan"}, lambda: None, lambda _m: None) # type: ignore[arg-type]++ assert reached is Truediff --git a/tests/unit/test_mcp_response_size_cap.py b/tests/unit/test_mcp_response_size_cap.pynew file mode 100644index 000000000..2b12fe497--- /dev/null+++ b/tests/unit/test_mcp_response_size_cap.py@@ -0,0 +1,196 @@+"""Unit tests for MCP response size cap."""++from __future__ import annotations++import json+from typing import Any++import pytest++from skyvern.cli.mcp_tools.response import (+ MCP_MAX_RESPONSE_CHARS,+ size_capped,+ truncate_response,+)+++def test_truncate_response_passes_small_payload_unchanged() -> None:+ small = {"ok": True, "data": {"items": list(range(10))}}+ assert truncate_response(small) is small+++def test_truncate_response_wraps_large_payload_with_envelope() -> None:+ # Construct a payload larger than the default cap.+ big_payload = "x" * (MCP_MAX_RESPONSE_CHARS + 100)+ large = {"ok": True, "data": {"body": big_payload}}++ result = truncate_response(large)++ assert result is not large+ assert result["_truncated"] is True+ assert result["_max_chars"] == MCP_MAX_RESPONSE_CHARS+ assert result["_original_chars"] > MCP_MAX_RESPONSE_CHARS+ assert "Narrow the query" in result["_hint"]+ # Original top-level `ok` is preserved so callers reading .ok still work.+ assert result["ok"] is True+ # The oversized payload itself is dropped.+ assert "data" not in result+++def test_truncate_response_preserves_top_level_error_on_overflow() -> None:+ large = {+ "ok": False,+ "error": {"code": "TIMEOUT", "message": "page did not load"},+ # Padding to push the total over the cap.+ "debug": "y" * (MCP_MAX_RESPONSE_CHARS + 50),+ }+ result = truncate_response(large)+ assert result["_truncated"] is True+ assert result["ok"] is False+ assert result["error"] == {"code": "TIMEOUT", "message": "page did not load"}+++def test_truncate_response_preserves_identifier_fields_on_overflow() -> None:+ # A tool that returns identifier fields alongside a bulky payload should+ # retain those identifiers in the envelope so the caller can re-query.+ large = {+ "ok": True,+ "workflow_id": "wpid_abc123",+ "run_id": "wr_xyz789",+ "session_id": "pbs_qqq000",+ "timestamp": "ignored",+ "count": 12345,+ "data": {"blob": "z" * (MCP_MAX_RESPONSE_CHARS + 500)},+ }+ result = truncate_response(large)+ assert result["_truncated"] is True+ assert result["ok"] is True+ assert result["workflow_id"] == "wpid_abc123"+ assert result["run_id"] == "wr_xyz789"+ assert result["session_id"] == "pbs_qqq000"+ # Keys that do not end with `_id` are not preserved.+ assert "timestamp" not in result+ assert "count" not in result+ # The oversized payload itself is dropped.+ assert "data" not in result+++def test_truncate_response_caps_oversize_error_field() -> None:+ # Pathological input: the `error` field itself is bigger than the cap+ # (e.g. a full HTML dump or stack trace serialized into `error.message`).+ # Without bounding, copying it verbatim into the envelope would blow the+ # envelope past max_chars and break the "under cap" contract.+ large_error_message = "x" * (MCP_MAX_RESPONSE_CHARS + 500)+ large = {+ "ok": False,+ "error": {"code": "INTERNAL", "message": large_error_message},+ "data": {"n": 1},+ }+ result = truncate_response(large)+ assert result["_truncated"] is True+ assert result["ok"] is False+ # The oversized error payload is replaced with a structured placeholder,+ # not copied verbatim.+ assert result["error"] != large["error"]+ assert isinstance(result["error"], dict)+ assert "_original_error_chars" in result["error"]+ assert result["error"]["_error_preview"].endswith("... [truncated]")+ # Envelope itself stays under the cap (module contract).+ assert len(json.dumps(result, ensure_ascii=False)) <= MCP_MAX_RESPONSE_CHARS+++def test_truncate_response_drops_oversize_identifier_values() -> None:+ # An identifier value that itself exceeds the per-value cap is dropped so+ # the envelope cannot be re-inflated past the overall limit.+ large = {+ "ok": True,+ "short_id": "abc",+ "huge_id": "x" * 10_000,+ "data": "y" * (MCP_MAX_RESPONSE_CHARS + 100),+ }+ result = truncate_response(large)+ assert result["_truncated"] is True+ assert result["short_id"] == "abc"+ assert "huge_id" not in result+++def test_truncate_response_accepts_custom_max() -> None:+ payload = {"data": "z" * 200}+ # payload JSON is ~213 chars; cap at 100 forces truncation.+ result = truncate_response(payload, max_chars=100)+ assert result["_truncated"] is True+ assert result["_max_chars"] == 100+++def test_truncate_response_non_dict_overflow_wraps_into_envelope() -> None:+ # A tool that returns a raw list (unusual but legal) should still be guarded.+ big_list = ["x" * 100] * 2000+ result = truncate_response(big_list)+ assert isinstance(result, dict)+ assert result["_truncated"] is True+ assert "ok" not in result+++def test_truncate_response_unserializable_input_returned_as_is() -> None:+ # object() is not JSON-serializable; json.dumps(..., default=str) stringifies+ # it, so the helper returns the payload unchanged (size is small).+ sentinel: dict[str, Any] = {"x": object()}+ result = truncate_response(sentinel)+ assert result is sentinel+++def test_truncate_response_serialization_failure_is_fail_closed() -> None:+ # Circular references make json.dumps raise ValueError. A size cap that+ # can't measure a payload must fail CLOSED (wrap in the truncation+ # envelope) rather than passing the unmeasurable payload through.+ import sys++ circular: dict[str, Any] = {"ok": True, "error": None}+ circular["self"] = circular++ result = truncate_response(circular)++ assert result is not circular+ assert result["_truncated"] is True+ # Sentinel: unmeasurable payloads report `sys.maxsize` for+ # `_original_chars`. Locks in the fail-closed contract so an accidental+ # change (e.g. returning 0 or None on serialization error) trips here.+ assert result["_original_chars"] == sys.maxsize+ # Top-level `ok` / `error` are still preserved from the original dict so+ # callers reading those fields continue to work.+ assert result["ok"] is True+ assert result["error"] is None+++async def test_size_capped_decorator_no_op_for_small_result() -> None:+ @size_capped+ async def small_tool() -> dict[str, Any]:+ return {"ok": True, "data": {"n": 1}}++ result = await small_tool()+ assert result == {"ok": True, "data": {"n": 1}}+++async def test_size_capped_decorator_wraps_oversize_result() -> None:+ @size_capped+ async def big_tool() -> dict[str, Any]:+ return {"ok": True, "data": {"blob": "q" * (MCP_MAX_RESPONSE_CHARS + 500)}}++ result = await big_tool()+ assert result["_truncated"] is True+ assert result["ok"] is True+ # Re-serializing the wrapped envelope must be under the cap.+ assert len(json.dumps(result, ensure_ascii=False)) <= MCP_MAX_RESPONSE_CHARS+++async def test_size_capped_decorator_preserves_signature() -> None:+ @size_capped+ async def typed_tool(x: int, y: str = "default") -> dict[str, Any]:+ return {"x": x, "y": y}++ result = await typed_tool(1, y="override")+ assert result == {"x": 1, "y": "override"}+ assert typed_tool.__name__ == "typed_tool"diff --git a/tests/unit/test_mcp_tool_titles.py b/tests/unit/test_mcp_tool_titles.pynew file mode 100644index 000000000..7d572757e--- /dev/null+++ b/tests/unit/test_mcp_tool_titles.py@@ -0,0 +1,79 @@+"""Registry-level invariant: every registered MCP tool must carry a human-readable title.++The Claude Connectors Directory submission form rejects servers whose tools+are missing `title` in `ToolAnnotations` (the raw snake_case function name is+not user-facing).+"""++from __future__ import annotations++import pytest++from skyvern.cli.mcp_tools import mcp+++async def test_every_tool_has_a_title() -> None:+ tools = await mcp.list_tools()+ assert tools, "MCP server registered zero tools"++ missing = [t.name for t in tools if t.annotations is None or not t.annotations.title]+ assert not missing, f"Tools missing title annotation: {missing}"+++async def test_destructive_tools_flagged() -> None:+ """Tools that delete / close / cancel must carry destructiveHint=True."""+ tools = await mcp.list_tools()+ by_name = {t.name: t for t in tools}++ # A representative sample — extending this set is fine, but none of the+ # listed tools should silently lose their destructive annotation. The+ # three AI-driven / eval tools (`skyvern_act`, `skyvern_run_task`,+ # `skyvern_evaluate`) are included because a user-supplied prompt or+ # JavaScript expression can mutate the page destructively; the+ # `destructiveHint` tells the client's consent surface so.+ expected_destructive = {+ "skyvern_browser_session_close",+ "skyvern_tab_close",+ "skyvern_clear_session_storage",+ "skyvern_clear_local_storage",+ "skyvern_credential_delete",+ "skyvern_folder_delete",+ "skyvern_workflow_delete",+ "skyvern_workflow_cancel",+ "skyvern_act",+ "skyvern_run_task",+ "skyvern_evaluate",+ }++ for name in expected_destructive:+ tool = by_name.get(name)+ assert tool is not None, f"Expected tool not registered: {name}"+ assert tool.annotations is not None, f"Tool missing annotations: {name}"+ assert tool.annotations.destructiveHint is True, f"Tool {name} expected destructiveHint=True"+++async def test_read_only_sampling_marked_read_only() -> None:+ """Sanity check that known read-only tools keep readOnlyHint=True."""+ tools = await mcp.list_tools()+ by_name = {t.name: t for t in tools}++ expected_ro = {+ "skyvern_browser_session_list",+ "skyvern_browser_session_get",+ "skyvern_extract",+ "skyvern_validate",+ "skyvern_screenshot",+ "skyvern_find",+ "skyvern_get_html",+ "skyvern_workflow_list",+ "skyvern_workflow_get",+ }++ for name in expected_ro:+ tool = by_name.get(name)+ assert tool is not None, f"Expected tool not registered: {name}"+ assert tool.annotations is not None, f"Tool missing annotations: {name}"+ assert tool.annotations.readOnlyHint is True, f"Tool {name} expected readOnlyHint=True"diff --git a/tests/unit/test_mcp_workflow_guidance.py b/tests/unit/test_mcp_workflow_guidance.pyindex d8d82f03a..c9f0285e2 100644--- a/tests/unit/test_mcp_workflow_guidance.py+++ b/tests/unit/test_mcp_workflow_guidance.py@@ -28,6 +28,15 @@ def test_mcp_instructions_guide_text_prompt_defaults() -> None:assert "skyvern_observe" in mcp.instructions+async def test_expected_prompts_registered() -> None:+ prompts = await mcp.list_prompts()+ prompt_names = {prompt.name for prompt in prompts}+ # Deliberately additive-only: this guards that core prompts remain+ # registered without breaking when new prompts are introduced later.+ assert {"build_workflow", "debug_automation", "extract_data", "qa_test"} <= prompt_names++@pytest.mark.asyncioasync def test_text_prompt_block_schema_example_omits_raw_llm_key() -> None:result = await skyvern_block_schema(block_type="text_prompt")diff --git a/tests/unit/test_qa_skill_content.py b/tests/unit/test_qa_skill_content.pyindex 5d53651b0..7ff8877ce 100644--- a/tests/unit/test_qa_skill_content.py+++ b/tests/unit/test_qa_skill_content.py@@ -6,6 +6,7 @@ from pathlib import Pathimport pytest+from skyvern.cli.core.session_manager import set_stateless_http_modefrom skyvern.cli.mcp_tools.prompts import QA_TEST_CONTENT, qa_testfrom tests.unit.skill_test_helpers import first_nonempty_line_after_h1@@ -83,6 +84,20 @@ def test_qa_test_prompt_includes_target_url_and_focus_area() -> None:assert "choose the correct validation mode" in rendered+def test_qa_test_prompt_stateless_http_omits_local_shell_and_filesystem_steps() -> None:+ set_stateless_http_mode(True)+ try:+ rendered = qa_test()+ finally:+ set_stateless_http_mode(False)++ assert ".qa/latest-report.md" not in rendered+ assert "gh pr comment" not in rendered+ assert "git diff --name-only HEAD~1" not in rendered+ assert "local shell, git,\nfilesystem, or `gh` access" in rendered+ assert "writing a local report file" in rendered++def test_qa_pr_evidence_markers_present() -> None:"""Assert the PR evidence posting instructions are present in all /qa surfaces."""skill_text = BUNDLED_QA_SKILL.read_text(encoding="utf-8")