Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(cli): add OpenCode MCP setup with API key auth (#6100)
Shiven Gariabc6c681d5a3b
diff --git a/docs/integrations/cli.mdx b/docs/integrations/cli.mdxindex ed0fdd0b5..f663c2b26 100644--- a/docs/integrations/cli.mdx+++ b/docs/integrations/cli.mdx@@ -162,6 +162,7 @@ skyvern setup claude # Register with Claude Desktopskyvern setup cursor # Register with Cursorskyvern setup windsurf # Register with Windsurfskyvern setup openclaw # Register with OpenClaw+skyvern setup opencode # Register with OpenCode (API key auth; avoids OAuth timeouts)skyvern mcp switch # Interactively switch existing Skyvern MCP configsskyvern mcp switch --dry-run # Preview changes without writing filesskyvern mcp profile list # List saved switch sourcesdiff --git a/integrations/mcp/README.md b/integrations/mcp/README.mdindex 9a45e9cb5..2d3ac8aed 100644--- a/integrations/mcp/README.md+++ b/integrations/mcp/README.md@@ -54,8 +54,24 @@ https://github.com/user-attachments/assets/70cfe310-24dc-431a-adde-e72691f198a7- Cursor- Windsurf- Claude Desktop+- OpenCode (`skyvern setup opencode` — uses API key auth; avoids OAuth callback timeouts)- Your custom MCP App?+### OpenCode (remote MCP)++If `opencode mcp auth Skyvern` fails with **OAuth callback timeout**, use API key auth instead:++```bash+skyvern login+skyvern setup opencode+```++This writes `~/.config/opencode/opencode.json` with `"oauth": false` and your `x-api-key` header. Do not run `opencode mcp auth` afterward.++> **Note:** The remote `/mcp` endpoint is stateless. Call `skyvern_browser_session_create` first+> and pass `browser_session_id` on every browser tool call, or browser tools will return+> `BrowserNotAvailable`.+Use the following config if you want to set up Skyvern for any other MCP-enabled application```json{diff --git a/skyvern/cli/masked_prompt.py b/skyvern/cli/masked_prompt.pyindex a6fdcc0ea..82580ca95 100644--- a/skyvern/cli/masked_prompt.py+++ b/skyvern/cli/masked_prompt.py@@ -111,7 +111,7 @@ def _read_masked_tty_unix(output: TextIO, *, mask: str) -> str:input_file = sys.stdinfd = input_file.fileno()- old_settings = termios.tcgetattr(fd)+ old_settings = termios.tcgetattr(fd) # type: ignore[attr-defined]wrote_newline = Falsedef write(text: str) -> None:@@ -122,7 +122,7 @@ def _read_masked_tty_unix(output: TextIO, *, mask: str) -> str:output.flush()try:- tty.setcbreak(fd)+ tty.setcbreak(fd) # type: ignore[attr-defined]try:return _read_masked_line(lambda: input_file.read(1), write, mask=mask)except (EOFError, KeyboardInterrupt):@@ -130,7 +130,7 @@ def _read_masked_tty_unix(output: TextIO, *, mask: str) -> str:write("\n")raisefinally:- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # type: ignore[attr-defined]def _read_masked_tty_windows(output: TextIO, *, mask: str) -> str:diff --git a/skyvern/cli/mcp_commands.py b/skyvern/cli/mcp_commands.pyindex 452c6b073..d44721111 100644--- a/skyvern/cli/mcp_commands.py+++ b/skyvern/cli/mcp_commands.py@@ -33,11 +33,13 @@ from .setup_commands import (_get_env_credentials,_load_mcp_config,_load_openclaw_config,+ _load_opencode_config,_load_yaml_config,_mask_key,_mask_secrets,_normalize_openclaw_remote_entry,_openclaw_config_path,+ _opencode_config_path,_save_yaml_config,_walk_nested_path,_warn_openclaw_json_normalization,@@ -58,6 +60,7 @@ _CONFIG_FORMAT_JSON = "json"_CONFIG_FORMAT_JSON5 = "json5"_CONFIG_FORMAT_CODEX = "codex_toml"_CONFIG_FORMAT_YAML = "yaml"+_CONFIG_FORMAT_OPENCODE = "opencode"@dataclass(frozen=True)@@ -298,6 +301,8 @@ def _load_switch_config(config_path: Path, config_format: str) -> tuple[dict | Nreturn _load_codex_config(config_path)if config_format == _CONFIG_FORMAT_JSON5:return _load_openclaw_config(config_path)+ if config_format == _CONFIG_FORMAT_OPENCODE:+ return _load_opencode_config(config_path)if config_format == _CONFIG_FORMAT_YAML:data = _load_yaml_config(config_path)if data is None:@@ -356,6 +361,12 @@ def _switch_target_specs() -> list[SwitchTargetSpec]:config_format=_CONFIG_FORMAT_JSON5,entry_path=["mcp", "servers"],),+ SwitchTargetSpec(+ "OpenCode",+ _opencode_config_path,+ config_format=_CONFIG_FORMAT_OPENCODE,+ entry_path=["mcp"],+ ),SwitchTargetSpec("Hermes", _hermes_config_path, config_format=_CONFIG_FORMAT_YAML),]# Discover per-profile Hermes configs alongside the global one@@ -380,18 +391,33 @@ def _switch_target_specs() -> list[SwitchTargetSpec]:def _entry_kind(entry: dict | None) -> str:- if not entry:- return "missing"+ if entry is None:+ return "unsupported"++ entry_type = entry.get("type")- command_name = Path(str(entry.get("command", ""))).name.lower()+ if entry_type == "local":+ return "local stdio"++ if entry_type in {"http", "remote"}:+ return "remote http"++ command = entry.get("command", "")+ if isinstance(command, list):+ command_name = Path(str(command[0])).name if command else ""+ else:+ command_name = Path(command).name if command else ""args = entry.get("args", [])if command_name == "npx" and isinstance(args, list) and args and args[0] == "mcp-remote":return "mcp-remote bridge"- if isinstance(entry.get("env"), dict):+ if entry.get("type") == "http" or "url" in entry or isinstance(entry.get("http_headers"), dict):+ return "remote http"++ if isinstance(entry.get("env"), dict) or isinstance(entry.get("environment"), dict):return "local stdio"- if entry.get("type") == "http" or "url" in entry or isinstance(entry.get("http_headers"), dict):+ if "url" in entry or isinstance(entry.get("http_headers"), dict):return "remote http"return "unsupported"@@ -410,7 +436,11 @@ def _extract_entry_api_key(entry: dict) -> str:if isinstance(api_key, str):return api_key- env = entry.get("env", {})+ if entry.get("type") == "local":+ env = entry.get("environment") or entry.get("env", {})+ else:+ env = entry.get("env", {})+if isinstance(env, dict):api_key = env.get("SKYVERN_API_KEY")if isinstance(api_key, str):@@ -549,9 +579,12 @@ def _select_profile(profile_name: str | None, discovered: list[SwitchTarget]) ->def _entry_location(entry: dict) -> str:kind = _entry_kind(entry)if kind == "local stdio":- env = entry.get("env", {})+ env = entry.get("environment")+ if env is None:+ env = entry.get("env", {})if isinstance(env, dict):return str(env.get("SKYVERN_BASE_URL", ""))+if kind == "remote http":return str(entry.get("url", ""))if kind == "mcp-remote bridge":@@ -729,14 +762,28 @@ def _patch_entry_with_profile(kind = _entry_kind(entry)if kind == "local stdio":- env = dict(patched.get("env") or {})+ env = dict(patched.get("environment") or patched.get("env") or {})env["SKYVERN_API_KEY"] = profile.api_keyenv["SKYVERN_BASE_URL"] = profile.base_url- patched["env"] = env+ if "environment" in patched or config_format == _CONFIG_FORMAT_OPENCODE:+ patched["environment"] = env+ patched.pop("env", None)+ if config_format == _CONFIG_FORMAT_OPENCODE:+ patched["type"] = "local"+ else:+ patched["env"] = envreturn patchedif kind == "remote http":target_url = _profile_to_mcp_url(profile.base_url)+ if config_format == _CONFIG_FORMAT_OPENCODE:+ headers = dict(patched.get("headers") or {})+ headers["x-api-key"] = profile.api_key+ patched["headers"] = headers+ patched["url"] = target_url+ patched["type"] = "remote"+ patched["oauth"] = False+ return patchedif config_format == _CONFIG_FORMAT_JSON5:return _normalize_openclaw_remote_entry(patched, api_key=profile.api_key, url=target_url)if config_format == _CONFIG_FORMAT_CODEX or "http_headers" in patched:diff --git a/skyvern/cli/setup_commands.py b/skyvern/cli/setup_commands.pyindex 37f302758..702109fb2 100644--- a/skyvern/cli/setup_commands.py+++ b/skyvern/cli/setup_commands.py@@ -181,6 +181,56 @@ def _build_openclaw_mcp_entry(api_key: str, url: str = _DEFAULT_REMOTE_URL) -> dreturn entry+def _build_opencode_remote_mcp_entry(api_key: str, url: str = _DEFAULT_REMOTE_URL) -> dict:+ """Build an OpenCode remote MCP entry using API key auth instead of OAuth.++ OpenCode auto-discovers OAuth when the field is omitted, which can fail with+ callback timeouts (see https://github.com/Skyvern-AI/skyvern/issues/6044).+ OpenCode documents MCP server config, including `oauth: false`, at:+ https://opencode.ai/docs/mcp-servers/++ """+ entry: dict = {+ "type": "remote",+ "url": url,+ "oauth": False,+ }+ if api_key:+ entry["headers"] = {"x-api-key": api_key}+ return entry+++def _build_opencode_local_mcp_entry(+ api_key: str,+ base_url: str,+ use_python_path: bool = False,+ command: str | None = None,+ browser_type: str | None = None,+ browser_remote_debugging_url: str | None = None,+) -> dict:+ """Build an OpenCode local stdio MCP entry."""+ local_entry = _build_local_mcp_entry(+ api_key,+ base_url,+ use_python_path=use_python_path,+ command=command,+ browser_type=browser_type,+ browser_remote_debugging_url=browser_remote_debugging_url,+ )+ command_name = str(local_entry.get("command") or sys.executable)+ args = local_entry.get("args", [])+ if not isinstance(args, list):+ args = []+ entry: dict = {+ "type": "local",+ "command": [command_name, *[str(arg) for arg in args]],+ }+ env_block = local_entry.get("env")+ if isinstance(env_block, dict) and env_block:+ entry["environment"] = env_block+ return entry++def _normalize_openclaw_remote_entry(entry: dict, *, api_key: str, url: str) -> dict:"""Normalize an OpenClaw remote entry to `{url, transport, headers}` shape.@@ -226,12 +276,21 @@ def _has_api_key(entry: dict | None) -> bool:"""Check whether an MCP config entry carries an API key (remote, local, or mcp-remote bridge format)."""if not entry:return False- if entry.get("headers", {}).get("x-api-key"):+ headers = entry.get("headers")+ if isinstance(headers, dict) and headers.get("x-api-key"):+ return True+ http_headers = entry.get("http_headers")+ if isinstance(http_headers, dict) and http_headers.get("x-api-key"):return True- if entry.get("http_headers", {}).get("x-api-key"):++ env = entry.get("env")+ if isinstance(env, dict) and env.get("SKYVERN_API_KEY"):return True- if entry.get("env", {}).get("SKYVERN_API_KEY"):++ environment = entry.get("environment")+ if isinstance(environment, dict) and environment.get("SKYVERN_API_KEY"):return True+# mcp-remote bridge: API key is in args as "--header", "x-api-key:..."args = entry.get("args", [])return any(isinstance(a, str) and a.startswith("x-api-key:") for a in args)@@ -289,6 +348,11 @@ def _mask_secrets(entry: dict) -> dict:key = masked["env"]["SKYVERN_API_KEY"]masked["env"]["SKYVERN_API_KEY"] = _mask_key(key)+ # OpenCode local stdio format: environment.SKYVERN_API_KEY+ if "environment" in masked and "SKYVERN_API_KEY" in masked["environment"]:+ key = masked["environment"]["SKYVERN_API_KEY"]+ masked["environment"]["SKYVERN_API_KEY"] = _mask_key(key)+# mcp-remote bridge format: args contain "x-api-key:..."if "args" in masked:masked["args"] = [@@ -323,6 +387,26 @@ def _load_mcp_config(config_path: Path) -> tuple[dict | None, str | None]:return existing, None+def _load_opencode_config(config_path: Path) -> tuple[dict | None, str | None]:+ """Load an OpenCode config file, accepting OpenCode's JSONC/JSON5 syntax."""+ if not config_path.exists():+ return {}, None++ try:+ existing = json5.loads(config_path.read_text(encoding="utf-8"))+ except ValueError:+ return None, f"Cannot parse {config_path}. Fix the JSONC/JSON and re-run."++ if not isinstance(existing, dict):+ return None, f"{config_path} must contain a top-level JSON object."++ servers = existing.get("mcp")+ if servers is not None and not isinstance(servers, dict):+ return None, f"{config_path} has invalid `mcp`; expected a JSON object."++ return existing, None++def _load_openclaw_config(config_path: Path) -> tuple[dict | None, str | None]:"""Load an OpenClaw config file, accepting OpenClaw's JSON5-on-read format.@@ -565,6 +649,15 @@ def _is_claude_desktop_installed() -> bool:return False+def _is_opencode_installed() -> bool:+ if shutil.which("opencode") is not None:+ return True+ try:+ return _opencode_config_path().parent.is_dir()+ except typer.Exit:+ return False++def _get_known_tools() -> list[DetectedTool]:"""Return all known AI coding tools in detection order.@@ -595,6 +688,11 @@ def _get_known_tools() -> list[DetectedTool]:is_installed_fn=_is_claude_desktop_installed,use_mcp_remote_bridge=True,),+ DetectedTool(+ name="OpenCode",+ config_path_fn=_opencode_config_path,+ is_installed_fn=_is_opencode_installed,+ ),]@@ -738,6 +836,13 @@ def _openclaw_config_path() -> Path:return Path.home() / ".openclaw" / "openclaw.json"+def _opencode_config_path() -> Path:+ config_override = os.environ.get("OPENCODE_CONFIG")+ if config_override:+ return Path(config_override).expanduser()+ return Path.home() / ".config" / "opencode" / "opencode.json"++_PROJECT_MARKERS = (".git",".mcp.json",@@ -955,7 +1060,8 @@ def setup_guided(" skyvern setup claude-code\n"" skyvern setup cursor\n"" skyvern setup windsurf\n"- " skyvern setup claude"+ " skyvern setup claude\n"+ " skyvern setup opencode")capture_setup_event("quickstart-no-tools", success=True)return@@ -986,17 +1092,40 @@ def setup_guided(# Pass browser config from env for local modeenv_browser_type = os.environ.get("BROWSER_TYPE") if local else Noneenv_browser_url = os.environ.get("BROWSER_REMOTE_DEBUGGING_URL") if local else None- entry = _build_entry(- resolved_key,- env_url,- local=local,- use_python_path=use_python_path,- url=url,- use_mcp_remote_bridge=use_bridge,- browser_type=env_browser_type,- browser_remote_debugging_url=env_browser_url,- )- _upsert_mcp_config(config_path, tool.name, entry, dry_run=dry_run, yes=True)+ if tool.name == "OpenCode":+ if local:+ entry = _build_opencode_local_mcp_entry(+ resolved_key,+ env_url,+ use_python_path=use_python_path,+ browser_type=env_browser_type,+ browser_remote_debugging_url=env_browser_url,+ )+ else:+ remote_url = url or _DEFAULT_REMOTE_URL+ parsed = urlparse(remote_url)+ if parsed.scheme not in ("http", "https") or not parsed.netloc:+ console.print(+ f"[red]Invalid URL: {remote_url} (must be a full URL like https://api.skyvern.com/mcp/)[/red]"+ )+ raise typer.Exit(code=1)+ entry = _build_opencode_remote_mcp_entry(resolved_key, url=remote_url)++ _upsert_opencode_config(config_path, entry, dry_run=dry_run, yes=True, tool_name=tool.name)+ console.print(f"[dim]{_opencode_setup_success_message(local=local)}[/dim]")++ else:+ entry = _build_entry(+ resolved_key,+ env_url,+ local=local,+ use_python_path=use_python_path,+ url=url,+ use_mcp_remote_bridge=use_bridge,+ browser_type=env_browser_type,+ browser_remote_debugging_url=env_browser_url,+ )+ _upsert_mcp_config(config_path, tool.name, entry, dry_run=dry_run, yes=True)if tool.name == "Claude Code":_, install_skills = _claude_code_config_target()if install_skills:@@ -1269,6 +1398,95 @@ def setup_openclaw(console.print(f"[dim]Backup saved to {backup_path}[/dim]")+def _upsert_opencode_config(+ config_path: Path,+ skyvern_entry: dict,+ *,+ dry_run: bool = False,+ yes: bool = False,+ tool_name: str = "OpenCode",+) -> None:+ """Read OpenCode config, diff, prompt, and write. Idempotent."""+ existing, error = _load_opencode_config(config_path)+ if error:+ console.print(f"[red]{error}[/red]")+ raise typer.Exit(code=1)++ config = existing or {}+ servers = config.setdefault("mcp", {})+ if not isinstance(servers, dict):+ console.print(f"[red]Invalid existing OpenCode `mcp` section in {config_path}; expected a JSON object.[/red]")+ raise typer.Exit(code=1)++ server_key = _find_server_key(servers, preferred="skyvern") or "skyvern"+ current = servers.get(server_key)+ if current is not None and not isinstance(current, dict):+ console.print(f"[red]Invalid existing OpenCode MCP entry for '{server_key}'; expected a JSON object.[/red]")+ raise typer.Exit(code=1)++ if not _preview_upsert_change(current, skyvern_entry, tool_name):+ return++ if dry_run:+ console.print(f"\n[yellow]Dry run -- no changes written to {config_path}[/yellow]")+ return++ if not yes and not typer.confirm("\nApply changes?"):+ raise typer.Abort()++ servers[server_key] = skyvern_entry+ backup_path = _write_mcp_config(config_path, config)+ console.print(f"[green]Configured {tool_name} at {config_path}[/green]")+ if backup_path is not None:+ console.print(f"[dim]Backup saved to {backup_path}[/dim]")+++def _opencode_setup_success_message(*, local: bool) -> str:+ if local:+ return "OpenCode is configured for local Skyvern MCP (stdio)."+ return (+ "OpenCode is configured with API key auth (`oauth: false`).\n"+ "Do not run `opencode mcp auth Skyvern` — that triggers OAuth and can time out.\n"+ "See https://github.com/Skyvern-AI/skyvern/issues/6044"+ )+++@setup_app.command("opencode")+def setup_opencode(+ api_key: str | None = _api_key_opt,+ dry_run: bool = _dry_run_opt,+ yes: bool = _yes_opt,+ local: bool = _local_opt,+ use_python_path: bool = _python_path_opt,+ url: str | None = _url_opt,+ browser_type: str | None = None,+ browser_remote_debugging_url: str | None = None,+) -> None:+ """Register Skyvern MCP with OpenCode using API key auth (avoids OAuth callback timeouts)."""+ resolved_key, env_url = _resolve_setup_credentials(api_key_flag=api_key, yes=yes, local=local)+ if local:+ entry = _build_opencode_local_mcp_entry(+ resolved_key,+ env_url,+ use_python_path=use_python_path,+ browser_type=browser_type,+ browser_remote_debugging_url=browser_remote_debugging_url,+ )+ else:+ remote_url = url or _DEFAULT_REMOTE_URL+ parsed = urlparse(remote_url)+ if parsed.scheme not in ("http", "https") or not parsed.netloc:+ console.print(+ f"[red]Invalid URL: {remote_url} (must be a full URL like https://api.skyvern.com/mcp/)[/red]"+ )+ raise typer.Exit(code=1)+ entry = _build_opencode_remote_mcp_entry(resolved_key, url=remote_url)++ config_path = _opencode_config_path()+ _upsert_opencode_config(config_path, entry, dry_run=dry_run, yes=yes)+ console.print(f"[dim]{_opencode_setup_success_message(local=local)}[/dim]")++@setup_app.command("hermes")def setup_hermes(api_key: str | None = _api_key_opt,@@ -1419,6 +1637,7 @@ def setup_mcporter() -> None:("Claude Code (project)", "skyvern setup claude-code --project", _claude_code_project_config_path()),("Cursor", "skyvern setup cursor", _cursor_config_path()),("Windsurf", "skyvern setup windsurf", _windsurf_config_path()),+ ("OpenCode", "skyvern setup opencode", _opencode_config_path()),]found: list[str] = []@@ -1426,13 +1645,21 @@ def setup_mcporter() -> None:try:if not path.exists():continue- cfg, err = _load_mcp_config(path)+ if name == "OpenCode":+ cfg, err = _load_opencode_config(path)+ servers_key = "mcp"+ else:+ cfg, err = _load_mcp_config(path)+ servers_key = "mcpServers"+if err or not cfg:continue- servers = cfg.get("mcpServers", {})++ servers = cfg.get(servers_key, {})if _find_server_key(servers, "skyvern"):- console.print(f" [green]\u2713[/green] {name} \u2014 {path}")+ console.print(f" [green]\u2713[/green] {name} — {path}")found.append(name)+except Exception:continue@@ -1444,5 +1671,6 @@ def setup_mcporter() -> None:"Set up at least one tool first:\n"" skyvern setup cursor\n"" skyvern setup claude-code\n"- " skyvern setup claude"+ " skyvern setup claude\n"+ " skyvern setup opencode")diff --git a/tests/unit/test_mcp_commands.py b/tests/unit/test_mcp_commands.pyindex 2b3f20f9a..6e679f49b 100644--- a/tests/unit/test_mcp_commands.py+++ b/tests/unit/test_mcp_commands.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport osimport stat+import sysfrom pathlib import Pathimport pytest@@ -183,6 +184,19 @@ def test_entry_kind_requires_exact_npx_for_mcp_remote_bridge() -> None:assert _entry_kind(entry) == "unsupported"+def test_entry_kind_accepts_opencode_local_command_array() -> None:+ entry = {+ "type": "local",+ "command": [sys.executable, "-m", "skyvern", "run", "mcp"],+ "environment": {+ "SKYVERN_BASE_URL": "http://localhost:8000",+ "SKYVERN_API_KEY": "old-key",+ },+ }++ assert _entry_kind(entry) == "local stdio"++def test_sanitize_prompt_response_strips_arrow_escape_noise() -> None:assert _sanitize_prompt_response("\x1b[C\x1b[C\x1b[Call") == "all"@@ -244,6 +258,60 @@ def test_apply_profile_to_target_updates_codex_entry_and_creates_backup(tmp_pathassert backup["mcp_servers"]["skyvern"]["http_headers"]["x-api-key"] == "old-key"+def test_apply_profile_to_target_updates_opencode_local_jsonc_entry(tmp_path: Path) -> None:+ config_path = tmp_path / "opencode.json"+ config_path.write_text(+ f"""+{{+ // OpenCode allows JSONC.+ "mcp": {{+ "skyvern": {{+ "type": "local",+ "command": {json.dumps([sys.executable, "-m", "skyvern", "run", "mcp"])},+ "environment": {{+ "SKYVERN_BASE_URL": "http://localhost:8000",+ "SKYVERN_API_KEY": "old-key",+ "OTHER": "keep-me",+ }},+ }},+ }},+}}+""",+ encoding="utf-8",+ )+ entry = {+ "type": "local",+ "command": [sys.executable, "-m", "skyvern", "run", "mcp"],+ "environment": {+ "SKYVERN_BASE_URL": "http://localhost:8000",+ "SKYVERN_API_KEY": "old-key",+ "OTHER": "keep-me",+ },+ }+ target = SwitchTarget(+ name="OpenCode",+ config_path=config_path,+ entry_key="skyvern",+ entry=entry,+ config_format="opencode",+ entry_path=["mcp"],+ )+ profile = _build_profile("Prod", "new-key-1234567890", "https://alt.skyvern.example")++ changed, backup_path = _apply_profile_to_target(target, profile)++ assert changed is True+ assert backup_path is not None+ written = json.loads(config_path.read_text(encoding="utf-8"))+ written_entry = written["mcp"]["skyvern"]+ assert written_entry["type"] == "local"+ assert written_entry["command"] == [sys.executable, "-m", "skyvern", "run", "mcp"]+ assert written_entry["environment"]["SKYVERN_API_KEY"] == "new-key-1234567890"+ assert written_entry["environment"]["SKYVERN_BASE_URL"] == "https://alt.skyvern.example"+ assert written_entry["environment"]["OTHER"] == "keep-me"+ assert "env" not in written_entry++def test_patch_entry_with_profile_preserves_openclaw_transport_and_extras() -> None:profile = _build_profile("Prod", "new-key-1234567890", "https://alt.skyvern.example")entry = {@@ -672,7 +740,7 @@ def test_discover_switch_targets_finds_claude_code_and_codex(assert discovered_by_name["Codex"].entry_key == "skyvern"assert discovered_by_name["OpenClaw"].entry_key == "skyvern"assert discovered_by_name["OpenClaw"].entry_path == ["mcp", "servers"]- assert {name for name, _ in missing} == {"Claude Desktop", "Cursor", "Windsurf", "Hermes"}+ assert {name for name, _ in missing} == {"Claude Desktop", "Cursor", "Windsurf", "OpenCode", "Hermes"}def test_discover_switch_targets_reports_openclaw_invalid_nested_structure(diff --git a/tests/unit/test_setup_opencode.py b/tests/unit/test_setup_opencode.pynew file mode 100644index 000000000..521aac67d--- /dev/null+++ b/tests/unit/test_setup_opencode.py@@ -0,0 +1,144 @@+"""Tests for skyvern setup opencode command (fixes OAuth callback timeouts in OpenCode)."""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner++from skyvern.cli.setup_commands import _mask_secrets, setup_app++runner = CliRunner()+++def _load_json(path: Path) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def opencode_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ config_dir = tmp_path / ".config" / "opencode"+ monkeypatch.setattr("skyvern.cli.setup_commands.Path.home", lambda: tmp_path)+ monkeypatch.setenv("SKYVERN_API_KEY", "test-key-1234567890")+ monkeypatch.setenv("SKYVERN_BASE_URL", "https://api.skyvern.com")+ return config_dir+++def test_setup_opencode_writes_remote_config_with_oauth_disabled(opencode_home: Path) -> None:+ result = runner.invoke(setup_app, ["opencode", "--yes"])++ assert result.exit_code == 0, result.output+ config = _load_json(opencode_home / "opencode.json")+ entry = config["mcp"]["skyvern"]+ assert entry["type"] == "remote"+ assert entry["url"] == "https://api.skyvern.com/mcp/"+ assert entry["oauth"] is False+ assert entry["headers"]["x-api-key"] == "test-key-1234567890"+ assert "opencode mcp auth" in result.output+++def test_setup_opencode_writes_local_stdio_config(opencode_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SKYVERN_BASE_URL", "http://localhost:8000")++ result = runner.invoke(setup_app, ["opencode", "--local", "--yes"])++ assert result.exit_code == 0, result.output+ config = _load_json(opencode_home / "opencode.json")+ entry = config["mcp"]["skyvern"]+ assert entry["type"] == "local"+ assert entry["command"] == [sys.executable, "-m", "skyvern", "run", "mcp"]+ assert entry["environment"]["SKYVERN_BASE_URL"] == "http://localhost:8000"+ assert entry["environment"]["SKYVERN_API_KEY"] == "test-key-1234567890"+ assert "oauth" not in entry+++def test_setup_opencode_case_insensitive_key(opencode_home: Path) -> None:+ config_path = opencode_home / "opencode.json"+ config_path.parent.mkdir(parents=True)+ config_path.write_text(+ json.dumps(+ {+ "mcp": {+ "Skyvern": {+ "type": "remote",+ "url": "https://old.example.com/mcp/",+ "oauth": True,+ }+ }+ }+ )+ + "\n",+ encoding="utf-8",+ )++ result = runner.invoke(setup_app, ["opencode", "--yes"])++ assert result.exit_code == 0, result.output+ config = _load_json(config_path)+ entry = config["mcp"]["Skyvern"]+ assert entry["url"] == "https://api.skyvern.com/mcp/"+ assert entry["oauth"] is False+ assert entry["headers"]["x-api-key"] == "test-key-1234567890"+++def test_setup_opencode_respects_opencode_config_env(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ custom_config = tmp_path / "custom-opencode.json"+ monkeypatch.setenv("OPENCODE_CONFIG", str(custom_config))+ monkeypatch.setenv("SKYVERN_API_KEY", "test-key-1234567890")+ monkeypatch.setenv("SKYVERN_BASE_URL", "https://api.skyvern.com")++ result = runner.invoke(setup_app, ["opencode", "--yes"])++ assert result.exit_code == 0, result.output+ config = _load_json(custom_config)+ assert config["mcp"]["skyvern"]["oauth"] is False+++def test_setup_opencode_accepts_jsonc_config(opencode_home: Path) -> None:+ config_path = opencode_home / "opencode.json"+ config_path.parent.mkdir(parents=True)+ config_path.write_text(+ """+{+ // OpenCode configs are JSONC.+ "mcp": {+ "skyvern": {+ "type": "remote",+ "url": "https://old.example.com/mcp/",+ "oauth": true,+ },+ },+}+""",+ encoding="utf-8",+ )++ result = runner.invoke(setup_app, ["opencode", "--yes"])++ assert result.exit_code == 0, result.output+ config = _load_json(config_path)+ entry = config["mcp"]["skyvern"]+ assert entry["url"] == "https://api.skyvern.com/mcp/"+ assert entry["oauth"] is False+ assert entry["headers"]["x-api-key"] == "test-key-1234567890"+++def test_mask_secrets_masks_opencode_environment_api_key() -> None:+ masked = _mask_secrets(+ {+ "type": "local",+ "command": [sys.executable, "-m", "skyvern", "run", "mcp"],+ "environment": {+ "SKYVERN_BASE_URL": "http://localhost:8000",+ "SKYVERN_API_KEY": "test-key-1234567890",+ },+ }+ )++ assert masked["environment"]["SKYVERN_API_KEY"] == "test****7890"