🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
Python aiai-scrapingautomationcrawlercrawlingcrawling-pythondatadata-extractionmcpmcp-serverplaywrightpythonscrapingselectorsstealthweb-scraperweb-scrapingweb-scraping-pythonwebscrapingxpath
feat(mcp): Add tool to write text
Karim shoair230ac0995e2c
diff --git a/agent-skill/Scrapling-Skill.zip b/agent-skill/Scrapling-Skill.zipindex 2bd2e83..a84ff27 100644Binary files a/agent-skill/Scrapling-Skill.zip and b/agent-skill/Scrapling-Skill.zip differdiff --git a/agent-skill/Scrapling-Skill/references/mcp-server.md b/agent-skill/Scrapling-Skill/references/mcp-server.mdindex 7c44fe5..3cdf2dd 100644--- a/agent-skill/Scrapling-Skill/references/mcp-server.md+++ b/agent-skill/Scrapling-Skill/references/mcp-server.md@@ -1,8 +1,8 @@# Scrapling MCP Server-The Scrapling MCP server exposes sixteen tools over the MCP protocol. It supports CSS-selector-based content narrowing (reducing tokens by extracting only relevant elements before returning results), three levels of scraping capability (plain HTTP, browser-rendered, and stealth/anti-bot bypass), persistent browser session management, mouse actions, and page screenshots returned as real image content blocks. Fetch tools come in two modes: one-shot tools (`browser_fetch_once`, `browser_fetch_many_once`, `browser_stealth_fetch_once`, `browser_stealth_fetch_many_once`) each launch and close their own browser, while `browser_fetch` and `session_make_request` work through sessions opened with `browser_open`/`open_request_session`.+The Scrapling MCP server exposes seventeen tools over the MCP protocol. It supports CSS-selector-based content narrowing (reducing tokens by extracting only relevant elements before returning results), three levels of scraping capability (plain HTTP, browser-rendered, and stealth/anti-bot bypass), persistent browser session management, mouse actions, text input, and page screenshots returned as real image content blocks. Fetch tools come in two modes: one-shot tools (`browser_fetch_once`, `browser_fetch_many_once`, `browser_stealth_fetch_once`, `browser_stealth_fetch_many_once`) each launch and close their own browser, while `browser_fetch` and `session_make_request` work through sessions opened with `browser_open`/`open_request_session`.-Fetch and HTTP request tools return a `ResponseModel` with fields: `status` (int), `content` (list of strings), `url` (str). Bulk tools return a list of these responses. The `browser_screenshot` tool returns a list of MCP content blocks: an `ImageContent` (the screenshot bytes) followed by a `TextContent` (the post-redirect URL). `browser_snapshot`, `browser_mouse_move`, and `browser_click` return plain text.+Fetch and HTTP request tools return a `ResponseModel` with fields: `status` (int), `content` (list of strings), `url` (str). Bulk tools return a list of these responses. The `browser_screenshot` tool returns a list of MCP content blocks: an `ImageContent` (the screenshot bytes) followed by a `TextContent` (the post-redirect URL). `browser_snapshot`, `browser_mouse_move`, `browser_click`, and `browser_type` return plain text.## Shadow DOM@@ -201,6 +201,26 @@ Invalid targets, unknown sessions, and missing, closed, or busy pages return anReturns plain text without an automatic snapshot. Use `browser_snapshot` to inspect the page afterward. A cancelled or timed-out click sends a button release before the page can be reused, even if it was still waiting for a target. This does not undo page actions. Do not repeat a failed click without checking the page state.+### `browser_type` -- Enter text by selector or snapshot reference++Enters text on the existing page in a dynamic or stealthy browser session. Call `browser_fetch` first. Supply exactly one target: `selector` or `ref`.++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `session_id` | str | required | ID of an open browser session |+| `text` | str | required | Text to enter; an empty string clears the field in the default mode |+| `selector` | str or null | null | Nonempty Playwright selector matching exactly one element |+| `ref` | str or null | null | Nonempty reference from the current `browser_snapshot`, such as `e2` |+| `slowly` | bool | false | Type one character at a time at the current caret or selection without clearing first |+| `submit` | bool | false | Press Enter on the same target after successful text entry |+| `timeout` | number | 30000 | Finite nonnegative timeout in milliseconds per native operation; 0 disables the limit |++By default, Playwright's locator fill replaces the contents of an input, textarea, or contenteditable element. With `slowly=true`, locator press_sequentially sends key events for each character at the current caret or selection, without first clearing existing text. With `submit=true`, locator press sends Enter only after text entry succeeds. The timeout applies separately to text entry and the optional Enter press.++Pass the exact snapshot reference value, such as `ref="e2"`. Take a new snapshot if the reference is stale. Invalid targets, unknown or HTTP sessions, and missing, closed, or busy pages return an error.++Returns `Text entered.` as plain text without echoing the text or taking a snapshot. Errors are not retried, and the page reservation is released after success, failure, or cancellation. Entry or submission may have already changed the page when an error occurs; use `browser_snapshot` to check before retrying.+### `session_make_request` -- HTTP request through an open requests sessionMakes an HTTP request (any method) through a session opened with `open_request_session`, reusing its cookies, connections, and browser fingerprint across calls. Same parameters as `make_request` plus a required `session_id`, minus the session-level `impersonate`, `proxy`, and `proxy_auth`. Raises on a browser session.@@ -256,6 +276,7 @@ Requires an open browser session. Call `browser_open` first, then pass the `sess| Read the current page's AI ARIA snapshot | `browser_snapshot` with `session_id` || Move the mouse on the current page | `browser_mouse_move` with `session_id` || Click by selector, snapshot ref, or coordinates | `browser_click` with `session_id` |+| Enter text by selector or snapshot ref | `browser_type` with `session_id` |Start with `make_request` (fastest, lowest resource cost). Escalate to `browser_fetch_once` if content requires JS rendering. Escalate to `browser_stealth_fetch_once` only if blocked. For multiple pages from the same site, use a persistent session to avoid browser launch overhead.@@ -346,7 +367,7 @@ The MCP server name when registering with a client is `ScraplingServer`. The com## Connecting to remote browsers-`browser_open` doesn't have to launch a browser locally. Pass a `cdp_url` and it connects to an already-running browser through the Chrome DevTools Protocol, whether that browser is on the same machine, another host, or a managed browser provider. Both session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_click`, and `browser_screenshot` as usual.+`browser_open` doesn't have to launch a browser locally. Pass a `cdp_url` and it connects to an already-running browser through the Chrome DevTools Protocol, whether that browser is on the same machine, another host, or a managed browser provider. Both session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_click`, `browser_type`, and `browser_screenshot` as usual.The URL can be a WebSocket endpoint (`ws://`/`wss://`), which is what managed browser providers hand out, or the HTTP endpoint of a browser started with `--remote-debugging-port=9222`, reached as `cdp_url="http://localhost:9222"`.diff --git a/docs/ai/mcp-server.md b/docs/ai/mcp-server.mdindex 5763dcc..7b97eb5 100644--- a/docs/ai/mcp-server.md+++ b/docs/ai/mcp-server.md@@ -6,7 +6,7 @@ The **Scrapling MCP Server** is a new feature that brings Scrapling's powerful W## Features-The Scrapling MCP Server provides sixteen tools for web scraping and browser interaction, split into two modes: one-shot tools that each launch and close their own browser/client, and session tools that open a browser or an HTTP session once and then work through it.+The Scrapling MCP Server provides seventeen tools for web scraping and browser interaction, split into two modes: one-shot tools that each launch and close their own browser/client, and session tools that open a browser or an HTTP session once and then work through it.### One-shot tools@@ -46,6 +46,10 @@ The Scrapling MCP Server provides sixteen tools for web scraping and browser int- **`browser_mouse_move`**: Move the browser's mouse to reveal hover menus, tooltips, and other content that appears on hover. Target elements through selectors or snapshot references, with automatic waiting and scrolling into view. Coordinate moves support multiple steps for controls that react as the pointer moves.- **`browser_click`**: Click buttons, follow links, and use other page controls through selectors, snapshot references, or page coordinates. Supports left, right, and middle clicks, plus double-clicks.+#### Text Input++- **`browser_type`**: Fill search boxes, login fields, text areas, and other editable content through selectors or snapshot references. Replace or clear existing text, or type one character at a time for fields that react to key events. Can also press Enter to run a search or submit a form.+### Shadow DOMSet `pierce_shadow=true` on `browser_fetch_once`, `browser_fetch_many_once`, `browser_stealth_fetch_once`, `browser_stealth_fetch_many_once`, or `browser_fetch` to include open Shadow DOM content. It defaults to `false`. For persistent sessions, pass it on each `browser_fetch` call. See [Shadow DOM](../fetching/dynamic.md#shadow-dom) for selector examples and limits.@@ -205,7 +209,7 @@ You can also set the `SCRAPLING_EXECUTABLE_PATH` environment variable before sta```Open a stealthy browser session on wss://cdp.provider.example/session/abc123, then use it to scrape the product details from https://shop.example.com. Close the session when you're done.```-Both browser session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_click`, and `browser_screenshot` as usual.+Both browser session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_click`, `browser_type`, and `browser_screenshot` as usual.The URL can be a WebSocket endpoint (`ws://`/`wss://`), which is what managed browser providers hand out, or the HTTP endpoint of a browser you started yourself with the remote debugging port enabled:```commandlinediff --git a/docs/api-reference/mcp-server.md b/docs/api-reference/mcp-server.mdindex 36ce223..90d7bcc 100644--- a/docs/api-reference/mcp-server.md+++ b/docs/api-reference/mcp-server.md@@ -5,7 +5,7 @@ search:# MCP Server API Reference-The **Scrapling MCP Server** provides sixteen tools for web scraping and browser interaction through the Model Context Protocol (MCP). This server integrates Scrapling's capabilities directly into AI chatbots and agents, allowing conversational web scraping with advanced anti-bot bypass features.+The **Scrapling MCP Server** provides seventeen tools for web scraping and browser interaction through the Model Context Protocol (MCP). This server integrates Scrapling's capabilities directly into AI chatbots and agents, allowing conversational web scraping with advanced anti-bot bypass features.You can start the MCP server by running:@@ -30,7 +30,7 @@ server = ScraplingMCPServer(executable_path="/path/to/chromium")## Response Model-The standardized response structure returned by the fetch and HTTP request tools. Bulk tools return a list of these responses. Session management tools use the models below, `browser_screenshot` returns image and text content blocks, and `browser_snapshot`, `browser_mouse_move`, and `browser_click` return plain text.+The standardized response structure returned by the fetch and HTTP request tools. Bulk tools return a list of these responses. Session management tools use the models below, `browser_screenshot` returns image and text content blocks, and `browser_snapshot`, `browser_mouse_move`, `browser_click`, and `browser_type` return plain text.## ::: scrapling.core.ai.ResponseModelhandler: python@@ -59,6 +59,7 @@ The main MCP server class that provides all web scraping tools:- **`browser_snapshot`**: Inspect the current page without reloading it. Structured text includes element roles, names, references, positions, and sizes to help the AI target page controls.- **`browser_mouse_move`**: Reveal hover menus and tooltips with the browser's mouse. Target elements through selectors or snapshot references, with automatic waiting and scrolling into view, or use coordinates with movement in multiple steps.- **`browser_click`**: Click buttons, links, and other controls using selectors, snapshot references, or page coordinates. Supports left, right, and middle clicks, plus double-clicks.+- **`browser_type`**: Fill search boxes, login fields, text areas, and other editable content through selectors or snapshot references. Supports replacing or clearing text, typing one character at a time for key events, and pressing Enter after entry.- **`browser_fetch`**: Fetch a page through an open browser session and extract HTML, Markdown, text, or a structured snapshot. Snapshots can cover the whole page or a chosen element and include element references, positions, and sizes for later interaction.## ::: scrapling.core.ai.ScraplingMCPServerdiff --git a/scrapling/core/ai.py b/scrapling/core/ai.pyindex 734af38..f0ee257 100644--- a/scrapling/core/ai.py+++ b/scrapling/core/ai.py@@ -101,7 +101,7 @@ def _session_settings(session: Any) -> Dict[str, Any]:_FETCH_TOOL_ANNOTATIONS = ToolAnnotations(read_only_hint=True, open_world_hint=True)_SESSION_TOOL_ANNOTATIONS = ToolAnnotations(read_only_hint=False, destructive_hint=False, open_world_hint=True)_LIST_TOOL_ANNOTATIONS = ToolAnnotations(read_only_hint=True, open_world_hint=False)-_MOUSE_TOOL_ANNOTATIONS = ToolAnnotations(+_INPUT_TOOL_ANNOTATIONS = ToolAnnotations(read_only_hint=False, destructive_hint=True, idempotent_hint=False, open_world_hint=True)@@ -482,6 +482,36 @@ class ScraplingMCPServer:raisereturn "Click sent."+ async def browser_type(+ self,+ session_id: str,+ text: str,+ selector: Optional[NonEmptyString] = None,+ ref: Optional[NonEmptyString] = None,+ slowly: bool = False,+ submit: bool = False,+ timeout: NonNegativeFiniteFloat = 30000,+ ) -> str:+ """Enter text using exactly one selector or snapshot ref; return plain text.+ Replaces existing text by default; slowly types without clearing first.++ :param session_id: ID from `browser_open`; call `browser_fetch` first.+ :param text: Text to enter; empty clears the field in default mode.+ :param selector: Playwright selector matching exactly one element.+ :param ref: Element reference from the current snapshot, e.g. "e2".+ :param slowly: Type character by character at the current caret or selection, triggering key events.+ :param submit: Press Enter on the target after successful text entry.+ :param timeout: Limit per operation in milliseconds; 0 disables it.+ """+ if (selector is None) == (ref is None):+ raise ValueError("Provide exactly one target: 'selector' or 'ref'.")+ with self._browser_page(session_id) as (_, page):+ locator = page.locator(selector if selector is not None else f"aria-ref={ref}")+ await (locator.press_sequentially if slowly else locator.fill)(text, timeout=timeout)+ if submit:+ await locator.press("Enter", timeout=timeout)+ return "Text entered."+async def browser_screenshot(self,url: str,@@ -1210,6 +1240,7 @@ class ScraplingMCPServer:10. The user can pass a CDP URL to connect to a remote browser session through the `browser_open` tool, then use it with the session tools.11. Set `extraction_type="snapshot"` on `browser_fetch` to get an AI ARIA snapshot with element references and bounding boxes in its content field. Use `css_selector` to snapshot one element, or omit it for the whole page. `main_content_only` and `pierce_shadow` do not filter snapshots. Use `browser_snapshot` to read the current page without navigating; it returns plain text with boxes by default. Set `depth` to limit the tree or `boxes=False` to omit boxes.12. Use `browser_mouse_move` to move the mouse on the current page. Use `browser_click` with exactly one target: `selector`, `ref` from the current snapshot, or both `x` and `y` viewport CSS coordinates. Selector/ref clicks use Playwright's normal waiting and scrolling; coordinate clicks do not scroll or wait for navigation. Get coordinates from `browser_snapshot` and inspect the page afterward with `browser_snapshot`. Clicks can change website data. Do not repeat a click without checking the page state.+13. Use `browser_snapshot` to inspect the page after `browser_type`. Typing or submission may partly complete before an error; check the page before repeating the action.""",}if self._auth_token:@@ -1306,14 +1337,21 @@ class ScraplingMCPServer:title="Move mouse",description=self.browser_mouse_move.__doc__,structured_output=False,- annotations=_MOUSE_TOOL_ANNOTATIONS,+ annotations=_INPUT_TOOL_ANNOTATIONS,)server.add_tool(self.browser_click,title="Click",description=self.browser_click.__doc__,structured_output=False,- annotations=_MOUSE_TOOL_ANNOTATIONS,+ annotations=_INPUT_TOOL_ANNOTATIONS,+ )+ server.add_tool(+ self.browser_type,+ title="Type text",+ description=self.browser_type.__doc__,+ structured_output=False,+ annotations=_INPUT_TOOL_ANNOTATIONS,)# Screenshot tool (returns image + url content blocks, not structured JSON)server.add_tool(diff --git a/tests/ai/test_ai_mcp.py b/tests/ai/test_ai_mcp.pyindex 5d75183..f9e59fe 100644--- a/tests/ai/test_ai_mcp.py+++ b/tests/ai/test_ai_mcp.py@@ -982,7 +982,7 @@ class TestServerToolRegistration:@pytest.mark.asyncioasync def test_tools_are_listed_with_expected_schemas(self):- """All 16 tools are advertised, with plain content for screenshots, snapshots, and mouse actions"""+ """All 17 tools are advertised, with plain content for screenshots, snapshots, and input actions"""server = ScraplingMCPServer()._build_server("127.0.0.1", 8000)async with Client(server) as client:assert client.instructions@@ -1001,11 +1001,12 @@ class TestServerToolRegistration:result = await client.call_tool(name, {})assert result.is_error- assert len(tools) == 16+ assert len(tools) == 17assert tools["browser_screenshot"].output_schema is Noneassert tools["browser_snapshot"].output_schema is Noneassert tools["browser_mouse_move"].output_schema is Noneassert tools["browser_click"].output_schema is None+ assert tools["browser_type"].output_schema is Noneassert {"session_snapshot","open_session",@@ -1027,7 +1028,8 @@ class TestServerToolRegistration:assert all(tool.output_schema is not Nonefor name, tool in tools.items()- if name not in ("browser_screenshot", "browser_snapshot", "browser_mouse_move", "browser_click")+ if name+ not in ("browser_screenshot", "browser_snapshot", "browser_mouse_move", "browser_click", "browser_type"))@pytest.mark.asyncio@@ -1092,7 +1094,7 @@ class TestServerToolRegistration:assert result.ttl_ms == 3_600_000 and result.cache_scope == "public"annotations = {tool.name: tool.annotations for tool in result.tools if tool.annotations is not None}- assert len(annotations) == 16+ assert len(annotations) == 17for name in ("make_request","bulk_get",@@ -1113,7 +1115,7 @@ class TestServerToolRegistration:assert annotations[name].open_world_hint is Trueassert annotations["list_sessions"].read_only_hint is Trueassert annotations["list_sessions"].open_world_hint is False- for name in ("browser_mouse_move", "browser_click"):+ for name in ("browser_mouse_move", "browser_click", "browser_type"):assert annotations[name].read_only_hint is Falseassert annotations[name].destructive_hint is Trueassert annotations[name].idempotent_hint is Falsediff --git a/tests/ai/test_browser_type.py b/tests/ai/test_browser_type.pynew file mode 100644index 0000000..20b2973--- /dev/null+++ b/tests/ai/test_browser_type.py@@ -0,0 +1,353 @@+import asyncio+from contextlib import asynccontextmanager+from json import loads+from os import getenv+from re import search+from unittest.mock import AsyncMock, Mock, call++import pytest+from anyio import CancelScope+from mcp.client import Client+from mcp.types import TextContent+from patchright.async_api import TimeoutError as PatchrightTimeoutError+from playwright.async_api import TimeoutError as PlaywrightTimeoutError+from pydantic import ValidationError++from scrapling.core.ai import ScraplingMCPServer, SessionType, _SessionEntry+from scrapling.core._types import Any, AsyncGenerator+from scrapling.engines._browsers._base import AsyncSession+++HTML = """<!DOCTYPE html><html><body>+<form><label>Name<input id="name" name="name" value="initial"></label><button>Save</button></form>+<textarea id="notes">initial notes</textarea><div id="editor" contenteditable="true">initial editor</div>+<output id="submitted" data-count="0"></output><textarea id="events" hidden>[]</textarea><script>+document.querySelector('form').addEventListener('submit', event => {+ event.preventDefault();+ const output = document.querySelector('#submitted');+ output.textContent = new FormData(event.target).get('name');+ output.dataset.count = Number(output.dataset.count) + 1;+});+for (const type of ['keydown', 'keyup', 'input']) {+ document.addEventListener(type, event => {+ const events = document.querySelector('#events');+ events.value = JSON.stringify([...JSON.parse(events.value),+ {type, key: event.key, trusted: event.isTrusted, target: event.target.id}]);+ });+}+</script></body></html>"""+++def _server(session_type: SessionType = "dynamic") -> tuple[ScraplingMCPServer, AsyncSession, Mock]:+ server = ScraplingMCPServer()+ session = AsyncSession()+ session._is_alive = True+ page = Mock()+ page.is_closed.return_value = False+ for method in ("fill", "press_sequentially", "press"):+ setattr(page.locator.return_value, method, AsyncMock())+ session.page_pool.add_page(page).mark_ready()+ server._sessions["browser"] = _SessionEntry(session, session_type)+ return server, session, page+++async def test_browser_type_schema() -> None:+ async with Client(ScraplingMCPServer()._build_server("127.0.0.1", 8000)) as client:+ tool = next(tool for tool in (await client.list_tools()).tools if tool.name == "browser_type")+ assert set(tool.input_schema["properties"]) == {+ "session_id",+ "text",+ "selector",+ "ref",+ "slowly",+ "submit",+ "timeout",+ }+ assert tool.input_schema["required"] == ["session_id", "text"]+ props = tool.input_schema["properties"]+ assert props["text"]["type"] == "string"+ assert props["slowly"]["default"] is props["submit"]["default"] is False+ assert props["timeout"]["default"] == 30000+ assert props["timeout"]["minimum"] == 0+++ "target, options, method, timeout",+ [+ ({"selector": "#name"}, {}, "fill", 30000),+ ({"ref": "e4"}, {"submit": True, "timeout": 0}, "fill", 0),+ ({"selector": "#name"}, {"slowly": True, "timeout": 400}, "press_sequentially", 400),+ ({"ref": "e4"}, {"slowly": True, "submit": True}, "press_sequentially", 30000),+ ],+)+async def test_browser_type_forwards_options_and_submits_after_typing(+ target: dict[str, Any], options: dict[str, Any], method: str, timeout: int+) -> None:+ server, session, page = _server()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool(+ "browser_type", {"session_id": "browser", "text": "private text", **target, **options}+ )+ assert not result.is_error+ assert result.structured_content is None+ assert result.content == [TextContent(type="text", text="Text entered.")]+ page.locator.assert_called_once_with("#name" if "selector" in target else "aria-ref=e4")+ expected = [getattr(call, method)("private text", timeout=timeout)]+ if options.get("submit"):+ expected.append(call.press("Enter", timeout=timeout))+ assert page.locator.return_value.mock_calls == expected+ assert session.page_pool.pages[0].state == "ready"+ page.goto.assert_not_called()+ page.aria_snapshot.assert_not_called()+ page.set_default_timeout.assert_not_called()+++ "values",+ [+ {"selector": None},+ {"selector": ""},+ {"selector": None, "ref": ""},+ {"ref": "e1"},+ {"text": None},+ {"text": ["invalid"]},+ {"slowly": "invalid"},+ {"submit": "invalid"},+ {"timeout": -1},+ ],+)+async def test_browser_type_invalid_input_does_not_reserve_page(values: dict[str, Any]) -> None:+ server, session, page = _server()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool(+ "browser_type", {"session_id": "browser", "text": "value", "selector": "#name", **values}+ )+ assert result.is_error+ page.is_closed.assert_not_called()+ page.locator.assert_not_called()+ assert session.page_pool.pages[0].state == "ready"++[email protected]("timeout", [float("nan"), float("inf"), float("-inf")])+def test_browser_type_rejects_nonfinite_timeout(timeout: float) -> None:+ tool = ScraplingMCPServer()._build_server("127.0.0.1", 8000)._tool_manager.get_tool("browser_type")+ assert tool is not None+ with pytest.raises(ValidationError):+ tool.fn_metadata.arg_model.model_validate(+ {"session_id": "browser", "selector": "#name", "text": "value", "timeout": timeout}+ )+++ "state, message",+ [+ ("missing", "not found"),+ ("dead", "no longer alive"),+ ("static", "'static'"),+ ("empty", "browser_fetch"),+ ("busy", "busy"),+ ("closed", "closed"),+ ],+)+async def test_browser_type_session_errors_reach_mcp(state: str, message: str) -> None:+ server, session, page = _server("static" if state == "static" else "dynamic")+ if state == "missing":+ server._sessions.clear()+ elif state == "dead":+ session._is_alive = False+ elif state == "empty":+ session.page_pool.clear()+ elif state == "busy":+ session.page_pool.pages[0].mark_busy()+ elif state == "closed":+ page.is_closed.return_value = True+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_type", {"session_id": "browser", "selector": "#name", "text": "value"})+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert message in result.content[0].text+ page.locator.assert_not_called()+ if state == "closed":+ assert session.page_pool.pages_count == 0+ elif state == "busy":+ assert session.page_pool.pages[0].state == "busy"+++ "session_type, error", [("dynamic", PlaywrightTimeoutError), ("stealthy", PatchrightTimeoutError)]+)[email protected]("method", ["fill", "press_sequentially", "press"])+async def test_browser_type_timeout_does_not_retry_or_submit_failed_input(+ session_type: SessionType, error: type[Exception], method: str+) -> None:+ server, session, page = _server(session_type)+ action = getattr(page.locator.return_value, method)+ action.side_effect = error("typing timed out")+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool(+ "browser_type",+ {+ "session_id": "browser",+ "selector": "#name",+ "text": "value",+ "slowly": method == "press_sequentially",+ "submit": True,+ },+ )+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert "typing timed out" in result.content[0].text+ action.assert_awaited_once()+ if method != "press":+ page.locator.return_value.press.assert_not_awaited()+ else:+ page.locator.return_value.fill.assert_awaited_once()+ assert session.page_pool.pages[0].state == "ready"+ action.side_effect = None+ assert await server.browser_type("browser", "next", selector="#name") == "Text entered."++[email protected]("method", ["fill", "press_sequentially", "press"])[email protected]("cancel_mode", ["task", "scope"])+async def test_browser_type_reserves_page_until_cancelled(method: str, cancel_mode: str) -> None:+ server, session, page = _server()+ entered = asyncio.Event()+ scope = CancelScope()++ async def pending(*args: Any, **kwargs: Any) -> None:+ entered.set()+ await asyncio.Event().wait()++ async def type_text() -> None:+ with scope:+ await server.browser_type(+ "browser", "value", selector="#name", slowly=method == "press_sequentially", submit=True+ )++ getattr(page.locator.return_value, method).side_effect = pending+ task = asyncio.create_task(type_text())+ try:+ await asyncio.wait_for(entered.wait(), 5)+ assert session.page_pool.pages[0].state == "busy"+ with pytest.raises(RuntimeError, match="busy"):+ await server.browser_type("browser", "other", selector="#name")+ finally:+ scope.cancel() if cancel_mode == "scope" else task.cancel()+ if cancel_mode == "scope":+ await asyncio.wait_for(task, 5)+ assert scope.cancelled_caught+ else:+ with pytest.raises(asyncio.CancelledError):+ await task+ assert session.page_pool.pages[0].state == "ready"+ if method != "press":+ page.locator.return_value.press.assert_not_awaited()+++@asynccontextmanager+async def _browser(session_type: SessionType) -> AsyncGenerator[tuple[ScraplingMCPServer, Client, Any, Any], None]:+ server = ScraplingMCPServer(executable_path=getenv("SCRAPLING_EXECUTABLE_PATH"))++ async def serve(route: Any) -> None:+ await route.fulfill(status=200, content_type="text/html", body=HTML)++ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ opened = await client.call_tool("browser_open", {"session_type": session_type, "session_id": "browser"})+ assert not opened.is_error+ try:+ session = server._sessions["browser"].session+ await session.context.route("**/*", serve)+ fetched = await client.call_tool(+ "browser_fetch", {"session_id": "browser", "url": "https://type.test/", "google_search": False}+ )+ assert not fetched.is_error+ yield server, client, session, session.page_pool.pages[0].page+ finally:+ closed = await client.call_tool("close_session", {"session_id": "browser"})+ assert not closed.is_error++[email protected]("session_type", ["dynamic", "stealthy"])+async def test_browser_type_live_fill_selectors_refs_and_editable_fields(session_type: SessionType) -> None:+ async with _browser(session_type) as browser:+ server, client, session, page = browser+ snapshot = await server.browser_snapshot("browser")+ match = search(r'textbox "Name".*?\[ref=([^\]]+)\]', snapshot)+ assert match is not None+ for target, text, element in (+ ({"selector": "#name"}, "new α value", "#name"),+ ({"ref": match[1]}, "", "#name"),+ ({"selector": 'xpath=//textarea[@id="notes"]'}, "line one\nline two", "#notes"),+ ({"selector": "#editor"}, "edited content", "#editor"),+ ):+ result = await client.call_tool("browser_type", {"session_id": "browser", "text": text, **target})+ assert not result.is_error+ value = (+ await page.locator(element).inner_text()+ if element == "#editor"+ else await page.locator(element).input_value()+ )+ assert value == text+ assert session.page_pool.pages[0].state == "ready"+ events = loads(await page.locator("#events").input_value())+ assert {event["target"] for event in events if event["type"] == "input"} == {"name", "notes", "editor"}+ assert all(event["trusted"] for event in events)+ assert await page.locator("#submitted").get_attribute("data-count") == "0"++[email protected]("session_type", ["dynamic", "stealthy"])+async def test_browser_type_live_sequential_keys_and_submit(session_type: SessionType) -> None:+ async with _browser(session_type) as browser:+ _, client, session, page = browser+ for text, slowly, expected, count in (("prefix", False, "prefix", 1), ("abc", True, "prefixabc", 2)):+ await page.locator("#events").evaluate("element => element.value = '[]'")+ result = await client.call_tool(+ "browser_type",+ {"session_id": "browser", "selector": "#name", "text": text, "slowly": slowly, "submit": True},+ )+ assert not result.is_error+ assert await page.locator("#name").input_value() == expected+ assert await page.locator("#submitted").inner_text() == expected+ assert await page.locator("#submitted").get_attribute("data-count") == str(count)+ events = loads(await page.locator("#events").input_value())+ assert all(event["trusted"] and event["target"] == "name" for event in events)+ assert [event["key"] for event in events if event["type"] == "keydown"] == (+ ["a", "b", "c", "Enter"] if slowly else ["Enter"]+ )+ assert [event["key"] for event in events if event["type"] == "keyup"] == (+ ["a", "b", "c", "Enter"] if slowly else ["Enter"]+ )+ assert next(index for index, event in enumerate(events) if event.get("key") == "Enter") > max(+ index for index, event in enumerate(events) if event["type"] == "input"+ )+ assert session.page_pool.pages[0].state == "ready"++[email protected]("session_type", ["dynamic", "stealthy"])+async def test_browser_type_live_bad_targets_do_not_submit(session_type: SessionType) -> None:+ async with _browser(session_type) as browser:+ server, client, session, page = browser+ match = search(r'textbox "Name".*?\[ref=([^\]]+)\]', await server.browser_snapshot("browser"))+ assert match is not None+ await page.locator("#name").evaluate("element => element.remove()")+ for target in ({"selector": "textarea"}, {"selector": "#missing"}, {"ref": match[1]}):+ result = await client.call_tool(+ "browser_type", {"session_id": "browser", "text": "value", "submit": True, "timeout": 100, **target}+ )+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert ("strict mode violation" if target.get("selector") == "textarea" else "Timeout") in result.content[+ 0+ ].text+ assert loads(await page.locator("#events").input_value()) == []+ assert await page.locator("#submitted").get_attribute("data-count") == "0"+ assert session.page_pool.pages[0].state == "ready"