🕷️ 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)!: Replace browser type with fields filling tool to save tokens
Karim shoair427f00ffea89
diff --git a/agent-skill/Scrapling-Skill.zip b/agent-skill/Scrapling-Skill.zipindex 39d45e1..9b2ca83 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 9a82475..a07d1ef 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 twenty 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, batch field filling, keyboard shortcuts, 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 nineteen 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, batch field filling, keyboard shortcuts, 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`, `browser_mouse_wheel`, `browser_click`, `browser_type`, `browser_fill_fields`, and `browser_press_key` 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_mouse_wheel`, `browser_click`, `browser_fill_fields`, and `browser_press_key` return plain text.## Shadow DOM@@ -215,27 +215,7 @@ 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.--### `browser_fill_fields` -- Fill multiple page fields in order+### `browser_fill_fields` -- Fill one or more page fields in orderFills fields anywhere on the existing page in a dynamic or stealthy browser session. Fields do not need a `<form>` parent. Call `browser_fetch` first. Each field needs exactly one nonempty `selector` or snapshot `ref`, plus its `type` and `value`.@@ -244,24 +224,26 @@ Fills fields anywhere on the existing page in a dynamic or stealthy browser sess| `session_id` | str | required | ID of an open browser session || `fields` | list[object] | required | Nonempty ordered list of field targets, types, and values || `timeout` | number | 30000 | Finite nonnegative timeout in milliseconds per operation; 0 disables the limit |-| `slowly` | bool | false | Replace text with fresh random delays: 50-150 ms per character, 100-300 ms between fields |+| `slowly` | bool | false | Add fresh random delays: 50-150 ms per character, 100-300 ms between fields || Field `type` | `value` | Behavior ||--------------|---------|----------|-| `textbox` | str | Replace text in an input, textarea, or contenteditable element; an empty string clears it |+| `textbox` | str | By default, replace text in an input, textarea, or contenteditable element; an empty string clears it || `checkbox` | bool | `true` checks the box; `false` unchecks it || `radio` | `true` | Select the radio option; `false` is not supported || `combobox` | str or list[str] | Select native `<select>` options by label; use a list for multiple selections or `[]` to clear |-Selectors must match exactly one element. Use current snapshot references, such as `"e2"`. MCP validates all field types and values before execution, and target combinations are checked before reserving the page. One page stays reserved for the whole batch. Native locator `fill`, `set_checked`, and `select_option(label=...)` run in list order with their normal waiting. Combobox fields support native `<select>` elements, not custom dropdown widgets.+Textbox fields also accept `clear` (bool, default `true`). With `clear=false`, native `press_sequentially` types at the current caret or selection without clearing first, even when `slowly=false`. An empty value preserves existing content when `clear=false`; otherwise it clears the field.++Selectors must match exactly one element. Use current snapshot references, such as `"e2"`. MCP validates all field types and values before execution, and target combinations are checked before reserving the page. One page stays reserved for the whole batch. Native locator `fill`, `press_sequentially`, `set_checked`, and `select_option(label=...)` run in list order. Combobox fields support native `<select>` elements, not custom dropdown widgets.-With `slowly=true`, text fields are cleared before native `press_sequentially` types each character with a fresh random delay of 50-150 ms. Empty text only clears the field. All field types get a fresh random pause of 100-300 ms before the next field, with no pause before the first or after the last. The timeout applies separately to each native action, including clearing and each character press; pauses between fields are outside it.+With `slowly=true`, native `press_sequentially` types each character with a fresh random delay of 50-150 ms, clearing first unless the field has `clear=false`. All field types get a fresh random pause of 100-300 ms before the next field, with no pause before the first or after the last. The timeout applies separately to each native action, including clearing and each character press; pauses between fields are outside it.-Returns `Fields filled.` as plain text without echoing values, submitting forms, or taking a snapshot. An error or cancellation stops the remaining fields; completed changes stay and are not retried. The page reservation is released afterward. Use `browser_snapshot` to check the page before retrying or submitting a form. Unknown or HTTP sessions and missing, closed, or busy pages return an error.+Returns `Fields filled.` as plain text without echoing values, submitting forms, or taking a snapshot. An error or cancellation stops the remaining fields; completed changes stay and are not retried. The page reservation is released afterward. Use `browser_snapshot` to check the page before retrying. To submit with Enter, use `browser_press_key` with `keys=["Enter"]`; first focus the intended control with `browser_click` if needed, since the batch may end on another field. Unknown or HTTP sessions and missing, closed, or busy pages return an error.### `browser_press_key` -- Chain keys and shortcuts at the current focus-Presses each item in order through native `page.keyboard.press` on the existing page in a dynamic or stealthy browser session. The page stays reserved for the full sequence. Call `browser_fetch` first. Use `browser_click` or `browser_type` to focus a control before pressing when needed; later presses follow any focus changes caused by earlier ones.+Presses each item in order through native `page.keyboard.press` on the existing page in a dynamic or stealthy browser session. The page stays reserved for the full sequence. Call `browser_fetch` first. Use `browser_click` to focus a control before pressing when needed; later presses follow any focus changes caused by earlier ones.| Parameter | Type | Default | Description ||-----------|------|---------|-------------|@@ -328,8 +310,7 @@ Requires an open browser session. Call `browser_open` first, then pass the `sess| Move the mouse on the current page | `browser_mouse_move` with `session_id` || Scroll a page or nested panel | `browser_mouse_wheel` 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` |-| Fill several page fields in order | `browser_fill_fields` with `session_id` |+| Fill one or more page fields in order | `browser_fill_fields` with `session_id` || Chain keys or keyboard shortcuts | `browser_press_key` 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.@@ -421,7 +402,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_mouse_wheel`, `browser_click`, `browser_type`, `browser_fill_fields`, `browser_press_key`, 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_mouse_wheel`, `browser_click`, `browser_fill_fields`, `browser_press_key`, 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 380d649..0613447 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 twenty 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 nineteen 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@@ -49,8 +49,7 @@ The Scrapling MCP Server provides twenty tools for web scraping and browser inte#### Text Input and Keyboard-- **`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.-- **`browser_fill_fields`**: Fill multiple fields anywhere on the page in one call, including text, checkboxes, radio buttons, and native dropdowns. Target fields through selectors or snapshot references, waiting for each field to be ready. Supports clearing text, checking or unchecking boxes, and choosing one or more dropdown options by their visible labels. Slow mode types text one character at a time with random pauses between characters and fields.+- **`browser_fill_fields`**: Fill one or more fields anywhere on the page in one call, including text, checkboxes, radio buttons, and native dropdowns. Target fields through selectors or snapshot references. Replace or clear text, or type at the current caret without clearing existing content. Supports checking or unchecking boxes and choosing one or more dropdown options by their visible labels. Slow mode types text one character at a time with random pauses between characters and fields.- **`browser_press_key`**: Chain keys and shortcuts on the current page to move between fields, submit forms, or dismiss menus in one call. Supports actions such as selecting all text and then deleting it, using the browser's current focus for each press.### Shadow DOM@@ -212,7 +211,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_mouse_wheel`, `browser_click`, `browser_type`, `browser_fill_fields`, `browser_press_key`, 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_mouse_wheel`, `browser_click`, `browser_fill_fields`, `browser_press_key`, 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 085d43b..9b6e405 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 twenty 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 nineteen 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`, `browser_mouse_wheel`, `browser_click`, `browser_type`, `browser_fill_fields`, and `browser_press_key` 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_mouse_wheel`, `browser_click`, `browser_fill_fields`, and `browser_press_key` return plain text.## ::: scrapling.core.ai.ResponseModelhandler: python@@ -60,8 +60,7 @@ The main MCP server class that provides all web scraping tools:- **`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_mouse_wheel`**: Scroll pages and nested panels vertically or horizontally with native mouse wheel events. Works at the current pointer position, so mouse movement can choose the scrollable area.- **`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_fill_fields`**: Fill text fields, check or uncheck boxes, select radio buttons, and choose one or more native dropdown options by visible labels in one call. Targets fields anywhere on the page through selectors or snapshot references and waits for each field to be ready. Slow mode types text one character at a time with random pauses between characters and fields.+- **`browser_fill_fields`**: Fill text fields, check or uncheck boxes, select radio buttons, and choose one or more native dropdown options by visible labels in one call. Targets one or more fields anywhere on the page through selectors or snapshot references. Replace or clear text, or type at the current caret without clearing existing content. Slow mode types text one character at a time with random pauses between characters and fields.- **`browser_press_key`**: Chain keys and shortcuts in one call to move between fields, submit forms, dismiss menus, or select and delete text. Each press uses the browser's current focus.- **`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.diff --git a/scrapling/core/_types.py b/scrapling/core/_types.pyindex cd026e7..ea589e9 100644--- a/scrapling/core/_types.py+++ b/scrapling/core/_types.py@@ -32,7 +32,7 @@ from typing import (Coroutine,SupportsIndex,)-from typing_extensions import Self, Unpack, TypedDict+from typing_extensions import Self, Unpack, TypedDict, NotRequired# Proxy can be a string URL or a dict (Playwright format: {"server": "...", "username": "...", "password": "..."})ProxyType = Union[str, Dict[str, str]]diff --git a/scrapling/core/ai.py b/scrapling/core/ai.pyindex 4c76aaf..1a6cead 100644--- a/scrapling/core/ai.py+++ b/scrapling/core/ai.py@@ -38,6 +38,7 @@ from scrapling.core._types import (Mapping,Dict,TypedDict,+ NotRequired,List,Any,Annotated,@@ -116,6 +117,9 @@ class _FormTarget(TypedDict, total=False):class _TextFormField(_FormTarget):type: Literal["textbox"]value: str+ clear: NotRequired[+ Annotated[bool, Field(default=True, description="False types at the current caret or selection.")]+ ]class _CheckboxFormField(_FormTarget):@@ -530,36 +534,6 @@ 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_press_key(self, session_id: str, keys: Annotated[List[NonEmptyString], Field(min_length=1)]) -> str:@@ -585,7 +559,7 @@ class ScraplingMCPServer::param session_id: ID from `browser_open`; call `browser_fetch` first.:param fields: Ordered field values; each needs exactly one selector or snapshot ref.:param timeout: Limit per operation in milliseconds; 0 disables it.- :param slowly: Replace text with random pauses: 50-150 ms per character, 100-300 ms between fields.+ :param slowly: Type with random pauses: 50-150 ms per character, 100-300 ms between fields."""if any((item.get("selector") is None) == (item.get("ref") is None) for item in fields):raise ValueError("Each field must have exactly one target: 'selector' or 'ref'.")@@ -595,10 +569,13 @@ class ScraplingMCPServer:await sleep(uniform(0.1, 0.3))locator = page.locator(item.get("selector") or f"aria-ref={item.get('ref')}")if item["type"] == "textbox":- await locator.fill("" if slowly else item["value"], timeout=timeout)- if slowly:+ if item.get("clear", True):+ await locator.fill("" if slowly else item["value"], timeout=timeout)+ if slowly and item["value"]:for character in item["value"]:await locator.press_sequentially(character, delay=uniform(50, 150), timeout=timeout)+ elif not item.get("clear", True):+ await locator.press_sequentially(item["value"], timeout=timeout)elif item["type"] == "combobox":await locator.select_option(label=item["value"], timeout=timeout)else:@@ -1333,7 +1310,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.+13. Use `browser_snapshot` to inspect the page after `browser_fill_fields` or `browser_press_key`. Actions may partly complete before an error; check the page before repeating them. To submit, focus the intended control and use `browser_press_key` with ["Enter"].""",}if self._auth_token:@@ -1446,13 +1423,6 @@ class ScraplingMCPServer:structured_output=False,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,- )server.add_tool(self.browser_press_key,title="Press keys",diff --git a/tests/ai/test_ai_mcp.py b/tests/ai/test_ai_mcp.pyindex a9d1896..9a49c47 100644--- a/tests/ai/test_ai_mcp.py+++ b/tests/ai/test_ai_mcp.py@@ -982,12 +982,13 @@ class TestServerToolRegistration:@pytest.mark.asyncioasync def test_tools_are_listed_with_expected_schemas(self):- """All 20 tools are advertised, with plain content for screenshots, snapshots, and input actions"""+ """All 19 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.instructionstools = {tool.name: tool for tool in (await client.list_tools()).tools}for name in (+ "browser_type","browser_fill_form","open_session","session_fetch",@@ -1002,16 +1003,16 @@ class TestServerToolRegistration:result = await client.call_tool(name, {})assert result.is_error- assert len(tools) == 20+ assert len(tools) == 19assert 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 tools["browser_mouse_wheel"].output_schema is Noneassert tools["browser_press_key"].output_schema is Noneassert tools["browser_fill_fields"].output_schema is Noneassert {+ "browser_type","browser_fill_form","session_snapshot","open_session",@@ -1039,7 +1040,6 @@ class TestServerToolRegistration:"browser_snapshot","browser_mouse_move","browser_click",- "browser_type","browser_mouse_wheel","browser_press_key","browser_fill_fields",@@ -1108,7 +1108,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) == 20+ assert len(annotations) == 19for name in ("make_request","bulk_get",@@ -1132,7 +1132,6 @@ class TestServerToolRegistration:for name in ("browser_mouse_move","browser_click",- "browser_type","browser_mouse_wheel","browser_press_key","browser_fill_fields",diff --git a/tests/ai/test_browser_fill_fields.py b/tests/ai/test_browser_fill_fields.pyindex 17562ac..c861091 100644--- a/tests/ai/test_browser_fill_fields.py+++ b/tests/ai/test_browser_fill_fields.py@@ -9,6 +9,8 @@ import pytestfrom anyio import CancelScopefrom mcp.client import Clientfrom mcp.types import TextContent+from patchright.async_api import TimeoutError as PatchrightTimeoutError+from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom pydantic import ValidationErrorfrom scrapling.core.ai import ScraplingMCPServer, SessionType, _SessionEntry@@ -74,12 +76,16 @@ async def test_browser_fill_fields_schema() -> None:assert len(items["oneOf"]) == 4for kind, variant in variants.items():assert set(variant["required"]) == {"type", "value"}- assert set(variant["properties"]) == {"type", "value", "selector", "ref"}+ assert set(variant["properties"]) == {"type", "value", "selector", "ref"} | (+ {"clear"} if kind == "textbox" else set()+ )assert variant["properties"]["type"]["const"] == kindfor target in ("selector", "ref"):assert {"type": "null"} in variant["properties"][target]["anyOf"]assert any(option.get("minLength") == 1 for option in variant["properties"][target]["anyOf"])assert variants["textbox"]["properties"]["value"]["type"] == "string"+ assert variants["textbox"]["properties"]["clear"]["type"] == "boolean"+ assert variants["textbox"]["properties"]["clear"]["default"] is Trueassert variants["checkbox"]["properties"]["value"]["type"] == "boolean"assert variants["radio"]["properties"]["value"]["const"] is Trueassert {option["type"] for option in variants["combobox"]["properties"]["value"]["anyOf"]} == {"string", "array"}@@ -95,7 +101,7 @@ async def test_browser_fill_fields_forwards_native_actions_in_order(monkeypatch.setattr("scrapling.core.ai.sleep", pause)fields = [{**TEXT_FIELD, "ref": None},- {"type": "textbox", "selector": None, "ref": "e2", "value": ""},+ {"type": "textbox", "selector": None, "ref": "e2", "value": "", "clear": True},{"type": "checkbox", "selector": "#agree", "value": True},{"type": "checkbox", "selector": "#agree", "value": False},{"type": "checkbox", "selector": "#agree", "value": "false"},@@ -137,6 +143,30 @@ async def test_browser_fill_fields_forwards_native_actions_in_order(assert session.page_pool.pages[0].state == "ready"[email protected]("slowly", [False, True])[email protected]("value", ["xy", ""])+async def test_browser_fill_fields_types_without_clearing(+ slowly: bool, value: str, monkeypatch: pytest.MonkeyPatch+) -> None:+ server, session, page = _server()+ monkeypatch.setattr("scrapling.core.ai.uniform", Mock(side_effect=[60, 140]))+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool(+ "browser_fill_fields",+ {"session_id": "browser", "fields": [{**TEXT_FIELD, "value": value, "clear": False}], "slowly": slowly},+ )+ assert not result.is_error+ assert result.content == [TextContent(type="text", text="Fields filled.")]+ page.locator.return_value.fill.assert_not_awaited()+ assert page.locator.return_value.press_sequentially.await_args_list == (+ [call("x", delay=60, timeout=30000), call("y", delay=140, timeout=30000)]+ if slowly and value+ else [call(value, timeout=30000)]+ )+ assert session.page_pool.pages[0].state == "ready"++@pytest.mark.asyncioasync def test_browser_fill_fields_slow_pacing_and_empty_text(monkeypatch: pytest.MonkeyPatch) -> None:server, session, page = _server()@@ -218,6 +248,8 @@ async def test_browser_fill_fields_slow_failure_stops_before_next_pause({"type": None},{"value": None},{"value": False},+ {"clear": None},+ {"clear": "invalid"},{"type": "checkbox", "value": "invalid"},{"type": "radio", "value": False},{"type": "combobox", "value": True},@@ -269,20 +301,65 @@ def test_browser_fill_fields_rejects_nonfinite_timeout(timeout: float) -> None:@pytest.mark.asyncio@pytest.mark.parametrize(- "state, message", [("missing", "not found"), ("static", "'static'"), ("empty", "browser_fetch")]+ "state, message",+ [+ ("missing", "not found"),+ ("dead", "no longer alive"),+ ("static", "'static'"),+ ("empty", "browser_fetch"),+ ("busy", "busy"),+ ("closed", "closed"),+ ],)async def test_browser_fill_fields_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 = Falseelif state == "empty":session.page_pool.clear()+ elif state == "busy":+ session.page_pool.pages[0].mark_busy()+ elif state == "closed":+ page.is_closed.return_value = Trueasync with Client(server._build_server("127.0.0.1", 8000)) as client:result = await client.call_tool("browser_fill_fields", {"session_id": "browser", "fields": [TEXT_FIELD]})assert result.is_errorassert result.content and isinstance(result.content[0], TextContent)assert message in result.content[0].textpage.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]("clear, slowly", [(True, False), (False, False), (False, True)])+async def test_browser_fill_fields_timeout_stops_and_releases_page(+ session_type: SessionType, error: type[Exception], clear: bool, slowly: bool+) -> None:+ server, session, page = _server(session_type)+ action = page.locator.return_value.fill if clear else page.locator.return_value.press_sequentially+ 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_fill_fields",+ {"session_id": "browser", "fields": [{**TEXT_FIELD, "clear": clear}, TEXT_FIELD], "slowly": slowly},+ )+ 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()+ page.locator.assert_called_once_with("#name")+ page.locator.return_value.press.assert_not_called()+ assert session.page_pool.pages[0].state == "ready"+ action.side_effect = None+ assert await server.browser_fill_fields("browser", [TEXT_FIELD]) == "Fields filled."@pytest.mark.asyncio@@ -304,11 +381,12 @@ async def test_browser_fill_fields_error_stops_remaining_fields_and_releases_pag@pytest.mark.asyncio@pytest.mark.parametrize("cancel_mode", ["task", "scope"])-async def test_browser_fill_fields_cancellation_stops_remaining_fields(cancel_mode: str) -> None:[email protected]("clear", [False, True])+async def test_browser_fill_fields_cancellation_stops_remaining_fields(cancel_mode: str, clear: bool) -> None:server, session, page = _server()entered = asyncio.Event()scope = CancelScope()- fields = [{**TEXT_FIELD, "value": value} for value in ("first", "second", "third")]+ fields = [{**TEXT_FIELD, "value": value, "clear": clear} for value in ("first", "second", "third")]async def pending(value: str, **kwargs: Any) -> None:if value == "second":@@ -319,7 +397,8 @@ async def test_browser_fill_fields_cancellation_stops_remaining_fields(cancel_mowith scope:await server.browser_fill_fields("browser", fields)- page.locator.return_value.fill.side_effect = pending+ action = page.locator.return_value.fill if clear else page.locator.return_value.press_sequentially+ action.side_effect = pendingtask = asyncio.create_task(fill())try:await asyncio.wait_for(entered.wait(), 5)@@ -334,7 +413,7 @@ async def test_browser_fill_fields_cancellation_stops_remaining_fields(cancel_moelse:with pytest.raises(asyncio.CancelledError):await task- assert page.locator.return_value.fill.await_args_list == [+ assert action.await_args_list == [call("first", timeout=30000),call("second", timeout=30000),]@@ -530,6 +609,56 @@ async def test_browser_fill_fields_live_slow_typing_and_field_delays(session_typassert session.page_pool.pages[0].state == "ready"[email protected]("session_type", ["dynamic", "stealthy"])[email protected]("slowly", [False, True])+async def test_browser_fill_fields_live_caret_selection_and_submit(session_type: SessionType, slowly: bool) -> None:+ async with _browser(session_type) as (client, session, page):+ snapshot = await client.call_tool("browser_snapshot", {"session_id": "browser"})+ assert not snapshot.is_error+ assert snapshot.content and isinstance(snapshot.content[0], TextContent)+ name = search(r'textbox "Name".*?\[ref=([^\]]+)\]', snapshot.content[0].text)+ assert name is not None++ async def fill(fields: list[dict[str, Any]]) -> None:+ result = await client.call_tool(+ "browser_fill_fields", {"session_id": "browser", "fields": fields, "slowly": slowly}+ )+ assert not result.is_error+ assert session.page_pool.pages[0].state == "ready"++ async def press(keys: list[str]) -> None:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", "keys": keys})+ assert not result.is_error++ await fill([{**TEXT_FIELD, "value": "abcd"}])+ await press(["ArrowLeft"])+ await fill([{"type": "textbox", "ref": name[1], "value": "XY", "clear": False}])+ assert await page.locator("#name").input_value() == "abcXYd"+ await press(["Shift+ArrowLeft", "Shift+ArrowLeft"])+ await fill([{**TEXT_FIELD, "value": "z", "clear": False}])+ assert await page.locator("#name").input_value() == "abczd"+ await fill([{**TEXT_FIELD, "value": "", "clear": False}])+ assert await page.locator("#name").input_value() == "abczd"+ await fill(+ [+ {**TEXT_FIELD, "value": "!", "clear": False},+ {"type": "textbox", "selector": "#notes", "value": "new notes"},+ ]+ )+ assert await page.locator("#name").input_value() == "abcz!d"+ assert await page.locator("#notes").input_value() == "new notes"+ assert await page.locator("#submitted").inner_text() == "0"+ focused = await client.call_tool("browser_click", {"session_id": "browser", "ref": name[1]})+ assert not focused.is_error+ await press(["Enter"])+ assert await page.locator("#submitted").inner_text() == "1"+ events = loads(await page.locator("#events").input_value())+ assert [+ event["key"] for event in events if event["type"] == "keydown" and event["key"] in ["X", "Y", "z", "!"]+ ] == ["X", "Y", "z", "!"]++@pytest.mark.asyncio@pytest.mark.parametrize("session_type", ["dynamic", "stealthy"])async def test_browser_fill_fields_live_failed_field_preserves_prior_changes(session_type: SessionType) -> None:diff --git a/tests/ai/test_browser_press_key.py b/tests/ai/test_browser_press_key.pyindex 3456c47..d03fac0 100644--- a/tests/ai/test_browser_press_key.py+++ b/tests/ai/test_browser_press_key.py@@ -202,7 +202,8 @@ async def test_browser_press_key_live_focus_editing_and_shortcuts(session_type:assert session.page_pool.pages[0].state == "ready"typed = await client.call_tool(- "browser_type", {"session_id": "browser", "selector": "#first", "text": "initial"}+ "browser_fill_fields",+ {"session_id": "browser", "fields": [{"type": "textbox", "selector": "#first", "value": "initial"}]},)assert not typed.is_errorawait page.locator("#events").evaluate("element => element.value = '[]'")diff --git a/tests/ai/test_browser_type.py b/tests/ai/test_browser_type.pydeleted file mode 100644index 20b2973..0000000--- a/tests/ai/test_browser_type.py+++ /dev/null@@ -1,353 +0,0 @@-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"