Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
MCP-created code blocks default to the new code block editor experience (#7697)
Aaron Perez54ad2876e5eb
diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.pyindex ca4c1610c..3cbfbcb4d 100644--- a/skyvern/cli/mcp_tools/workflow.py+++ b/skyvern/cli/mcp_tools/workflow.py@@ -686,6 +686,74 @@ def _inject_code_v2_defaults(definition: str, fmt: str) -> str:return json.dumps(raw) if changed else definition+def _collect_code_block_labels(blocks: Any) -> frozenset[str]:+ labels: set[str] = set()+ if not isinstance(blocks, list):+ return frozenset()+ for block in blocks:+ if not isinstance(block, dict):+ continue+ if block.get("block_type") == "code" and isinstance(block.get("label"), str):+ labels.add(block["label"])+ labels |= _collect_code_block_labels(block.get("loop_blocks"))+ return frozenset(labels)+++def _inject_code_block_prompt_defaults(definition: str, fmt: str, existing_code_labels: frozenset[str]) -> str:+ """Default `prompt` to "" on new code blocks, matching the editor's new-block default.++ A non-null prompt is what makes the frontend render the code-first (new) code block+ experience; the empty string is runtime-neutral (all backend prompt checks are truthiness+ based). Blocks whose label is in `existing_code_labels`, or that carry an explicit prompt+ value (including null), are left untouched so existing legacy blocks are never migrated.+ """+ raw, parsed_format = _load_definition_dict(definition, fmt)+ if raw is None or parsed_format is None:+ return definition+ workflow_definition = raw.get("workflow_definition")+ blocks = workflow_definition.get("blocks") if isinstance(workflow_definition, dict) else None+ if not isinstance(blocks, list):+ return definition++ changed = False++ def _walk(items: list[Any]) -> None:+ nonlocal changed+ for block in items:+ if not isinstance(block, dict):+ continue+ if (+ block.get("block_type") == "code"+ and "prompt" not in block+ and block.get("label") not in existing_code_labels+ ):+ block["prompt"] = ""+ changed = True+ loop_blocks = block.get("loop_blocks")+ if isinstance(loop_blocks, list):+ _walk(loop_blocks)++ _walk(blocks)+ return _dump_definition_dict(raw, parsed_format) if changed else definition+++async def _inject_workflow_update_code_block_prompt_defaults(+ definition: str,+ fmt: str,+ fetch_existing: Callable[[], Awaitable[dict[str, Any]]],+) -> str:+ """Apply the new-code-block prompt default on update, only for labels new to the workflow."""++ raw, parsed_format = _load_definition_dict(definition, fmt)+ if raw is None or parsed_format is None:+ return definition++ existing = await fetch_existing()+ existing_definition = existing.get("workflow_definition")+ existing_blocks = existing_definition.get("blocks") if isinstance(existing_definition, dict) else None+ return _inject_code_block_prompt_defaults(definition, fmt, _collect_code_block_labels(existing_blocks))++async def _inject_workflow_update_proxy_default(definition: str,fmt: str,@@ -1637,6 +1705,8 @@ async def skyvern_workflow_create(Defaults to AI agent execution (run_with="agent"). For JSON definitions, code_version=2 is alsoinjected (YAML definitions go through the backend schema, which currently leaves code_version unset).Pass run_with="code" to opt into cached script execution. Blocks share a browser session automatically.+ Code blocks that omit `prompt` are defaulted to prompt="" so they render the current code block+ editor experience.Leave optional toggles and overrides unset unless the user explicitly asks for them. Thisapplies to workflow-level fields (persist_browser_session, pin_saved_session_ip, extra_http_headers,@@ -1662,6 +1732,7 @@ async def skyvern_workflow_create(# Default MCP-created workflows to the same editor defaults while preserving# any explicit user-supplied values.definition = _inject_code_v2_defaults(definition, format)+ definition = _inject_code_block_prompt_defaults(definition, format, existing_code_labels=frozenset())definition = _inject_missing_top_level_defaults(definition,format,@@ -1771,6 +1842,7 @@ async def skyvern_workflow_update(try:definition = await _inject_workflow_update_proxy_default(definition, format, fetch_existing)definition = await _inject_workflow_update_top_level_settings(definition, format, fetch_existing)+ definition = await _inject_workflow_update_code_block_prompt_defaults(definition, format, fetch_existing)if code_only:existing = await fetch_existing()existing_wf_def = existing.get("workflow_definition")diff --git a/tests/unit/test_mcp_workflow_create_defaults.py b/tests/unit/test_mcp_workflow_create_defaults.pyindex 5ad502c5d..b572d2e0f 100644--- a/tests/unit/test_mcp_workflow_create_defaults.py+++ b/tests/unit/test_mcp_workflow_create_defaults.py@@ -2,11 +2,14 @@import json+import pytestimport yamlfrom skyvern.cli.mcp_tools.workflow import (+ _inject_code_block_prompt_defaults,_inject_code_v2_defaults,_inject_missing_top_level_defaults,+ _inject_workflow_update_code_block_prompt_defaults,_parse_definition,)from skyvern.schemas.runs import ProxyLocation@@ -124,6 +127,128 @@ def test_invalid_json_passthrough() -> None:assert result == bad_json+def _code_workflow_json(blocks: list[dict[str, object]]) -> str:+ return json.dumps(+ {+ "title": "Test Workflow",+ "workflow_definition": {"parameters": [], "blocks": blocks},+ }+ )+++def test_code_block_prompt_defaulted_on_create() -> None:+ """A code block without a prompt key gets prompt "" (the editor's new-block default)."""+ definition = _code_workflow_json([{"block_type": "code", "label": "step1", "code": "x = 1"}])+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset())+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert blocks[0]["prompt"] == ""+++def test_code_block_explicit_prompt_preserved() -> None:+ definition = _code_workflow_json([{"block_type": "code", "label": "step1", "code": "x = 1", "prompt": "Do X"}])+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset())+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert blocks[0]["prompt"] == "Do X"+++def test_code_block_explicit_null_prompt_preserved() -> None:+ """An explicit null prompt (e.g. a legacy block round-tripped through workflow get) stays null."""+ definition = _code_workflow_json([{"block_type": "code", "label": "step1", "code": "x = 1", "prompt": None}])+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset())+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert blocks[0]["prompt"] is None+++def test_code_block_prompt_not_defaulted_for_existing_label() -> None:+ """On update, an existing code block resubmitted without a prompt key is not migrated."""+ definition = _code_workflow_json(+ [+ {"block_type": "code", "label": "old_block", "code": "x = 1"},+ {"block_type": "code", "label": "new_block", "code": "y = 2"},+ ]+ )+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset({"old_block"}))+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert "prompt" not in blocks[0]+ assert blocks[1]["prompt"] == ""+++def test_code_block_prompt_defaulted_inside_for_loop() -> None:+ definition = _code_workflow_json(+ [+ {+ "block_type": "for_loop",+ "label": "loop",+ "loop_over_parameter_key": "items",+ "loop_blocks": [{"block_type": "code", "label": "inner", "code": "x = 1"}],+ }+ ]+ )+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset())+ loop = json.loads(result)["workflow_definition"]["blocks"][0]+ assert loop["loop_blocks"][0]["prompt"] == ""+++def test_non_code_blocks_untouched_by_prompt_default() -> None:+ definition = _minimal_workflow_json()+ result = _inject_code_block_prompt_defaults(definition, "json", existing_code_labels=frozenset())+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert "prompt" not in blocks[0]+++def test_code_block_prompt_defaulted_for_yaml() -> None:+ yaml_str = """+title: Test+workflow_definition:+ parameters: []+ blocks:+ - block_type: code+ label: step1+ code: x = 1+"""+ result = _inject_code_block_prompt_defaults(yaml_str, "yaml", existing_code_labels=frozenset())+ parsed = yaml.safe_load(result)+ assert parsed["workflow_definition"]["blocks"][0]["prompt"] == ""+++def test_code_block_prompt_invalid_json_passthrough() -> None:+ bad_json = "not valid json {"+ result = _inject_code_block_prompt_defaults(bad_json, "json", existing_code_labels=frozenset())+ assert result == bad_json+++async def test_update_wrapper_excludes_existing_code_labels_including_nested() -> None:+ existing = {+ "workflow_definition": {+ "blocks": [+ {"block_type": "code", "label": "old_top", "code": "x = 1"},+ {+ "block_type": "for_loop",+ "label": "loop",+ "loop_blocks": [{"block_type": "code", "label": "old_nested", "code": "y = 2"}],+ },+ ]+ }+ }++ async def fetch_existing() -> dict[str, object]:+ return existing++ definition = _code_workflow_json(+ [+ {"block_type": "code", "label": "old_top", "code": "x = 1"},+ {"block_type": "code", "label": "old_nested", "code": "y = 2"},+ {"block_type": "code", "label": "brand_new", "code": "z = 3"},+ ]+ )+ result = await _inject_workflow_update_code_block_prompt_defaults(definition, "json", fetch_existing)+ blocks = json.loads(result)["workflow_definition"]["blocks"]+ assert "prompt" not in blocks[0]+ assert "prompt" not in blocks[1]+ assert blocks[2]["prompt"] == ""++def test_parse_definition_unaffected() -> None:"""_parse_definition itself does NOT inject defaults (used by both create and update)."""definition = _minimal_workflow_json()diff --git a/tests/unit/test_workflow_persist_code_only.py b/tests/unit/test_workflow_persist_code_only.pyindex 95ee127b8..855effad0 100644--- a/tests/unit/test_workflow_persist_code_only.py+++ b/tests/unit/test_workflow_persist_code_only.py@@ -402,6 +402,27 @@ async def test_workflow_create_auto_wire_excludes_unsafe_and_malformed_parameterassert block["parameter_keys"] == ["eligible"][email protected]("serialized_as", ["json", "yaml"])+async def test_workflow_create_defaults_code_block_prompt(+ monkeypatch: pytest.MonkeyPatch,+ serialized_as: str,+) -> None:+ """An MCP-created code block without a prompt persists with prompt "" (new code block experience)."""+ request_mock = _patch_skyvern_http(monkeypatch)+ definition = _workflow_definition([_code_block()])++ result = await workflow_tools.skyvern_workflow_create(+ definition=_serialized_definition(definition, serialized_as),+ format=serialized_as,+ )++ assert result["ok"] is True, result+ sent = _sent_definition(request_mock)+ blocks = sent["workflow_definition"]["blocks"]+ assert blocks[0]["prompt"] == ""++@pytest.mark.parametrize("format_name", ["yaml", "auto"])@pytest.mark.asyncioasync def test_workflow_create_code_only_false_preserves_yaml_bytes(@@ -409,8 +430,10 @@ async def test_workflow_create_code_only_false_preserves_yaml_bytes(format_name: str,) -> None:request_mock = _patch_skyvern_http(monkeypatch)+ # prompt supplied explicitly: an omitted prompt is now defaulted (new code block+ # experience), which intentionally rewrites the definition.definition = _workflow_definition(- [_code_block()],+ [_code_block(prompt="")],proxy_location="RESIDENTIAL",code_version=2,run_with="agent",