🕷️ 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 control mouse wheel
Karim shoaire512bc0bc480
diff --git a/agent-skill/Scrapling-Skill.zip b/agent-skill/Scrapling-Skill.zipindex a84ff27..534c8e7 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 3cdf2dd..165a401 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 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`.+The Scrapling MCP server exposes eighteen 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`, `browser_click`, and `browser_type` 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`, and `browser_type` return plain text.## Shadow DOM@@ -180,6 +180,20 @@ Selector and reference hovers use Playwright's locator hover, which waits for thReturns plain text without an automatic snapshot. Use `browser_snapshot` to inspect the page afterward. Invalid targets, unknown sessions, and missing, closed, or busy pages return an error.+### `browser_mouse_wheel` -- Scroll at the current pointer position++Sends a native mouse wheel event on the existing page in a dynamic or stealthy browser session. Call `browser_fetch` first. To target a scrollable area, use `browser_mouse_move` with a selector, snapshot reference, or coordinates before scrolling.++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `session_id` | str | required | ID of an open browser session |+| `delta_x` | number | 0 | Finite horizontal delta in CSS pixels; positive moves right, negative moves left |+| `delta_y` | number | 0 | Finite vertical delta in CSS pixels; positive moves down, negative moves up |++Fractional values and zero are allowed. Uses `page.mouse.wheel` at the current pointer position without moving the mouse, injecting a page script, or navigating. Dispatch does not guarantee scrolling: the page can prevent the event, or the scrollable area can be at its edge. It does not wait for scrolling, animations, or content loaded by scrolling to finish.++Returns `Wheel event sent.` as plain text without an automatic snapshot. Use `browser_snapshot` to inspect the current page afterward. Errors are not retried. Invalid deltas, unknown or HTTP sessions, and missing, closed, or busy pages return an error.+### `browser_click` -- Click by selector, snapshot reference, or coordinatesClicks on the existing page in a dynamic or stealthy browser session. Call `browser_fetch` first. Supply exactly one target: `selector`, `ref`, or both `x` and `y`.@@ -275,6 +289,7 @@ Requires an open browser session. Call `browser_open` first, then pass the `sess| Need a screenshot of a page | `browser_open` + `browser_screenshot` with `session_id` || 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` |+| 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` |@@ -367,7 +382,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`, `browser_type`, 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_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 7b97eb5..b1b2480 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 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.+The Scrapling MCP Server provides eighteen 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@@ -44,6 +44,7 @@ The Scrapling MCP Server provides seventeen tools for web scraping and browser i#### Mouse Actions- **`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_mouse_wheel`**: Scroll pages, menus, and nested panels vertically or horizontally with the browser's native mouse wheel. Helps the AI explore long feeds and content that loads as you scroll. The AI can move the mouse first to choose a scrollable area.- **`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@@ -209,7 +210,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`, `browser_type`, 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_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 90d7bcc..47f2003 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 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.+The **Scrapling MCP Server** provides eighteen 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_click`, and `browser_type` 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`, and `browser_type` return plain text.## ::: scrapling.core.ai.ResponseModelhandler: python@@ -58,6 +58,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_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_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/ai.py b/scrapling/core/ai.pyindex f0ee257..24aad9a 100644--- a/scrapling/core/ai.py+++ b/scrapling/core/ai.py@@ -439,6 +439,22 @@ class ScraplingMCPServer:await page.mouse.move(x, y, steps=steps)return f"Mouse moved to ({x}, {y})."+ async def browser_mouse_wheel(+ self,+ session_id: str,+ delta_x: FiniteFloat = 0,+ delta_y: FiniteFloat = 0,+ ) -> str:+ """Send a wheel event at the current mouse position; return plain text.++ :param session_id: ID from `browser_open`; call `browser_fetch` first.+ :param delta_x: Horizontal pixels; positive scrolls right, negative scrolls left.+ :param delta_y: Vertical pixels; positive scrolls down, negative scrolls up.+ """+ with self._browser_page(session_id) as (_, page):+ await page.mouse.wheel(delta_x, delta_y)+ return "Wheel event sent."+async def browser_click(self,session_id: str,@@ -1339,6 +1355,13 @@ class ScraplingMCPServer:structured_output=False,annotations=_INPUT_TOOL_ANNOTATIONS,)+ server.add_tool(+ self.browser_mouse_wheel,+ title="Scroll",+ description=self.browser_mouse_wheel.__doc__,+ structured_output=False,+ annotations=_INPUT_TOOL_ANNOTATIONS,+ )server.add_tool(self.browser_click,title="Click",diff --git a/tests/ai/test_ai_mcp.py b/tests/ai/test_ai_mcp.pyindex f9e59fe..b915893 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 17 tools are advertised, with plain content for screenshots, snapshots, and input actions"""+ """All 18 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,12 +1001,13 @@ class TestServerToolRegistration:result = await client.call_tool(name, {})assert result.is_error- assert len(tools) == 17+ assert len(tools) == 18assert 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 Noneassert tools["browser_type"].output_schema is None+ assert tools["browser_mouse_wheel"].output_schema is Noneassert {"session_snapshot","open_session",@@ -1029,7 +1030,14 @@ class TestServerToolRegistration:tool.output_schema is not Nonefor name, tool in tools.items()if name- not in ("browser_screenshot", "browser_snapshot", "browser_mouse_move", "browser_click", "browser_type")+ not in (+ "browser_screenshot",+ "browser_snapshot",+ "browser_mouse_move",+ "browser_click",+ "browser_type",+ "browser_mouse_wheel",+ ))@pytest.mark.asyncio@@ -1094,7 +1102,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) == 17+ assert len(annotations) == 18for name in ("make_request","bulk_get",@@ -1115,7 +1123,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", "browser_type"):+ for name in ("browser_mouse_move", "browser_click", "browser_type", "browser_mouse_wheel"):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_wheel.py b/tests/ai/test_browser_wheel.pynew file mode 100644index 0000000..1ca1953--- /dev/null+++ b/tests/ai/test_browser_wheel.py@@ -0,0 +1,240 @@+import asyncio+from contextlib import asynccontextmanager+from json import loads+from os import getenv+from unittest.mock import AsyncMock, Mock++import pytest+from anyio import CancelScope+from mcp.client import Client+from mcp.types import TextContent+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><head><style>+html { scroll-behavior: auto; }+body { margin: 0; }+#surface { width: 3000px; height: 3000px; }+#panel { position: fixed; left: 40px; top: 40px; width: 240px; height: 180px;+ overflow: auto; overscroll-behavior: contain; scroll-behavior: auto; }+#content { width: 2000px; height: 2000px; }+</style></head><body><main id="surface">Page</main><div id="panel"><div id="content">Panel</div></div>+<textarea id="events" hidden>[]</textarea><script>+document.addEventListener('wheel', event => {+ const events = document.querySelector('#events');+ events.value = JSON.stringify([...JSON.parse(events.value), {dx: event.deltaX, dy: event.deltaY,+ x: event.clientX, y: event.clientY, mode: event.deltaMode, trusted: event.isTrusted,+ target: event.target.closest('#panel') ? 'panel' : 'page'}]);+}, {passive: true});+</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+ page.mouse.wheel = AsyncMock()+ session.page_pool.add_page(page).mark_ready()+ server._sessions["browser"] = _SessionEntry(session, session_type)+ return server, session, page+++async def test_browser_wheel_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_mouse_wheel")+ assert set(tool.input_schema["properties"]) == {"session_id", "delta_x", "delta_y"}+ assert tool.input_schema["required"] == ["session_id"]+ for field in ("delta_x", "delta_y"):+ assert tool.input_schema["properties"][field]["type"] == "number"+ assert tool.input_schema["properties"][field]["default"] == 0+++ "values", [{}, {"delta_y": 120}, {"delta_x": -12.5, "delta_y": 23.5}, {"delta_x": 10.5, "delta_y": -20.5}]+)+async def test_browser_wheel_forwards_deltas_without_moving_or_capturing(values: dict[str, float]) -> None:+ server, session, page = _server()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_mouse_wheel", {"session_id": "browser", **values})+ assert not result.is_error+ assert result.structured_content is None+ assert result.content == [TextContent(type="text", text="Wheel event sent.")]+ page.mouse.wheel.assert_awaited_once_with(values.get("delta_x", 0), values.get("delta_y", 0))+ page.mouse.move.assert_not_called()+ page.locator.assert_not_called()+ page.aria_snapshot.assert_not_called()+ page.screenshot.assert_not_called()+ assert session.page_pool.pages[0].state == "ready"++[email protected]("field", ["delta_x", "delta_y"])[email protected]("value", ["invalid", "NaN", "Infinity", None])+async def test_browser_wheel_invalid_input_does_not_reserve_page(field: str, value: 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_mouse_wheel", {"session_id": "browser", field: value})+ assert result.is_error+ page.is_closed.assert_not_called()+ page.mouse.wheel.assert_not_awaited()+ assert session.page_pool.pages[0].state == "ready"++[email protected]("value", [float("nan"), float("inf"), float("-inf")])+def test_browser_wheel_schema_rejects_nonfinite_deltas(value: float) -> None:+ tool = ScraplingMCPServer()._build_server("127.0.0.1", 8000)._tool_manager.get_tool("browser_mouse_wheel")+ assert tool is not None+ for field in ("delta_x", "delta_y"):+ with pytest.raises(ValidationError):+ tool.fn_metadata.arg_model.model_validate({"session_id": "browser", field: value})+++ "state, message",+ [+ ("missing", "not found"),+ ("dead", "no longer alive"),+ ("static", "'static'"),+ ("empty", "browser_fetch"),+ ("busy", "busy"),+ ("closed", "closed"),+ ],+)+async def test_browser_wheel_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_mouse_wheel", {"session_id": "browser", "delta_y": 120})+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert message in result.content[0].text+ page.mouse.wheel.assert_not_awaited()+++async def test_browser_wheel_error_is_not_retried_and_releases_page() -> None:+ server, session, page = _server()+ page.mouse.wheel.side_effect = RuntimeError("wheel failed")+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_mouse_wheel", {"session_id": "browser", "delta_y": 120})+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert "wheel failed" in result.content[0].text+ page.mouse.wheel.assert_awaited_once()+ assert session.page_pool.pages[0].state == "ready"+ page.mouse.wheel.side_effect = None+ assert await server.browser_mouse_wheel("browser", delta_y=-120) == "Wheel event sent."++[email protected]("cancel_mode", ["task", "scope"])+async def test_browser_wheel_reserves_page_until_cancelled(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 wheel() -> None:+ with scope:+ await server.browser_mouse_wheel("browser", delta_y=120)++ page.mouse.wheel.side_effect = pending+ task = asyncio.create_task(wheel())+ 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_mouse_wheel("browser", delta_y=120)+ 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+ page.mouse.wheel.assert_awaited_once()+ assert session.page_pool.pages[0].state == "ready"+++@asynccontextmanager+async def _browser(session_type: SessionType) -> AsyncGenerator[tuple[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://wheel.test/", "google_search": False}+ )+ assert not fetched.is_error+ yield 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_wheel_live_scrolls_under_current_pointer(session_type: SessionType) -> None:+ async with _browser(session_type) as (client, session, page):+ expected = {"page": [0, 0], "panel": [0, 0]}+ events_count = 0+ for target, x, y in (("page", 400, 300), ("panel", 100, 100)):+ moved = await client.call_tool("browser_mouse_move", {"session_id": "browser", "x": x, "y": y})+ assert not moved.is_error+ for dx, dy in ((0, 120), (80, 0), (0, -60), (-40, 0)):+ result = await client.call_tool(+ "browser_mouse_wheel", {"session_id": "browser", "delta_x": dx, "delta_y": dy}+ )+ assert not result.is_error+ expected[target][0] += dx+ expected[target][1] += dy+ await page.wait_for_function(+ """([target, x, y]) => {+ const element = target === 'page' ? document.scrollingElement : document.querySelector('#panel');+ return Math.abs(element.scrollLeft - x) < 1 && Math.abs(element.scrollTop - y) < 1;+ }""",+ arg=[target, *expected[target]],+ timeout=5000,+ )+ assert (+ await page.evaluate("""() => ({page: [scrollX, scrollY], panel:+ [document.querySelector('#panel').scrollLeft, document.querySelector('#panel').scrollTop]})""")+ == expected+ )+ events = loads(await page.locator("#events").input_value())+ events_count += 1+ assert len(events) == events_count+ event = events[-1]+ for axis, delta in (("dx", dx), ("dy", dy)):+ assert event[axis] == 0 if delta == 0 else event[axis] * delta > 0+ assert event.items() >= {"x": x, "y": y, "mode": 0, "trusted": True, "target": target}.items()+ assert session.page_pool.pages[0].state == "ready"