Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
docs(SKY-12601): make MCP element-ref lifetime truthful per transport (stdio vs hosted HTTP) (#7519)
Marc Kelechava579c9ed2e8f1
diff --git a/skills/skyvern/SKILL.md b/skills/skyvern/SKILL.mdindex 4af725fb2..da5bbc2eb 100644--- a/skills/skyvern/SKILL.md+++ b/skills/skyvern/SKILL.md@@ -20,7 +20,7 @@ Skyvern uses AI to navigate and interact with websites. Every command below is a| Throwaway autonomous trial | "try this once", "see if this works" | `skyvern browser run-task` | Higher | One-off autonomous agent for exploration. Do not use for recurring or multi-page production automations. || Multi-page or reusable automation | "navigate a multi-page wizard", "set this up", "automate this weekly" | `skyvern workflow create` + `run` | N LLM + screenshots | Build a workflow with one block per step. Each block gets visual reasoning, verification, and reusable run history. |-**MCP note:** if you are using the Skyvern MCP instead of the CLI, prefer `observe + execute` for same-page multi-step UI work. The CLI does not expose that pair directly.+**MCP note:** if you are using the Skyvern MCP instead of the CLI, prefer `observe + execute` for same-page multi-step UI work on stdio; refs persist across calls until the next observe, navigation, or page/document context change. On hosted stateless HTTP, prefer `selector` or `intent` params; prior-call refs do not resolve, and one execute batch can use refs only when predictable before the call, never adaptively from an inline observe. The CLI does not expose that pair directly.## Step 2: Apply These Decision Rules@@ -90,7 +90,7 @@ skyvern browser act --prompt "Close the cookie banner, then click Sign In"```**Warning:** act has NO screenshots in its LLM reasoning. It uses an economy accessibility tree.-Fine for well-labeled elements. For visually complex targets, use MCP observe+click or hybrid mode.+Fine for well-labeled elements. For visually complex targets, use MCP observe+execute on stdio (on hosted stateless HTTP prefer selector/intent) or hybrid mode.### Same-page multi-stepdiff --git a/skills/skyvern/references/quick-start-patterns.md b/skills/skyvern/references/quick-start-patterns.mdindex 6bb38563d..3a43bf7de 100644--- a/skills/skyvern/references/quick-start-patterns.md+++ b/skills/skyvern/references/quick-start-patterns.md@@ -22,7 +22,10 @@ skyvern_click(selector="#submit") or skyvern_type(selector="#email", text="user@skyvern_act(prompt="Click the Sign In button")```-## Multi-step (simple, PREFERRED for forms)+## Multi-step (simple)++On stdio transports, refs persist across calls until the next observe, navigation, or page/document context change. Follow this pattern:+1. `skyvern_observe()` returns element refs (`e0`, `e1`, ...)2. Your LLM decides which refs to interact with3. Run `skyvern_execute(...)` with those refs, for example:@@ -36,6 +39,8 @@ skyvern_execute()```+On hosted stateless HTTP, prefer `selector` or `intent` params because refs from prior calls do not resolve. A single `skyvern_execute` batch may use refs only when predictable before the call; refs returned by an inline observe cannot be selected adaptively later in that batch.+## Throwaway autonomous trial```skyvern_run_task(prompt="Try the checkout flow once and tell me whether it succeeds")diff --git a/skills/skyvern/references/sessions.md b/skills/skyvern/references/sessions.mdindex ecdf6e333..5730d5b08 100644--- a/skills/skyvern/references/sessions.md+++ b/skills/skyvern/references/sessions.md@@ -1,10 +1,21 @@# Session Reuse-## When to reuse a session+This guidance is about **runtime session reuse** — passing a `pbs_*` ID as `browser_session_id`+to `skyvern_workflow_run` or `skyvern_run_task` so a one-off run continues a browser that is+already open.-- Multiple actions on one authenticated site.-- Workflow chains that depend on retained state.-- Follow-up extraction immediately after login.+It is NOT about the workflow-level "Save & Reuse Session" toggle (`persist_browser_session`).+Leave that toggle unset unless the user explicitly asks for cross-run state retention — it+defaults to off and should stay off.++Blocks inside a single workflow already share one browser session automatically — do NOT+pass `browser_session_id` to keep state between blocks of the same run. Reach for runtime+session reuse only across separate runs.++## When to reuse a runtime session++- A follow-up task that depends on state from a session you just opened.+- Chained workflow runs where a later run needs the authenticated state from the first.## When to start freshdiff --git a/skills/skyvern/references/tool-map.md b/skills/skyvern/references/tool-map.mdindex f56e8d0ce..f2def6d65 100644--- a/skills/skyvern/references/tool-map.md+++ b/skills/skyvern/references/tool-map.md@@ -54,10 +54,12 @@| `skyvern_workflow_create` | Create a workflow definition || `skyvern_workflow_list` | List workflows || `skyvern_workflow_get` | Get workflow details |+| `skyvern_workflow_run_list` | List runs for a workflow || `skyvern_workflow_update` | Update a workflow || `skyvern_workflow_delete` | Delete a workflow || `skyvern_workflow_run` | Execute a workflow || `skyvern_workflow_status` | Check run status |+| `skyvern_workflow_retry` | Retry a terminal workflow run || `skyvern_workflow_cancel` | Cancel a running workflow |## Workflow blocksdiff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex e999d3db0..ffc9ac560 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -172,7 +172,7 @@ from .workflow import (_RUN_TASK_TOOL_DESCRIPTION = ("Run a one-off autonomous trial via the highest-cost AI path. ""Not for production or reusable automations. "- "Prefer direct tools (click/type/select via selector/ref) and skyvern_observe + skyvern_execute."+ "Prefer direct tools (click/type/select via selector) and skyvern_observe + skyvern_execute.")@@ -235,7 +235,7 @@ static JSON/XML fetches, or generic web search.| Quick inspection | "what does the page show?" | skyvern_extract | 1 LLM + screenshots | Dedicated extraction LLM + schema validation + caching. Better than screenshot+read. || Single action (known target) | "click #submit" | skyvern_click / skyvern_type | 0 LLM | Deterministic Playwright. No AI. Fastest. || Single action (unknown target) | "click the submit button" | skyvern_act | 2-3 LLM, no screenshots | No screenshots in reasoning. Economy a11y tree. For visual targets, use observe first. |-| Multi-step (simple, fast) | "fill the form and submit" | skyvern_observe + skyvern_execute | 0 Skyvern LLM | A11y tree + YOUR LLM plans from refs + batched primitives. Fast, cheap. |+| Multi-step (simple, fast) | "fill the form and submit" | skyvern_observe + skyvern_execute | 0 Skyvern LLM | On stdio, refs persist across calls until the next observe, navigation, or page/document change. On hosted stateless HTTP, prefer selector/intent; refs work only within one execute batch when predictable in advance, never adaptively from an inline observe. || Throwaway autonomous trial | "try this once", "see if this works" | skyvern_run_task | Higher | One-off autonomous agent for exploratory work. Do not use for reusable or multi-page production automations. || Multi-step (complex) | "navigate a multi-page wizard" | skyvern_workflow_create (multi-block) | N LLM + screenshots | Build a workflow with one navigation block per step. Each block gets visual reasoning + verification. || Reusable workflow | "automate this", "wizard", "multi-step", "production" | skyvern_workflow_create | Varies | Caching converts AI runs into deterministic scripts over time (10-100x faster on repeat). |@@ -245,7 +245,7 @@ static JSON/XML fetches, or generic web search.1. If the user gives a selector, id, XPath, or exact field target, use browser primitives -- not skyvern_act.2. If you only need a yes/no answer, use skyvern_validate -- not skyvern_extract or skyvern_act.-3. If the work stays on one page and the UI is standard, prefer skyvern_observe + skyvern_execute.+3. If the work stays on one page and the UI is standard, prefer skyvern_observe + skyvern_execute on stdio, where refs persist across calls until the next observe, navigation, or page/document change. On hosted stateless HTTP, prefer selector or intent; use refs within one skyvern_execute batch only when predictable before the call, never adaptively from an inline observe.4. If the user says "try this once", "see if this works", or clearly wants a one-off exploratory trial, use skyvern_run_task.5. If the task spans multiple pages and is meant to be reusable/repeatable, use skyvern_workflow_create. To run it on a recurring cadence, follow up with skyvern_schedule_create against the resulting workflow_permanent_id.6. Never type passwords. Always use skyvern_login with stored credentials.@@ -256,13 +256,13 @@ static JSON/XML fetches, or generic web search.- **Inspection:** skyvern_extract(prompt="Extract all prices", schema='{"type":"object","properties":{...}}')- **Known selector:** skyvern_click(selector="#submit") or skyvern_type(selector="#email", text="[email protected]")- **Unknown target:** skyvern_act(prompt="Click the Sign In button")-- **Multi-step form:** skyvern_observe() -> skyvern_execute(steps=[...])+- **Multi-step form:** stdio: skyvern_observe() -> skyvern_execute(steps=[...]); hosted stateless HTTP: prefer selector/intent, or use refs in one execute batch only when known before the call (not adaptively from an inline observe).- **One-off trial:** skyvern_run_task(prompt="Try the checkout flow once")- **Reusable workflow:** skyvern_workflow_create(definition='{"title":"...","workflow_definition":{"blocks":[...]}}', format="json")## Key Warnings-1. **act has NO screenshots** — uses economy a11y tree. For visual targets, use observe then click with ref.+1. **act has NO screenshots** — uses economy a11y tree. For visual targets, use observe, then execute with refs on stdio; on hosted stateless HTTP prefer selector/intent (see decision rule 3).2. **observe+execute ≠ workflows.** observe+execute: YOUR LLM plans, no Skyvern calls. Workflows: full ForgeAgent per block with screenshots.3. **validate is cheapest AI** for yes/no. **extract uses screenshots** with dedicated LLM.4. **NEVER type passwords** — use skyvern_login with stored credentials.diff --git a/skyvern/cli/mcp_tools/_common.py b/skyvern/cli/mcp_tools/_common.pyindex 2e7b56b83..1181d318e 100644--- a/skyvern/cli/mcp_tools/_common.py+++ b/skyvern/cli/mcp_tools/_common.py@@ -13,7 +13,7 @@ from skyvern.client.errors import NotFoundErrorDIRECT_TARGET_DESCRIPTION = "Direct target: deterministic, 0 LLM calls."AI_FALLBACK_DESCRIPTION = (- "AI fallback: costs Skyvern LLM calls, slower and nondeterministic — prefer selector/ref when known."+ "AI fallback: costs Skyvern LLM calls, slower and nondeterministic — prefer selector when known.")diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.pyindex b398b90c8..a7fa96a9c 100644--- a/skyvern/cli/mcp_tools/browser.py+++ b/skyvern/cli/mcp_tools/browser.py@@ -50,6 +50,7 @@ from skyvern.cli.core.guards import resolve_ai_mode as _resolve_ai_modefrom skyvern.cli.core.guards import (validate_wait_until,)+from skyvern.cli.core.session_manager import is_stateless_http_modefrom skyvern.cli.core.trajectory_store import append_trajectory_entryfrom skyvern.core.script_generations.skyvern_page import SkyvernPage@@ -1956,7 +1957,7 @@ async def skyvern_act() -> dict[str, Any]:"""Perform actions on a page by describing what to do in plain English. No screenshots in reasoning — uses economy a11y tree.Chain multiple actions in one prompt: "close the cookie banner, then click Sign In".- For visually complex targets, use skyvern_observe + skyvern_click with refs. NEVER include passwords — use skyvern_login.+ For visually complex targets, use skyvern_observe + skyvern_execute with refs on stdio; on hosted stateless HTTP prefer selector or intent. NEVER include passwords — use skyvern_login."""try:check_password_prompt(prompt)@@ -2026,7 +2027,7 @@ async def skyvern_run_task(] = 180,) -> dict[str, Any]:"""Run a one-off autonomous trial via the highest-cost AI path. Not for production or reusable automations.- Prefer direct tools (click/type/select via selector/ref) and skyvern_observe + skyvern_execute. Always uses engine 2.0.+ Prefer direct tools (click/type/select via selector) and skyvern_observe + skyvern_execute. Always uses engine 2.0."""# Block password/credential actions — redirect to skyvern_loginif PASSWORD_PATTERN.search(prompt):@@ -2624,7 +2625,7 @@ async def skyvern_observe(),] = False,) -> dict[str, Any]:- """Snapshot interactive elements with refs reusable in this browser session until the next observe or page/document context change (rarely earlier — on 'Unknown ref', re-observe). Input values are omitted by default; set include_values=True to return non-password values. Password values are never returned."""+ """Snapshot interactive elements. On stdio, refs persist across calls until the next observe or page/document context change (rarely earlier — on 'Unknown ref', re-observe). In hosted stateless HTTP, refs from prior requests do not resolve; prefer selector or intent params, using refs from an inline observe in one skyvern_execute batch only when predictable in advance. Input values are omitted by default; set include_values=True to return non-password values. Password values are never returned."""try:page, ctx = await get_page(session_id=session_id, cdp_url=cdp_url)except BrowserNotAvailableError:@@ -2674,9 +2675,11 @@ async def skyvern_observe(f"{f' (of {result.total_on_page} total on page)' if result.total_on_page > result.element_count else ''}. ""Use these refs in skyvern_execute steps, e.g.: "'{tool: "click", params: {ref: "e0"}}. '- "Refs remain valid across calls in this browser session until the next skyvern_observe, "+ "On stdio, refs remain valid across calls until the next skyvern_observe, ""skyvern_navigate, same-tab navigation, or tab/frame switch. Same-document DOM changes can also ""invalidate ordinal refs; re-observe on 'Unknown ref' or unexpected failures. "+ "In hosted stateless HTTP, refs from prior requests do not resolve; prefer selector or intent params, "+ "using refs from an inline observe in one skyvern_execute batch only when predictable in advance. ""Input values are omitted unless include_values=true; password values are never returned.")return make_result(@@ -2749,7 +2752,10 @@ async def _dispatch_step(if elem is None:elem = get_session_ref(ref, session_id=session_id, cdp_url=cdp_url, page_key=current_key)if elem is None:- raise ValueError(f"Unknown ref '{ref}' — call observe first or check ref exists")+ message = f"Unknown ref '{ref}' — call observe first or check ref exists"+ if is_stateless_http_mode():+ message += ". In stateless HTTP mode refs from prior requests do not resolve — use selector or intent params instead."+ raise ValueError(message)params["selector"] = ref_to_selector(elem)# Observe is handled inline (not an existing MCP tool)@@ -2802,10 +2808,11 @@ async def skyvern_execute(Field(description=("Array of {tool, params} step objects to execute sequentially. "- "Within params, refs from skyvern_observe are direct targets across calls in the same browser session. "- "The next skyvern_observe or page/document context change invalidates them; they can occasionally "- "expire early. Same-document DOM changes can also invalidate ordinal refs; on 'Unknown ref' or "- "unexpected failures, re-observe. "+ "Within params, refs from skyvern_observe are direct targets across calls on stdio transports until "+ "the next skyvern_observe, navigation, or page/document context change; they can occasionally expire "+ "early. In hosted stateless HTTP, refs from prior requests do not resolve; prefer selector or intent params, "+ "using observe+ref steps in a single batch only when refs are predictable in advance. Same-document DOM "+ "changes can also invalidate ordinal refs; on 'Unknown ref' or unexpected failures, re-observe. "f"{DIRECT_TARGET_DESCRIPTION}")),@@ -2817,7 +2824,7 @@ async def skyvern_execute(Field(description="Stop at first failure (true) or continue past errors (false). Default true."),] = True,) -> dict[str, Any]:- """Execute browser operations using current-session refs until the next observe or page/document context change.+ """Execute browser operations. On stdio, refs persist across calls until the next observe, navigation, or page/document context change. In hosted stateless HTTP, refs from prior requests do not resolve; prefer selector or intent params, using observe+ref steps in one batch only when refs are predictable in advance.Allowed tools: navigate, click, type, press_key, select_option, hover, scroll, wait, observe, screenshot, evaluate."""if not steps:return make_result(diff --git a/skyvern/cli/skills/skyvern/SKILL.md b/skyvern/cli/skills/skyvern/SKILL.mdindex 4af725fb2..da5bbc2eb 100644--- a/skyvern/cli/skills/skyvern/SKILL.md+++ b/skyvern/cli/skills/skyvern/SKILL.md@@ -20,7 +20,7 @@ Skyvern uses AI to navigate and interact with websites. Every command below is a| Throwaway autonomous trial | "try this once", "see if this works" | `skyvern browser run-task` | Higher | One-off autonomous agent for exploration. Do not use for recurring or multi-page production automations. || Multi-page or reusable automation | "navigate a multi-page wizard", "set this up", "automate this weekly" | `skyvern workflow create` + `run` | N LLM + screenshots | Build a workflow with one block per step. Each block gets visual reasoning, verification, and reusable run history. |-**MCP note:** if you are using the Skyvern MCP instead of the CLI, prefer `observe + execute` for same-page multi-step UI work. The CLI does not expose that pair directly.+**MCP note:** if you are using the Skyvern MCP instead of the CLI, prefer `observe + execute` for same-page multi-step UI work on stdio; refs persist across calls until the next observe, navigation, or page/document context change. On hosted stateless HTTP, prefer `selector` or `intent` params; prior-call refs do not resolve, and one execute batch can use refs only when predictable before the call, never adaptively from an inline observe. The CLI does not expose that pair directly.## Step 2: Apply These Decision Rules@@ -90,7 +90,7 @@ skyvern browser act --prompt "Close the cookie banner, then click Sign In"```**Warning:** act has NO screenshots in its LLM reasoning. It uses an economy accessibility tree.-Fine for well-labeled elements. For visually complex targets, use MCP observe+click or hybrid mode.+Fine for well-labeled elements. For visually complex targets, use MCP observe+execute on stdio (on hosted stateless HTTP prefer selector/intent) or hybrid mode.### Same-page multi-stepdiff --git a/skyvern/cli/skills/skyvern/references/quick-start-patterns.md b/skyvern/cli/skills/skyvern/references/quick-start-patterns.mdindex 6bb38563d..3a43bf7de 100644--- a/skyvern/cli/skills/skyvern/references/quick-start-patterns.md+++ b/skyvern/cli/skills/skyvern/references/quick-start-patterns.md@@ -22,7 +22,10 @@ skyvern_click(selector="#submit") or skyvern_type(selector="#email", text="user@skyvern_act(prompt="Click the Sign In button")```-## Multi-step (simple, PREFERRED for forms)+## Multi-step (simple)++On stdio transports, refs persist across calls until the next observe, navigation, or page/document context change. Follow this pattern:+1. `skyvern_observe()` returns element refs (`e0`, `e1`, ...)2. Your LLM decides which refs to interact with3. Run `skyvern_execute(...)` with those refs, for example:@@ -36,6 +39,8 @@ skyvern_execute()```+On hosted stateless HTTP, prefer `selector` or `intent` params because refs from prior calls do not resolve. A single `skyvern_execute` batch may use refs only when predictable before the call; refs returned by an inline observe cannot be selected adaptively later in that batch.+## Throwaway autonomous trial```skyvern_run_task(prompt="Try the checkout flow once and tell me whether it succeeds")diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.pyindex d4521bab8..ec85b6b72 100644--- a/tests/unit/test_mcp_browser_tools.py+++ b/tests/unit/test_mcp_browser_tools.py@@ -246,7 +246,7 @@ async def test_run_task_schema_description_demotes_autonomous_trial() -> None:assert "highest-cost AI path" in descriptionassert "Not for production or reusable automations" in descriptionassert "Prefer direct tools" in description- assert "selector/ref" in description+ assert "via selector" in descriptionassert "skyvern_observe + skyvern_execute" in descriptiondiff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.pyindex f8cb4f1ef..1b7638208 100644--- a/tests/unit/test_mcp_observe_execute.py+++ b/tests/unit/test_mcp_observe_execute.py@@ -25,6 +25,7 @@ from skyvern.cli.core.browser_ops import (from skyvern.cli.core.result import BrowserContextfrom skyvern.cli.core.session_manager import scoped_sessionfrom skyvern.cli.mcp_tools import browser as mcp_browser+from skyvern.cli.mcp_tools import mcpfrom skyvern.cli.mcp_tools import tabs as mcp_tabsfrom skyvern.client.errors import InternalServerErrorfrom skyvern.library.skyvern_browser_page import SkyvernBrowserPage@@ -887,6 +888,30 @@ class TestDoExecute:# ---------------------------------------------------------------------------+async def test_observe_execute_tool_contract_qualifies_ref_lifetime_by_transport() -> None:+ tools = {tool.name: tool for tool in await mcp.list_tools()}+ observe = tools["skyvern_observe"]+ execute = tools["skyvern_execute"]+ surfaces = {+ "observe description": observe.description,+ "execute description": execute.description,+ "execute steps schema": execute.parameters["properties"]["steps"]["description"],+ "server instructions": mcp.instructions,+ }++ for surface, text in surfaces.items():+ assert text is not None, f"Missing {surface}"+ normalized = text.lower()+ for term in ("stdio", "stateless http", "selector", "intent"):+ assert term in normalized, f"{surface} missing {term!r}"+ assert "across calls in this browser session" not in normalized+ assert "across calls in the same browser session" not in normalized+ assert "do not persist" not in normalized, f"{surface} uses persist wording for the hosted failure"+ if surface != "server instructions":+ assert "do not resolve" in normalized, f"{surface} missing resolve semantics"++class TestSkyvernObserveMCP:@pytest.mark.asyncioasync def test_observe_returns_elements(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -900,6 +925,22 @@ class TestSkyvernObserveMCP:assert len(result["data"]["elements"]) == 4assert result["data"]["element_count"] == 4+ @pytest.mark.asyncio+ async def test_observe_hint_qualifies_ref_lifetime_by_transport(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ page = _make_page()+ ctx = BrowserContext(mode="local")+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))++ result = await mcp_browser.skyvern_observe()++ hint = result["data"]["hint"].lower()+ for term in ("stdio", "stateless http", "selector", "intent"):+ assert term in hint+ assert "across calls in this browser session" not in hint+@pytest.mark.asyncioasync def test_default_observe_omits_values_from_output_and_registry(self,@@ -1745,16 +1786,33 @@ class TestSkyvernExecuteMCP:assert result["data"]["results"][1]["data"]["resolved_selector"] == "#region"@pytest.mark.asyncio- async def test_execute_unknown_ref_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:+ @pytest.mark.parametrize("stateless_http_mode", [False, True])+ async def test_execute_unknown_ref_error_is_transport_aware(+ self,+ monkeypatch: pytest.MonkeyPatch,+ stateless_http_mode: bool,+ ) -> None:page = _make_page()ctx = BrowserContext(mode="local")monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))- async with scoped_session(make_session_state(context=ctx)):- result = await mcp_browser.skyvern_execute(steps=[{"tool": "click", "params": {"ref": "e99"}}])+ previous_mode = session_manager.is_stateless_http_mode()+ try:+ session_manager.set_stateless_http_mode(stateless_http_mode)+ async with scoped_session(make_session_state(context=ctx)):+ result = await mcp_browser.skyvern_execute(steps=[{"tool": "click", "params": {"ref": "e99"}}])+ finally:+ session_manager.set_stateless_http_mode(previous_mode)assert result["ok"] is False- assert result["data"]["results"][0]["error"] == ("Unknown ref 'e99' — call observe first or check ref exists")+ error = result["data"]["results"][0]["error"]+ assert error.startswith("Unknown ref 'e99' — call observe first or check ref exists")+ if stateless_http_mode:+ assert "stateless HTTP mode" in error+ assert "do not resolve" in error+ assert "selector or intent" in error+ else:+ assert "stateless" not in error@pytest.mark.asyncioasync def test_execute_preserves_structured_direct_failure_error(self, monkeypatch: pytest.MonkeyPatch) -> None: