Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: default MCP-created workflows to Code 2.0 (#5050)
pedrohsdb155e017f3c73
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsxindex 6ff9702b3..def78ad8b 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx@@ -88,13 +88,19 @@ function getLoopIterationGroups(items: Array<WorkflowRunTimelineItem>,): Array<LoopIterationGroup> {const groupsByKey = new Map<string, LoopIterationGroup>();+ const unknownItems: Array<WorkflowRunTimelineItem> = [];+ // First pass: group items with known indexes, collect unknown items separatelyitems.forEach((item) => {const currentIndex = isBlockItem(item) ? item.block.current_index : null;const currentValue = isBlockItem(item) ? item.block.current_value : null;- const groupKey =- currentIndex === null ? "unknown" : `index-${currentIndex}`;+ if (currentIndex === null) {+ unknownItems.push(item);+ return;+ }++ const groupKey = `index-${currentIndex}`;if (!groupsByKey.has(groupKey)) {groupsByKey.set(groupKey, {index: currentIndex,@@ -110,6 +116,33 @@ function getLoopIterationGroups(group.items.push(item);});+ // Second pass: merge unknown items into the highest-index group.+ // During streaming, these are blocks whose current_index hasn't been+ // populated yet — they belong to the currently-executing iteration.+ if (unknownItems.length > 0) {+ if (groupsByKey.size > 0) {+ let maxIndex = -1;+ let maxGroup: LoopIterationGroup | null = null;+ for (const group of groupsByKey.values()) {+ if (group.index !== null && group.index > maxIndex) {+ maxIndex = group.index;+ maxGroup = group;+ }+ }+ if (maxGroup) {+ unknownItems.forEach((item) => maxGroup!.items.push(item));+ }+ } else {+ // No known groups exist yet — all items are unknown.+ // The first iteration must be running.+ groupsByKey.set("index-0", {+ index: 0,+ currentValue: null,+ items: unknownItems,+ });+ }+ }+return Array.from(groupsByKey.values()).sort((left, right) => {if (left.index === null && right.index === null) {return 0;@@ -592,9 +625,7 @@ function WorkflowRunTimelineBlockItem({const loopValueFromIterable =group.index !== null ? loopValues[group.index] ?? null : null;const iterationNumber =- group.index !== null- ? group.index + 1- : loopIterationGroups.length - groupIndex;+ group.index !== null ? group.index + 1 : groupIndex + 1;const currentValuePreview = truncateValue(stringifyTimelineValue(loopValueFromIterable ?? group.currentValue,diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.pyindex 72f036ceb..81d89ca87 100644--- a/skyvern/cli/mcp_tools/workflow.py+++ b/skyvern/cli/mcp_tools/workflow.py@@ -200,6 +200,34 @@ def _validate_definition_structure(json_def: WorkflowCreateYamlRequest | None, areturn None+_CODE_V2_DEFAULTS: dict[str, Any] = {+ "adaptive_caching": True,+ "run_with": "code",+}+++def _inject_code_v2_defaults(definition: str, fmt: str) -> str:+ """Inject Code 2.0 defaults into a JSON definition string when not explicitly set.++ Only modifies JSON definitions (or auto-detected JSON). YAML is returned unchanged.+ """+ if fmt == "yaml":+ return definition++ try:+ raw = json.loads(definition)+ except (json.JSONDecodeError, TypeError):+ return definition # let _parse_definition handle the error++ changed = False+ for key, value in _CODE_V2_DEFAULTS.items():+ if key not in raw:+ raw[key] = value+ changed = True++ return json.dumps(raw) if changed else definition++def _parse_definition(definition: str, fmt: str) -> tuple[WorkflowCreateYamlRequest | None, str | None, dict[str, Any] | None]:@@ -346,6 +374,9 @@ async def skyvern_workflow_create("""Create a new Skyvern workflow from a YAML or JSON definition. Use when you need to savea new automation workflow that can be run repeatedly with different parameters.+ By default, workflows created via MCP use Code 2.0 (adaptive caching with run_with="code").+ To disable this, explicitly set "adaptive_caching": false and/or "run_with": null in your definition.+Best practice: use one block per logical step with a short focused prompt (2-3 sentences).Use "navigation" blocks for actions (filling forms, clicking) and "extraction" blocks for pulling data.Do NOT use the deprecated "task" block type.@@ -397,6 +428,10 @@ async def skyvern_workflow_create(),)+ # Default to Code 2.0 for MCP-created workflows (create only, not update).+ # Inject defaults into the raw JSON before parsing so explicit user values are preserved.+ definition = _inject_code_v2_defaults(definition, format)+json_def, yaml_def, parse_err = _parse_definition(definition, format)if parse_err is not None:return make_result("skyvern_workflow_create", ok=False, error=parse_err)diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex 1d118c921..06ed979e0 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -4654,6 +4654,8 @@ class AgentDB(BaseAlchemyDB):output: dict | list | str | None = None,continue_on_failure: bool = False,engine: RunEngine | None = None,+ current_value: str | None = None,+ current_index: int | None = None,) -> WorkflowRunBlock:async with self.Session() as session:new_workflow_run_block = WorkflowRunBlockModel(@@ -4667,6 +4669,8 @@ class AgentDB(BaseAlchemyDB):output=output,continue_on_failure=continue_on_failure,engine=engine,+ current_value=current_value,+ current_index=current_index,)session.add(new_workflow_run_block)await session.commit()diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 342edb024..9e538e733 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -505,6 +505,8 @@ class Block(BaseModel, abc.ABC):parent_workflow_run_block_id: str | None = None,organization_id: str | None = None,browser_session_id: str | None = None,+ current_value: str | None = None,+ current_index: int | None = None,**kwargs: dict,) -> BlockResult:workflow_run_block_id = None@@ -521,6 +523,8 @@ class Block(BaseModel, abc.ABC):block_type=self.block_type,continue_on_failure=self.continue_on_failure,engine=engine,+ current_value=current_value,+ current_index=current_index,)workflow_run_block_id = workflow_run_block.workflow_run_block_id@@ -1856,6 +1860,8 @@ class ForLoopBlock(Block):parent_workflow_run_block_id=parent_wrb_id,organization_id=organization_id,browser_session_id=browser_session_id,+ current_value=str(loop_over_value),+ current_index=loop_idx,)# Track conditional workflow_run_block_ids so branch targetsdiff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.pyindex 22ea8c044..0f9ebc62b 100644--- a/skyvern/services/script_service.py+++ b/skyvern/services/script_service.py@@ -429,12 +429,21 @@ async def _create_workflow_block_run_and_task(workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(workflow_run_id)workflow_run_context.update_block_metadata(label, context.loop_metadata)+ current_value_str = None+ current_index_val = None+ if context.loop_metadata:+ cv = context.loop_metadata.get("current_value")+ current_value_str = str(cv) if cv is not None else None+ current_index_val = context.loop_metadata.get("current_index")+workflow_run_block = await app.DATABASE.create_workflow_run_block(workflow_run_id=workflow_run_id,parent_workflow_run_block_id=context.parent_workflow_run_block_id,organization_id=organization_id,block_type=block_type,label=label,+ current_value=current_value_str,+ current_index=current_index_val,)workflow_run_block_id = workflow_run_block.workflow_run_block_iddiff --git a/tests/unit/test_mcp_workflow_create_defaults.py b/tests/unit/test_mcp_workflow_create_defaults.pynew file mode 100644index 000000000..980871f1d--- /dev/null+++ b/tests/unit/test_mcp_workflow_create_defaults.py@@ -0,0 +1,87 @@+"""Tests for MCP workflow create code v2 defaults."""++import json++from skyvern.cli.mcp_tools.workflow import _inject_code_v2_defaults, _parse_definition+++def _minimal_workflow_json(**overrides: object) -> str:+ """Return a minimal valid workflow JSON string with optional field overrides."""+ base: dict[str, object] = {+ "title": "Test Workflow",+ "workflow_definition": {+ "parameters": [],+ "blocks": [+ {+ "block_type": "navigation",+ "label": "step1",+ "url": "https://example.com",+ "title": "Step 1",+ "navigation_goal": "Click the button",+ }+ ],+ },+ }+ base.update(overrides)+ return json.dumps(base)+++def test_defaults_injected_when_not_specified() -> None:+ """When adaptive_caching and run_with are omitted, _inject_code_v2_defaults adds them."""+ definition = _minimal_workflow_json()+ result = _inject_code_v2_defaults(definition, "json")+ parsed = json.loads(result)+ assert parsed["adaptive_caching"] is True+ assert parsed["run_with"] == "code"+++def test_defaults_injected_in_auto_mode() -> None:+ """Auto format also injects defaults for JSON input."""+ definition = _minimal_workflow_json()+ result = _inject_code_v2_defaults(definition, "auto")+ parsed = json.loads(result)+ assert parsed["adaptive_caching"] is True+ assert parsed["run_with"] == "code"+++def test_explicit_values_preserved() -> None:+ """When the user explicitly sets these fields, their values are preserved."""+ definition = _minimal_workflow_json(adaptive_caching=False, run_with="agent")+ result = _inject_code_v2_defaults(definition, "json")+ parsed = json.loads(result)+ assert parsed["adaptive_caching"] is False+ assert parsed["run_with"] == "agent"+++def test_explicit_null_run_with_preserved() -> None:+ """When the user explicitly sets run_with to null, it stays null."""+ definition = _minimal_workflow_json(run_with=None)+ result = _inject_code_v2_defaults(definition, "json")+ parsed = json.loads(result)+ assert parsed["run_with"] is None+ # adaptive_caching was not set, so it gets the default+ assert parsed["adaptive_caching"] is True+++def test_yaml_passthrough_unchanged() -> None:+ """YAML definitions are passed through without modification."""+ yaml_str = "title: Test\nworkflow_definition:\n blocks: []"+ result = _inject_code_v2_defaults(yaml_str, "yaml")+ assert result == yaml_str+++def test_invalid_json_passthrough() -> None:+ """Invalid JSON is passed through (let _parse_definition handle the error)."""+ bad_json = "not valid json {"+ result = _inject_code_v2_defaults(bad_json, "json")+ assert result == bad_json+++def test_parse_definition_unaffected() -> None:+ """_parse_definition itself does NOT inject defaults (used by both create and update)."""+ definition = _minimal_workflow_json()+ json_def, _, err = _parse_definition(definition, "json")+ assert err is None+ assert json_def is not None+ # run_with should be None (schema default), not "code"+ assert json_def.run_with is None