Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: add clipboard read/write MCP tools (PR 7/7) (#5365)
Marc Kelechava58fed69496bd
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.pyindex d1b1c5e8d..f01eeb31e 100644--- a/skyvern/cli/commands/browser.py+++ b/skyvern/cli/commands/browser.py@@ -1883,3 +1883,51 @@ def find_cmd(output(data, action="find", json_mode=json_output)except Exception as e:output_error(str(e), json_mode=json_output)+++# ---------------------------------------------------------------------------+++@browser_app.command("clipboard-read")+def clipboard_read_cmd(+ session: str | None = typer.Option(None, help="Browser session ID."),+ cdp: str | None = typer.Option(None, "--cdp", help="CDP WebSocket URL."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Read text from the browser clipboard."""+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read++ async def _run() -> dict:+ return await skyvern_clipboard_read(session_id=session, cdp_url=cdp)++ try:+ result = asyncio.run(_run())+ if result.get("ok"):+ output(result["data"], action="clipboard_read", json_mode=json_output)+ else:+ output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)+ except Exception as e:+ output_error(str(e), json_mode=json_output)+++@browser_app.command("clipboard-write")+def clipboard_write_cmd(+ text: str = typer.Argument(..., help="Text to write to the clipboard."),+ session: str | None = typer.Option(None, help="Browser session ID."),+ cdp: str | None = typer.Option(None, "--cdp", help="CDP WebSocket URL."),+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),+) -> None:+ """Write text to the browser clipboard."""+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_write++ async def _run() -> dict:+ return await skyvern_clipboard_write(text=text, session_id=session, cdp_url=cdp)++ try:+ result = asyncio.run(_run())+ if result.get("ok"):+ output(result["data"], action="clipboard_write", json_mode=json_output)+ else:+ output_error(result.get("error", {}).get("message", "Unknown error"), json_mode=json_output)+ except Exception as e:+ output_error(str(e), json_mode=json_output)diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex c0d94b056..bf1c1bca0 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -15,6 +15,8 @@ from .blocks import (from .browser import (skyvern_act,skyvern_click,+ skyvern_clipboard_read,+ skyvern_clipboard_write,skyvern_drag,skyvern_evaluate,skyvern_extract,@@ -152,6 +154,8 @@ targeted test cases, open a browser against the dev server, and report pass/fail| "Search for X on [site]" / "Look up X" | skyvern_act | Natural language actions || "Verify / check / confirm something on [site]" | skyvern_validate | AI assertion || "Fill out / submit a form" | skyvern_act | Multi-step form interaction |+| "Read clipboard" / "Paste from clipboard" | skyvern_clipboard_read | Read text from the browser clipboard |+| "Copy to clipboard" / "Write clipboard" | skyvern_clipboard_write | Write text to the browser clipboard || "Click [element]" / "Type [text]" | skyvern_click / skyvern_type | Precision targeting || "Hover over [menu]" | skyvern_hover | Reveal dropdowns || "Drag [element] to [target]" | skyvern_drag | AI or selector-based drag-and-drop |@@ -385,6 +389,10 @@ mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_navigate)mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_screenshot)mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_evaluate)+# -- Clipboard --+mcp.tool(tags={"browser_primitive"}, annotations=_RO)(skyvern_clipboard_read)+mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_clipboard_write)+# -- Precision tools (selector/intent-based browser primitives) --mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_click)mcp.tool(tags={"browser_primitive"}, annotations=_MUT)(skyvern_drag)@@ -487,6 +495,9 @@ __all__ = ["skyvern_navigate","skyvern_screenshot","skyvern_evaluate",+ # Clipboard+ "skyvern_clipboard_read",+ "skyvern_clipboard_write",# Precision (selector/intent browser primitives)"skyvern_click","skyvern_drag",diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.pyindex 935eb4db6..427717a25 100644--- a/skyvern/cli/mcp_tools/browser.py+++ b/skyvern/cli/mcp_tools/browser.py@@ -1862,3 +1862,90 @@ async def skyvern_find(},timing_ms=timer.timing_ms,)+++async def _ensure_clipboard_permissions(page: Any) -> None:+ """Grant clipboard permissions on the browser context (lazy, idempotent)."""+ try:+ await page.context.grant_permissions(["clipboard-read", "clipboard-write"])+ except Exception:+ LOG.debug("clipboard_permission_grant_skipped", exc_info=True)+++async def skyvern_clipboard_read(+ session_id: Annotated[str | None, Field(description="Browser session ID.")] = None,+ cdp_url: Annotated[str | None, Field(description="CDP WebSocket URL.")] = None,+) -> dict[str, Any]:+ """Read text from the browser clipboard (whatever was last copied via Ctrl+C or clipboard_write).++ Returns the current clipboard text content. Requires secure context+ (HTTPS or localhost). Clipboard permissions are granted automatically+ on first use.+ """+ try:+ page, ctx = await get_page(session_id=session_id, cdp_url=cdp_url)+ except BrowserNotAvailableError:+ return make_result("skyvern_clipboard_read", ok=False, error=no_browser_error())++ with Timer() as timer:+ try:+ await _ensure_clipboard_permissions(page)+ text = await page.evaluate("() => navigator.clipboard.readText()")+ timer.mark("clipboard_read")+ except Exception as e:+ return make_result(+ "skyvern_clipboard_read",+ ok=False,+ browser_context=ctx,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.ACTION_FAILED, str(e), "Ensure the page is a secure context (HTTPS or localhost)"+ ),+ )++ return make_result(+ "skyvern_clipboard_read",+ browser_context=ctx,+ data={"text": text},+ timing_ms=timer.timing_ms,+ )+++async def skyvern_clipboard_write(+ text: Annotated[str, Field(description="Text to write to the clipboard.")],+ session_id: Annotated[str | None, Field(description="Browser session ID.")] = None,+ cdp_url: Annotated[str | None, Field(description="CDP WebSocket URL.")] = None,+) -> dict[str, Any]:+ """Copy text to the browser clipboard (as if the user pressed Ctrl+C).++ The text can then be pasted into form fields or read back with+ clipboard_read. Requires secure context (HTTPS or localhost).+ Clipboard permissions are granted automatically on first use.+ """+ try:+ page, ctx = await get_page(session_id=session_id, cdp_url=cdp_url)+ except BrowserNotAvailableError:+ return make_result("skyvern_clipboard_write", ok=False, error=no_browser_error())++ with Timer() as timer:+ try:+ await _ensure_clipboard_permissions(page)+ await page.evaluate("(t) => navigator.clipboard.writeText(t)", text)+ timer.mark("clipboard_write")+ except Exception as e:+ return make_result(+ "skyvern_clipboard_write",+ ok=False,+ browser_context=ctx,+ timing_ms=timer.timing_ms,+ error=make_error(+ ErrorCode.ACTION_FAILED, str(e), "Ensure the page is a secure context (HTTPS or localhost)"+ ),+ )++ return make_result(+ "skyvern_clipboard_write",+ browser_context=ctx,+ data={"written": True, "length": len(text)},+ timing_ms=timer.timing_ms,+ )diff --git a/tests/unit/test_mcp_clipboard.py b/tests/unit/test_mcp_clipboard.pynew file mode 100644index 000000000..b4d322bf6--- /dev/null+++ b/tests/unit/test_mcp_clipboard.py@@ -0,0 +1,217 @@+"""Tests for MCP clipboard tools (skyvern_clipboard_read, skyvern_clipboard_write)."""++from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.cli.core.result import BrowserContext++# ═══════════════════════════════════════════════════+# Helpers+# ═══════════════════════════════════════════════════+++def _make_mock_page(url: str = "https://example.com") -> MagicMock:+ page = MagicMock()+ page.url = url+ page.page = page # SkyvernBrowserPage wraps raw page+ page.context = MagicMock()+ page.context.grant_permissions = AsyncMock()+ return page+++def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:+ from skyvern.cli.mcp_tools import browser as mcp_browser++ mock = AsyncMock(return_value=(page, ctx))+ monkeypatch.setattr(mcp_browser, "get_page", mock)+ return mock+++# ═══════════════════════════════════════════════════+# _ensure_clipboard_permissions+# ═══════════════════════════════════════════════════+++async def test_ensure_clipboard_permissions_calls_grant(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import _ensure_clipboard_permissions++ page = _make_mock_page()+ await _ensure_clipboard_permissions(page)+ page.context.grant_permissions.assert_awaited_once_with(["clipboard-read", "clipboard-write"])+++async def test_ensure_clipboard_permissions_survives_error(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import _ensure_clipboard_permissions++ page = _make_mock_page()+ page.context.grant_permissions = AsyncMock(side_effect=Exception("not supported"))+ # Should not raise+ await _ensure_clipboard_permissions(page)+++# ═══════════════════════════════════════════════════+# skyvern_clipboard_read+# ═══════════════════════════════════════════════════+++async def test_clipboard_read_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read++ page = _make_mock_page()+ page.evaluate = AsyncMock(return_value="hello world")+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_read()++ assert result["ok"] is True+ assert result["data"]["text"] == "hello world"+++async def test_clipboard_read_empty(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read++ page = _make_mock_page()+ page.evaluate = AsyncMock(return_value="")+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_read()++ assert result["ok"] is True+ assert result["data"]["text"] == ""+++async def test_clipboard_read_no_browser(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools import browser as mcp_browser+ from skyvern.cli.mcp_tools._session import BrowserNotAvailableError+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read++ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(side_effect=BrowserNotAvailableError()))++ result = await skyvern_clipboard_read()+ assert result["ok"] is False+++async def test_clipboard_read_evaluate_error(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read++ page = _make_mock_page()+ page.evaluate = AsyncMock(side_effect=Exception("Clipboard API not available"))+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_read()++ assert result["ok"] is False+ assert "Clipboard API not available" in result["error"]["message"]+++# ═══════════════════════════════════════════════════+# skyvern_clipboard_write+# ═══════════════════════════════════════════════════+++async def test_clipboard_write_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_write++ page = _make_mock_page()+ page.evaluate = AsyncMock(return_value=None)+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_write(text="copied text")++ assert result["ok"] is True+ assert result["data"]["written"] is True+ assert result["data"]["length"] == 11+++async def test_clipboard_write_empty_string(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_write++ page = _make_mock_page()+ page.evaluate = AsyncMock(return_value=None)+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_write(text="")++ assert result["ok"] is True+ assert result["data"]["written"] is True+ assert result["data"]["length"] == 0+++async def test_clipboard_write_no_browser(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools import browser as mcp_browser+ from skyvern.cli.mcp_tools._session import BrowserNotAvailableError+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_write++ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(side_effect=BrowserNotAvailableError()))++ result = await skyvern_clipboard_write(text="hello")+ assert result["ok"] is False+++async def test_clipboard_write_evaluate_error(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_write++ page = _make_mock_page()+ page.evaluate = AsyncMock(side_effect=Exception("Permission denied"))+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ result = await skyvern_clipboard_write(text="hello")++ assert result["ok"] is False+ assert "Permission denied" in result["error"]["message"]+++# ═══════════════════════════════════════════════════+# Roundtrip+# ═══════════════════════════════════════════════════+++async def test_clipboard_roundtrip(monkeypatch: pytest.MonkeyPatch) -> None:+ """Write → Read roundtrip using a simulated clipboard."""+ from skyvern.cli.mcp_tools.browser import skyvern_clipboard_read, skyvern_clipboard_write++ clipboard_store: dict[str, str] = {"text": ""}++ page = _make_mock_page()++ async def mock_evaluate(expr: Any, *args: Any) -> Any:+ if "writeText" in str(expr):+ clipboard_store["text"] = args[0] if args else ""+ return None+ if "readText" in str(expr):+ return clipboard_store["text"]+ return None++ page.evaluate = mock_evaluate+ ctx = BrowserContext(mode="local")+ _patch_get_page(monkeypatch, page, ctx)++ # Write+ write_result = await skyvern_clipboard_write(text="roundtrip test")+ assert write_result["ok"] is True++ # Read back+ read_result = await skyvern_clipboard_read()+ assert read_result["ok"] is True+ assert read_result["data"]["text"] == "roundtrip test"