Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix: preserve credential block references during MCP workflow update (#SKY-8462) (#5344)
Marc Kelechava21bb4cdf0f37
diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.pyindex e8fb47217..f91b35b6f 100644--- a/skyvern/cli/mcp_tools/workflow.py+++ b/skyvern/cli/mcp_tools/workflow.py@@ -609,6 +609,19 @@ async def _inject_workflow_update_proxy_default(definition: str, fmt: str, workf_AUTO_MANAGED_PARAMETER_TYPES = frozenset({"credential"})+def _iter_blocks_flat(blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Return all block dicts from a block list, recursing into for_loop nested blocks."""+ result: list[dict[str, Any]] = []+ for block in blocks:+ if not isinstance(block, dict):+ continue+ result.append(block)+ loop_blocks = block.get("loop_blocks")+ if isinstance(loop_blocks, list):+ result.extend(_iter_blocks_flat(loop_blocks))+ return result++async def _inject_workflow_update_parameters(definition: str, fmt: str, workflow_id: str) -> str:"""Preserve auto-managed parameters (e.g. credential) when MCP update omits them.@@ -637,7 +650,9 @@ async def _inject_workflow_update_parameters(definition: str, fmt: str, workflowexisting_params: list[dict[str, Any]] = existing_wf_def.get("parameters", [])- injected = False+ modified = False++ # --- Step 1: Inject missing credential parameters into the parameters list ---for param in existing_params:if not isinstance(param, dict):continue@@ -654,9 +669,45 @@ async def _inject_workflow_update_parameters(definition: str, fmt: str, workflowif ptype == "credential" and param.get("credential_id"):injected_param["credential_id"] = param["credential_id"]update_params.append(injected_param)- injected = True-- if not injected:+ modified = True++ # --- Step 2: Inject missing credential parameter keys into blocks ---+ # Collect all auto-managed parameter keys from the existing workflow+ all_cred_keys: set[str] = set()+ for p in existing_params:+ if isinstance(p, dict) and p.get("parameter_type") in _AUTO_MANAGED_PARAMETER_TYPES and p.get("key"):+ all_cred_keys.add(p["key"])++ if all_cred_keys:+ existing_blocks: list[dict[str, Any]] = existing_wf_def.get("blocks", [])+ update_blocks: list[dict[str, Any]] = wf_def.get("blocks", [])++ # Map existing block labels to the credential parameter keys they reference+ existing_block_cred_keys: dict[str, list[str]] = {}+ for block in _iter_blocks_flat(existing_blocks):+ label = block.get("label")+ if not label:+ continue+ existing_pkeys = block.get("parameter_keys") or []+ cred_keys = [k for k in existing_pkeys if k in all_cred_keys]+ if cred_keys:+ existing_block_cred_keys[label] = cred_keys++ # Inject credential parameter keys into matching update blocks+ if existing_block_cred_keys:+ for block in _iter_blocks_flat(update_blocks):+ label = block.get("label")+ if not label or label not in existing_block_cred_keys:+ continue+ block_pkeys: list[str] = list(block.get("parameter_keys") or [])+ current_keys = set(block_pkeys)+ for cred_key in existing_block_cred_keys[label]:+ if cred_key not in current_keys:+ block_pkeys.append(cred_key)+ modified = True+ block["parameter_keys"] = block_pkeys++ if not modified:return definitionwf_def["parameters"] = update_paramsdiff --git a/tests/unit/test_mcp_workflow_tools.py b/tests/unit/test_mcp_workflow_tools.pyindex b9f88b754..776b2df1b 100644--- a/tests/unit/test_mcp_workflow_tools.py+++ b/tests/unit/test_mcp_workflow_tools.py@@ -720,6 +720,238 @@ async def test_workflow_update_preserves_credential_parameters_when_omitted(assert cred_params[0].key == "credentials"+async def test_workflow_update_injects_credential_key_into_block_parameter_keys(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the update definition omits the credential parameter key from a login+ block's parameter_keys, the key should be injected from the existing workflow."""++ fake_client = SimpleNamespace(update_workflow=AsyncMock(return_value=_fake_workflow_response()))+ monkeypatch.setattr(workflow_tools, "get_skyvern", lambda: fake_client)++ async def fake_get_workflow_by_id(workflow_id: str, version: int | None = None) -> dict[str, object]:+ return {+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "credentials",+ "credential_id": "cred_abc123",+ },+ {+ "parameter_type": "workflow",+ "key": "url_input",+ "workflow_parameter_type": "string",+ "default_value": "https://example.com",+ },+ ],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "parameter_keys": ["credentials"],+ "navigation_goal": "Login",+ }+ ],+ },+ }++ monkeypatch.setattr(workflow_tools, "_get_workflow_by_id", fake_get_workflow_by_id)++ # Claude regenerated the login block WITHOUT the credential key in parameter_keys+ definition = {+ "title": "Updated workflow",+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "workflow",+ "key": "url_input",+ "workflow_parameter_type": "string",+ "default_value": "https://new-url.com",+ },+ ],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "parameter_keys": [],+ "navigation_goal": "Login to the site",+ }+ ],+ },+ }++ result = await workflow_tools.skyvern_workflow_update(+ workflow_id="wpid_test",+ definition=json.dumps(definition),+ format="json",+ )++ assert result["ok"] is True++ sent_def = fake_client.update_workflow.await_args.kwargs["json_definition"]+ # Verify credential parameter was injected+ params = sent_def.workflow_definition.parameters+ cred_params = [p for p in params if getattr(p, "parameter_type", None) == "credential"]+ assert len(cred_params) == 1+ assert cred_params[0].credential_id == "cred_abc123"++ # Verify the login block now references the credential parameter key+ blocks = sent_def.workflow_definition.blocks+ login_block = next(b for b in blocks if getattr(b, "label", None) == "login_block")+ pkeys = getattr(login_block, "parameter_keys", [])+ assert "credentials" in pkeys+++async def test_workflow_update_injects_credential_key_when_parameter_keys_omitted(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the update definition omits parameter_keys entirely from the block,+ credential keys should still be injected."""++ fake_client = SimpleNamespace(update_workflow=AsyncMock(return_value=_fake_workflow_response()))+ monkeypatch.setattr(workflow_tools, "get_skyvern", lambda: fake_client)++ async def fake_get_workflow_by_id(workflow_id: str, version: int | None = None) -> dict[str, object]:+ return {+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "credentials",+ "credential_id": "cred_abc123",+ },+ ],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "parameter_keys": ["credentials"],+ }+ ],+ },+ }++ monkeypatch.setattr(workflow_tools, "_get_workflow_by_id", fake_get_workflow_by_id)++ # Claude regenerated the login block WITHOUT parameter_keys at all+ definition = {+ "title": "Updated workflow",+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "navigation_goal": "Login to the site",+ }+ ],+ },+ }++ result = await workflow_tools.skyvern_workflow_update(+ workflow_id="wpid_test",+ definition=json.dumps(definition),+ format="json",+ )++ assert result["ok"] is True++ sent_def = fake_client.update_workflow.await_args.kwargs["json_definition"]+ # Verify credential parameter was injected+ params = sent_def.workflow_definition.parameters+ cred_params = [p for p in params if getattr(p, "parameter_type", None) == "credential"]+ assert len(cred_params) == 1++ # Verify the login block now has the credential key+ blocks = sent_def.workflow_definition.blocks+ login_block = next(b for b in blocks if getattr(b, "label", None) == "login_block")+ pkeys = getattr(login_block, "parameter_keys", [])+ assert "credentials" in pkeys+++async def test_workflow_update_preserves_block_credential_when_param_already_included(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the update already includes the credential parameter but the block omits+ the key from parameter_keys, the key should still be injected into the block."""++ fake_client = SimpleNamespace(update_workflow=AsyncMock(return_value=_fake_workflow_response()))+ monkeypatch.setattr(workflow_tools, "get_skyvern", lambda: fake_client)++ async def fake_get_workflow_by_id(workflow_id: str, version: int | None = None) -> dict[str, object]:+ return {+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "credentials",+ "credential_id": "cred_abc123",+ },+ ],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "parameter_keys": ["credentials"],+ }+ ],+ },+ }++ monkeypatch.setattr(workflow_tools, "_get_workflow_by_id", fake_get_workflow_by_id)++ # Claude included the credential param but omitted it from the block's parameter_keys+ definition = {+ "title": "Updated workflow",+ "proxy_location": "RESIDENTIAL",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "credentials",+ "credential_id": "cred_abc123",+ },+ ],+ "blocks": [+ {+ "block_type": "login",+ "label": "login_block",+ "parameter_keys": [],+ "navigation_goal": "Login to the site",+ }+ ],+ },+ }++ result = await workflow_tools.skyvern_workflow_update(+ workflow_id="wpid_test",+ definition=json.dumps(definition),+ format="json",+ )++ assert result["ok"] is True++ sent_def = fake_client.update_workflow.await_args.kwargs["json_definition"]+ blocks = sent_def.workflow_definition.blocks+ login_block = next(b for b in blocks if getattr(b, "label", None) == "login_block")+ pkeys = getattr(login_block, "parameter_keys", [])+ assert "credentials" in pkeys++ # Should not duplicate the credential parameter+ params = sent_def.workflow_definition.parameters+ cred_params = [p for p in params if getattr(p, "parameter_type", None) == "credential"]+ assert len(cred_params) == 1++@pytest.mark.asyncioasync def test_workflow_update_does_not_duplicate_existing_credential_parameter(monkeypatch: pytest.MonkeyPatch,