Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(mcp): code-block lint + synthesize tools (Copilot connector, M4) (#7017)
Marc Kelechava56dc1c51de9f
diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 4df9cdd08..6756761df 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -82,6 +82,7 @@ from .browser_profiles import (skyvern_browser_profile_list,skyvern_browser_profile_update,)+from .code_block import skyvern_code_block_lint, skyvern_code_block_synthesizefrom .credential import (skyvern_credential_delete,skyvern_credential_get,@@ -438,6 +439,8 @@ mcp.tool(tags={"storage"}, annotations=_web_dest("Clear Local Storage"))(skyvern# -- Block discovery + validation (no browser needed) --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)+mcp.tool(tags={"block_discovery"}, annotations=_ro("Lint Code Block"))(skyvern_code_block_lint)+mcp.tool(tags={"block_discovery"}, annotations=_ro("Synthesize Code Block"))(skyvern_code_block_synthesize)# -- Organization settings (no browser needed) --mcp.tool(tags={"settings"}, annotations=_ro("Get Organization Settings"))(skyvern_org_get)@@ -562,6 +565,8 @@ __all__ = [# Block discovery + validation"skyvern_block_schema","skyvern_block_validate",+ "skyvern_code_block_lint",+ "skyvern_code_block_synthesize",# Organization settings"skyvern_org_get","skyvern_org_update",diff --git a/skyvern/cli/mcp_tools/code_block.py b/skyvern/cli/mcp_tools/code_block.pynew file mode 100644index 000000000..9655bfa9e--- /dev/null+++ b/skyvern/cli/mcp_tools/code_block.py@@ -0,0 +1,182 @@+"""Skyvern MCP code-block tools."""++from __future__ import annotations++import json+from typing import Annotated, Any++from pydantic import Field++from skyvern.forge.sdk.copilot.code_block_preflight import (+ CodeBlockPreflightDiagnostic,+ author_time_code_block_diagnostics,+ preflight_code_block,+ sandbox_unresolved_name_diagnostics,+)+from skyvern.forge.sdk.copilot.code_block_security import (+ CodeBlockSecurityError,+ author_time_code_security_errors,+)+from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_block++from ._common import ErrorCode, make_error, make_result+++def _serialize_diagnostic(diagnostic: CodeBlockPreflightDiagnostic) -> dict[str, str]:+ return {"code": diagnostic.code, "message": diagnostic.message}+++def _serialize_security_error(error: CodeBlockSecurityError) -> dict[str, str]:+ return {"reason_code": error.reason_code, "surface": error.surface, "message": str(error)}+++def _code_safety_errors(code: str) -> list[dict[str, str]]:+ # Keep workflow model imports deferred for the lightweight-install import contract.+ from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected # noqa: PLC0415+ from skyvern.forge.sdk.workflow.models.block import CodeBlock # noqa: PLC0415++ try:+ CodeBlock.is_safe_code(code)+ except SyntaxError:+ return []+ except InsecureCodeDetected as exc:+ return [{"message": str(exc)}]+ return []+++async def skyvern_code_block_lint(+ code: Annotated[str, Field(description="Python source of the code block to lint")],+ parameter_keys: Annotated[+ list[str] | None,+ Field(description="Workflow parameter keys the block may reference (treated as defined names)"),+ ] = None,+ label: Annotated[str, Field(description="Block label, used in security-error messages")] = "code_block",+) -> dict[str, Any]:+ """Lint a Workflow Copilot `code` block with the copilot's own deterministic gates.++ Runs CodeBlock.is_safe_code(), the security denylist+ (page.request/context/evaluate/evaluate_handle), the sandbox unresolved-name analysis,+ static preflight, and author-time AST diagnostics. Returns a structured pass/fail result.+ No browser session or API call required.+ """+ action = "skyvern_code_block_lint"+ keys = tuple(parameter_keys or ())++ code_safety_errors = _code_safety_errors(code)+ security_errors = author_time_code_security_errors(label=label, code=code)+ preflight = preflight_code_block(code, parameter_keys=keys)+ sandbox = sandbox_unresolved_name_diagnostics(code, parameter_keys=keys)+ author_time = author_time_code_block_diagnostics(code)++ # Author-time diagnostics stay advisory and are deliberately excluded from ok.+ ok = not (code_safety_errors or security_errors or preflight or sandbox)+ return make_result(+ action,+ ok=ok,+ data={+ "lint_ok": ok,+ "code_safety_errors": code_safety_errors,+ "security_errors": [_serialize_security_error(error) for error in security_errors],+ "preflight_diagnostics": [_serialize_diagnostic(diagnostic) for diagnostic in preflight],+ "sandbox_diagnostics": [_serialize_diagnostic(diagnostic) for diagnostic in sandbox],+ "author_time_diagnostics": [_serialize_diagnostic(diagnostic) for diagnostic in author_time],+ },+ warnings=[diagnostic.message for diagnostic in author_time],+ error=(+ None+ if ok+ else make_error(+ ErrorCode.INVALID_INPUT,+ "Code block failed copilot lint gates",+ "Fix the listed security/preflight/sandbox issues before persisting the block",+ )+ ),+ )+++async def skyvern_code_block_synthesize(+ trajectory_json: Annotated[+ str,+ Field(+ description=(+ "JSON array of captured interaction objects (the scout trajectory). Each object has "+ "tool_name plus selector/source_url/role/accessible_name/typed_value/value/key as "+ "applicable. This tool does NOT scout a live page - the trajectory is supplied by the caller."+ )+ ),+ ],+ strict_selectors: Annotated[+ bool,+ Field(description="Emit only the scout's captured selectors verbatim; drop ambiguous bare selectors"),+ ] = False,+) -> dict[str, Any]:+ """Deterministically synthesize a Playwright `code` block from a captured trajectory.++ Wraps the copilot's pure synthesize_code_block(): output is byte-identical per trajectory,+ with no LLM and no I/O. The trajectory is supplied by the caller - capturing a live trajectory+ (the scout) is out of scope for this tool.+ """+ action = "skyvern_code_block_synthesize"++ try:+ trajectory = json.loads(trajectory_json)+ except (json.JSONDecodeError, TypeError) as exc:+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Invalid trajectory JSON: {exc}",+ "Provide a JSON array of interaction objects",+ ),+ )++ if not isinstance(trajectory, list):+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Expected a JSON array, got {type(trajectory).__name__}",+ "Provide a JSON array of interaction objects",+ ),+ )++ for index, item in enumerate(trajectory):+ if not isinstance(item, dict):+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ f"Expected trajectory item at index {index} to be an object, got {type(item).__name__}",+ "Provide a JSON array of interaction objects",+ ),+ )++ synthesized = synthesize_code_block(trajectory, strict_selectors=strict_selectors)+ if synthesized is None:+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ "Trajectory produced no synthesizable steps",+ "Supply a non-empty trajectory with at least one actionable interaction",+ ),+ )++ return make_result(+ action,+ data={+ "code": synthesized.code,+ "parameters": synthesized.parameters,+ "steps": synthesized.steps,+ "notes": synthesized.notes,+ "emitted_interaction_count": synthesized.diagnostics.emitted_interaction_count,+ "truncated": synthesized.diagnostics.truncated,+ },+ )+++__all__ = ["skyvern_code_block_lint", "skyvern_code_block_synthesize"]diff --git a/tests/unit/test_code_block_lint_mcp_tool.py b/tests/unit/test_code_block_lint_mcp_tool.pynew file mode 100644index 000000000..b5d7acc71--- /dev/null+++ b/tests/unit/test_code_block_lint_mcp_tool.py@@ -0,0 +1,96 @@+"""Tests for the MCP code-block lint tool."""++from __future__ import annotations++import pytest++from skyvern.cli.mcp_tools.code_block import skyvern_code_block_lint+++def _has_security_error(result: dict, *, reason_code: str, surface: str | None = None) -> bool:+ return any(+ error["reason_code"] == reason_code and (surface is None or error["surface"] == surface)+ for error in result["data"]["security_errors"]+ )+++def _has_diagnostic(result: dict, *, section: str, code: str) -> bool:+ return any(diagnostic["code"] == code for diagnostic in result["data"][section])+++async def test_clean_code_block_lints_ok() -> None:+ code = 'await page.goto("https://example.com", wait_until="domcontentloaded")\nreturn {"ok": True}'++ result = await skyvern_code_block_lint(code=code)++ assert result["ok"] is True+ assert result["data"]["lint_ok"] is True+ assert result["data"]["code_safety_errors"] == []+ assert result["data"]["security_errors"] == []+ assert result["data"]["preflight_diagnostics"] == []+ assert result["data"]["sandbox_diagnostics"] == []+ assert result["data"]["author_time_diagnostics"] == []+++async def test_dunder_access_is_blocked_by_code_safety_gate() -> None:+ result = await skyvern_code_block_lint(code="x = page.__class__\nreturn {}")++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert result["data"]["code_safety_errors"]+ assert "private methods or attributes" in result["data"]["code_safety_errors"][0]["message"]+++async def test_import_is_blocked_by_code_safety_gate() -> None:+ result = await skyvern_code_block_lint(code="import os\nreturn {}")++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert result["data"]["code_safety_errors"]+ assert "Not allowed to import" in result["data"]["code_safety_errors"][0]["message"]+++async def test_page_evaluate_is_blocked_by_security_denylist() -> None:+ result = await skyvern_code_block_lint(code='await page.evaluate("1+1")')++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert _has_security_error(result, reason_code="AUTHOR_PAGE_EVALUATE", surface="page.evaluate")+++async def test_page_request_is_blocked_by_security_denylist() -> None:+ result = await skyvern_code_block_lint(code='await page.request.get("https://example.com")')++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert _has_security_error(result, reason_code="AUTHOR_PAGE_REQUEST")+++async def test_undefined_name_is_caught_by_sandbox_analyzer() -> None:+ result = await skyvern_code_block_lint(code="x = undefined_thing + 1\nreturn {}")++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert _has_diagnostic(result, section="sandbox_diagnostics", code="SANDBOX_UNRESOLVED_NAME")+++async def test_parameter_key_is_treated_as_defined_by_sandbox_analyzer() -> None:+ result = await skyvern_code_block_lint(code="x = query + 1\nreturn {}", parameter_keys=["query"])++ assert not any("query" in diagnostic["message"] for diagnostic in result["data"]["sandbox_diagnostics"])+++async def test_syntax_error_is_caught_by_preflight() -> None:+ result = await skyvern_code_block_lint(code="await page.goto( # unbalanced paren")++ assert result["ok"] is False+ assert result["data"]["lint_ok"] is False+ assert _has_diagnostic(result, section="preflight_diagnostics", code="SYNTAX_ERROR")diff --git a/tests/unit/test_code_block_synthesize_mcp_tool.py b/tests/unit/test_code_block_synthesize_mcp_tool.pynew file mode 100644index 000000000..586230f6f--- /dev/null+++ b/tests/unit/test_code_block_synthesize_mcp_tool.py@@ -0,0 +1,84 @@+"""Tests for the MCP code-block synthesis tool.++OSS-synced: only example.* / RFC-2606 placeholder targets.+"""++from __future__ import annotations++import json++import pytest++from skyvern.cli.mcp_tools.code_block import skyvern_code_block_synthesize+++def _fixture_trajectory() -> list[dict]:+ return [+ {+ "tool_name": "type_text",+ "selector": "#search",+ "source_url": "https://example.com/catalog",+ "typed_value": "widget",+ "role": "textbox",+ "accessible_name": "Search",+ },+ {+ "tool_name": "click",+ "selector": "#search-submit",+ "source_url": "https://example.com/catalog",+ "role": "button",+ "accessible_name": "Submit",+ },+ ]+++async def test_fixture_trajectory_synthesizes_non_empty_code_block() -> None:+ result = await skyvern_code_block_synthesize(json.dumps(_fixture_trajectory()))++ assert result["ok"] is True+ code = result["data"]["code"]+ assert "page.goto" in code # nosemgrep: incomplete-url-substring-sanitization+ assert "https://example.com/catalog" in code # nosemgrep: incomplete-url-substring-sanitization+ assert ".fill(" in code+ assert ".click()" in code+ assert result["data"]["emitted_interaction_count"] == 2+++async def test_same_trajectory_synthesizes_byte_identical_code() -> None:+ r1 = await skyvern_code_block_synthesize(json.dumps(_fixture_trajectory()))+ r2 = await skyvern_code_block_synthesize(json.dumps(_fixture_trajectory()))++ assert r1["data"]["code"] == r2["data"]["code"]+++async def test_empty_trajectory_is_rejected() -> None:+ result = await skyvern_code_block_synthesize(json.dumps([]))++ assert result["ok"] is False+++async def test_non_array_json_is_rejected() -> None:+ result = await skyvern_code_block_synthesize(json.dumps({"not": "a list"}))++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"++[email protected]("trajectory", ([1], ["click"]))+async def test_non_object_trajectory_items_are_rejected(trajectory: list[object]) -> None:+ result = await skyvern_code_block_synthesize(json.dumps(trajectory))++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"+++async def test_bad_json_is_rejected() -> None:+ result = await skyvern_code_block_synthesize("{not valid json")++ assert result["ok"] is False