Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(playground): add CLI for arbitrary WebMCP sites
ldm07909cff7b65b
diff --git a/README.md b/README.mdindex 80508afc1..c1f0eee57 100644--- a/README.md+++ b/README.md@@ -172,8 +172,8 @@ console.log(await page.locator("body").innerText());await browser.close();```-For native WebMCP examples, the [WebMCP playground](moli-playground/webmcp/README.md)-discovers and invokes tools on public booking, restaurant, and pizza demo sites.+The [WebMCP playground](moli-playground/webmcp/README.md) includes a CLI to list+and call any site's native WebMCP tools, plus booking, restaurant, and pizza demos.## Why Molidiff --git a/moli-playground/webmcp/README.md b/moli-playground/webmcp/README.mdindex 14603bf61..87698996d 100644--- a/moli-playground/webmcp/README.md+++ b/moli-playground/webmcp/README.md@@ -1,10 +1,89 @@-# WebMCP demos with Moli+# WebMCP tools and demos with MoliThese demos open public WebMCP sites in Moli, discover their native tools overCDP, invoke them, and check both the tool responses and the page state. No modelaccount or API key is required: the scripts supply the tool arguments directly.-## Run+## Operate any WebMCP site++`webmcp.py` accepts a site URL and uses the site's native tool catalog. Build Moli+with `cargo build --release -p moli`, then list a site's tools and full schemas:++```bash+uv run moli-playground/webmcp/webmcp.py \+ https://googlechromelabs.github.io/webmcp-tools/demos/pizza-maker/ list+```++Call a tool with JSON arguments:++```bash+uv run moli-playground/webmcp/webmcp.py \+ https://googlechromelabs.github.io/webmcp-tools/demos/pizza-maker/ \+ call set_pizza_size --input '{"size":"Large"}'+```++`--input @arguments.json` reads a file; `--input -` reads JSON from stdin. Input+must be a JSON object. Tool responses go to stdout as JSON, including the native+status, output, and any execution error. A failed one-shot call exits with status+1. A site with no registered tools produces an empty list.++Each one-shot command opens a new page. To make several calls on the same page,+use the interactive shell:++```bash+uv run moli-playground/webmcp/webmcp.py \+ https://googlechromelabs.github.io/webmcp-tools/demos/pizza-maker/ shell+```++Inside the shell:++```text+tools+schema set_pizza_size+call set_pizza_size {"size":"Large"}+wait <invocationId>+call add_topping {"topping":"🍍","size":"Large","count":3}+wait <invocationId>+quit+```++Use the invocation ID printed by each `call`. `result ID` shows its current+status, `wait ID` waits for completion, and `cancel ID` cancels a pending call.+The shell keeps receiving tool additions, removals, and responses while waiting+for your next command. Commands may also be piped into the shell. Pending calls+started by this session are cancelled when it exits.++For declarative forms that need confirmation, run `call NAME JSON`, inspect the+prepared form in your attached page, then use `confirm ID` and `wait ID`.+Confirmation targets the form identified by the native tool's node, including+forms in child frames. For a one-shot call, `--confirm` explicitly submits the+form after filling. Without it, a manual form call reports that confirmation is+required before starting an invocation.++The catalog includes tools in child frames. If a name occurs in several frames,+select `--frame-id ID` or use `frame ID` in the shell. `frame main` selects the+main frame; `frame all` returns to the complete catalog. Frame IDs belong to the+current page, so use the shell or attach to that page when selecting a child.++To reuse an authenticated or already prepared page in an existing release Moli+server:++```bash+uv run moli-playground/webmcp/webmcp.py - shell \+ --cdp-endpoint http://127.0.0.1:9222 --target-id TID-1+```++The URL `-` preserves the current page without navigating. `--target-id` requires+`--cdp-endpoint`; the script leaves that page and server open on exit. The target+IDs can be obtained from the server's `/json/list` endpoint.++The CLI waits two seconds after page load to collect initial registrations;+increase `--wait-for-tools` for sites that register tools later. It also supports+the release binary, proxy, and timeout options listed below. Sites must expose+native WebMCP tools; a remote MCP endpoint or static inventory alone is not a+browser tool registration.++## Run the preset demosFrom the repository root, build a release Moli binary with native WebMCP supportand run all three demos:@@ -105,6 +184,19 @@ early when native `document.modelContext` exists. The runner supplies nopolyfill and invokes tools through Moli's registry. `Runtime.evaluate` reads thepage state and performs the bistro's ordinary confirmation click.+The CLI and demos share [webmcp_client.py](webmcp_client.py), including release+server startup, CDP event handling, and invocation tracking. Run the offline CLI+integration checks with a release binary already built:++```bash+uv run --with websockets python3 -m unittest discover \+ -s moli-playground/webmcp -p test_webmcp.py -v+```++The checks cover shared page state, duplicate names across frames, dynamic tool+registration/removal, cancellation, exact form confirmation with two pending+forms, execution errors, and preserving an attached page.+These demos need access to the external pages and their dependencies, includingGitHub Pages and the bistro's DOMPurify module on `esm.sh`. A network error or achanged tool/schema/page structure is reported as a failure. They are manualdiff --git a/moli-playground/webmcp/test_webmcp.py b/moli-playground/webmcp/test_webmcp.pynew file mode 100644index 000000000..89ebbe44e--- /dev/null+++ b/moli-playground/webmcp/test_webmcp.py@@ -0,0 +1,311 @@+"""Offline CLI integration checks against a release Moli and native WebMCP."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import subprocess+import sys+import threading+import unittest+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from unittest.mock import patch++from webmcp_client import CdpPage, discovery, moli_server+from websockets.asyncio.client import connect++DIRECTORY = Path(__file__).resolve().parent+CLI = DIRECTORY / "webmcp.py"+PAGE = """<!doctype html><body>+<form toolname="first_form" tooldescription="Return the first form's message">+ <input name="message" required><button>Send first</button>+</form>+<form toolname="second_form" tooldescription="Return the second form's message">+ <input name="message" required><button>Send second</button>+</form>+<iframe src="/child"></iframe>+<script>+let count = 0;+let extraController;+const context = document.modelContext;+context.registerTool({name:'echo',description:'Echo with a session counter',+ inputSchema:{type:'object',properties:{text:{type:'string'}},required:['text']},+ execute:({text})=>({text,count:++count})});+context.registerTool({name:'waiting',description:'Wait until cancelled',+ execute:(_,options)=>new Promise(resolve=>options.signal.addEventListener('abort',+ ()=>resolve('late result')))});+context.registerTool({name:'fail',description:'Return an execution error',+ execute:()=>{throw new Error('fixture failure')}});+context.registerTool({name:'add_extra',description:'Register an extra tool',+ execute:async()=>{+ extraController=new AbortController();+ await context.registerTool({name:'extra',description:'Dynamically registered tool',+ execute:()=>({extra:true})},{signal:extraController.signal});+ return 'added';+ }});+context.registerTool({name:'drop_extra',description:'Remove the extra tool',+ execute:()=>{extraController.abort();return 'removed'}});+for (const form of document.forms) form.addEventListener('submit',event=>{+ event.preventDefault();+ if (event.agentInvoked) event.respondWith({form:form.getAttribute('toolname'),+ message:form.elements.message.value});+});+</script>+"""+CHILD = """<!doctype html><script>+document.modelContext.registerTool({name:'echo',description:'Echo from a child frame',+ execute:({text})=>({text,child:true})});+</script>"""+++class Handler(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ content = (CHILD if self.path == "/child" else PAGE).encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(content)))+ self.end_headers()+ self.wfile.write(content)++ def log_message(self, _format, *_args) -> None:+ pass+++def records(output: str) -> list:+ decoder = json.JSONDecoder()+ values = []+ while output.strip():+ output = output.lstrip()+ value, length = decoder.raw_decode(output)+ values.append(value)+ output = output[length:]+ return values+++class WebMcpCliTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ # Match Cargo's local-test environment: fixtures must bypass host proxies.+ proxies = patch.dict(+ os.environ,+ {+ key: ""+ for key in (+ "all_proxy",+ "http_proxy",+ "https_proxy",+ "ALL_PROXY",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ )+ },+ )+ proxies.start()+ cls.addClassCleanup(proxies.stop)+ cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)+ cls.thread.start()+ cls.url = f"http://127.0.0.1:{cls.server.server_port}/"++ @classmethod+ def tearDownClass(cls) -> None:+ cls.server.shutdown()+ cls.server.server_close()+ cls.thread.join(timeout=3)++ def cli(+ self, *options: str, input_text: str | None = None, url: str | None = None+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [+ sys.executable,+ str(CLI),+ url or self.url,+ *options,+ "--timeout",+ "10",+ "--wait-for-tools",+ "0.2",+ ],+ input=input_text,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ def test_catalog_and_one_shot_calls(self) -> None:+ listed = self.cli("list")+ self.assertEqual(listed.returncode, 0, listed.stderr)+ echoes = [tool for tool in json.loads(listed.stdout) if tool["name"] == "echo"]+ self.assertEqual(len(echoes), 2)+ self.assertNotEqual(echoes[0]["frameId"], echoes[1]["frameId"])+ self.assertIn("target/release/moli", listed.stderr)+ called = self.cli(+ "call",+ "echo",+ "--frame-id",+ "main",+ "--input",+ "-",+ input_text='{"text":"from stdin"}',+ )+ self.assertEqual(called.returncode, 0, called.stderr)+ self.assertEqual(+ json.loads(called.stdout)["output"], {"text": "from stdin", "count": 1}+ )+ failed = self.cli("call", "fail")+ self.assertEqual(failed.returncode, 1, failed.stderr)+ self.assertEqual(json.loads(failed.stdout)["status"], "Error")+ self.assertIn(+ "fixture failure", json.loads(failed.stdout)["exception"]["description"]+ )+ invalid = self.cli("call", "echo", "--input", '{"text":NaN}')+ self.assertEqual(invalid.returncode, 1, invalid.stderr)+ self.assertIn("Invalid tool input", invalid.stderr)+ self.assertNotIn("Moli:", invalid.stderr)++ def test_session_state_dynamic_tools_cancel_and_exact_form_confirmation(+ self,+ ) -> None:+ result = self.cli(+ "shell",+ input_text="""call echo {"text":"ambiguous"}+frame main+call echo {"text":"first"}+wait 1+call echo {"text":"second"}+wait 2+call add_extra {}+wait 3+schema extra+call extra {}+wait 4+call drop_extra {}+wait 5+tools+call waiting {}+cancel 6+call first_form {"message":"one"}+call second_form {"message":"two"}+confirm 7+wait 7+confirm 8+wait 8+quit+""",+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("exists in multiple frames", result.stderr)+ values = records(result.stdout)+ responses = {+ value["invocationId"]: value+ for value in values+ if isinstance(value, dict)+ and value.get("status") in {"Completed", "Canceled"}+ }+ self.assertEqual(responses["1"]["output"], {"text": "first", "count": 1})+ self.assertEqual(responses["2"]["output"], {"text": "second", "count": 2})+ self.assertTrue(+ any(+ isinstance(value, dict) and value.get("name") == "extra"+ for value in values+ )+ )+ catalogs = [value for value in values if isinstance(value, list)]+ self.assertNotIn("extra", {tool["name"] for tool in catalogs[-1]})+ self.assertEqual(responses["6"]["status"], "Canceled")+ self.assertEqual(+ responses["7"]["output"], {"form": "first_form", "message": "one"}+ )+ self.assertEqual(+ responses["8"]["output"], {"form": "second_form", "message": "two"}+ )++ def test_existing_page_is_preserved_and_child_tool_is_callable(self) -> None:+ async def scenario(endpoint: str) -> None:+ version = discovery(endpoint)+ async with connect(+ version["webSocketDebuggerUrl"], proxy=None+ ) as websocket:+ page = CdpPage(websocket, 10)+ try:+ await page.open(self.url)+ await page.until(+ lambda: (+ len(+ [+ tool+ for tool in page.all_tools()+ if tool["name"] == "echo"+ ]+ )+ == 2+ ),+ "child tool",+ )+ child = next(+ tool+ for tool in page.all_tools()+ if tool["frameId"] != page.frame_id+ )+ attached = await asyncio.to_thread(+ self.cli,+ "call",+ "echo",+ "--input",+ '{"text":"child"}',+ "--frame-id",+ child["frameId"],+ "--cdp-endpoint",+ endpoint,+ "--target-id",+ page.target_id,+ url="-",+ )+ self.assertEqual(attached.returncode, 0, attached.stderr)+ self.assertEqual(+ json.loads(attached.stdout)["output"],+ {"text": "child", "child": True},+ )+ pending_form = await asyncio.to_thread(+ self.cli,+ "shell",+ "--cdp-endpoint",+ endpoint,+ "--target-id",+ page.target_id,+ url="-",+ input_text='call first_form {"message":"leave open"}\nquit\n',+ )+ self.assertEqual(pending_form.returncode, 0, pending_form.stderr)+ self.assertFalse(+ await page.evaluate(+ "document.forms[0].matches(':tool-form-active')"+ )+ )+ targets = await page.command("Target.getTargets", browser=True)+ self.assertIn(+ page.target_id,+ {target["targetId"] for target in targets["targetInfos"]},+ )+ self.assertEqual(await page.evaluate("location.href"), self.url)+ finally:+ await page.close()++ args = argparse.Namespace(+ cdp_endpoint=None,+ moli_bin=None,+ timeout=10,+ startup_timeout=15,+ http_proxy=None,+ )+ with moli_server(args) as endpoint:+ asyncio.run(scenario(endpoint))+++if __name__ == "__main__":+ unittest.main()diff --git a/moli-playground/webmcp/webmcp.py b/moli-playground/webmcp/webmcp.pynew file mode 100755index 000000000..14dede17a--- /dev/null+++ b/moli-playground/webmcp/webmcp.py@@ -0,0 +1,270 @@+#!/usr/bin/env python3+# /// script+# requires-python = ">=3.11"+# dependencies = ["websockets>=15,<18"]+# ///+"""List and call any site's native WebMCP tools, or operate them in one session."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import stat+import sys+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++from webmcp_client import (+ CdpPage,+ DemoError,+ discovery,+ moli_server,+ require,+)+from websockets.asyncio.client import connect+from websockets.exceptions import ConnectionClosed+++def arguments(value: str) -> dict[str, Any]:+ try:+ if value.startswith("@"):+ value = Path(value[1:]).read_text(encoding="utf-8")+ elif value == "-":+ value = sys.stdin.read()+ parsed = json.loads(value)+ json.dumps(parsed, allow_nan=False)+ except (OSError, ValueError) as error:+ raise DemoError(f"Invalid tool input: {error}") from error+ require(isinstance(parsed, dict), "Tool input must be a JSON object.")+ return parsed+++def emit(value: Any) -> None:+ print(json.dumps(value, ensure_ascii=False, indent=2), flush=True)+++def frame_selection(page: CdpPage, frame: str | None) -> str | None:+ return page.frame_id if frame == "main" else None if frame == "all" else frame+++def pending(page: CdpPage, invocation_id: str) -> dict[str, Any]:+ step = page.invocation(invocation_id)+ return page.responded.get(invocation_id) or {+ "invocationId": invocation_id,+ "toolName": step["tool"],+ "frameId": step["frameId"],+ "status": "Pending",+ }+++HELP = """Commands:+ tools List the current tool catalog and schemas+ schema NAME Show one tool's schema+ frame ID|main|all Select a frame (default: all)+ call NAME JSON Start a call; JSON defaults to {}+ result ID Show the current result without waiting+ wait ID Wait for a tool response+ confirm ID Submit the active declarative form+ cancel ID Cancel a pending invocation+ help Show these commands+ quit End the session+JSON may also be @file.json. Calls share the same page state.+"""+++async def input_lines() -> AsyncIterator[str]:+ interactive = sys.stdin.isatty()+ encoding = sys.stdin.encoding or "utf-8"+ if stat.S_ISREG(os.fstat(sys.stdin.fileno()).st_mode):+ for line in sys.stdin:+ yield line+ return+ reader = asyncio.StreamReader()+ transport, _ = await asyncio.get_running_loop().connect_read_pipe(+ lambda: asyncio.StreamReaderProtocol(reader), sys.stdin+ )+ try:+ while True:+ if interactive:+ print("webmcp> ", end="", file=sys.stderr, flush=True)+ line = await reader.readline()+ if not line:+ return+ yield line.decode(encoding)+ finally:+ transport.close()+++async def shell(page: CdpPage, frame: str | None) -> int:+ print(HELP, file=sys.stderr)+ emit(page.all_tools(frame_selection(page, frame)))+ async for line in input_lines():+ command, _, rest = line.strip().partition(" ")+ if not command:+ continue+ if command in {"quit", "exit"}:+ return 0+ try:+ await page.refresh()+ selected = frame_selection(page, frame)+ if command == "help":+ print(HELP, file=sys.stderr)+ elif command == "tools":+ emit(page.all_tools(selected))+ elif command == "schema":+ emit(page.select_tool(rest.strip(), selected))+ elif command == "frame":+ require(rest.strip(), "Usage: frame ID|main|all")+ frame = rest.strip()+ emit({"frameId": frame_selection(page, frame)})+ elif command == "call":+ name, _, value = rest.strip().partition(" ")+ require(name, "Usage: call NAME JSON")+ tool = page.select_tool(name, selected)+ require(+ value.strip() != "-", "Use inline JSON or @file.json in the shell."+ )+ invocation_id = await page.begin(+ name, arguments(value.strip() or "{}"), frame_id=tool["frameId"]+ )+ await page.refresh()+ emit(pending(page, invocation_id))+ elif command in {"result", "wait", "confirm", "cancel"}:+ invocation_id = rest.strip()+ require(invocation_id, f"Usage: {command} ID")+ if command == "result":+ emit(pending(page, invocation_id))+ elif command == "wait":+ emit(await page.response(invocation_id))+ elif command == "cancel":+ emit(await page.cancel(invocation_id))+ else:+ await page.confirm(invocation_id)+ await page.refresh()+ emit(pending(page, invocation_id))+ else:+ raise DemoError(f"Unknown command {command!r}; type help.")+ except DemoError as error:+ print(f"Error: {error}", file=sys.stderr)+ return 0+++async def run(args: argparse.Namespace, endpoint: str) -> int:+ version = await asyncio.to_thread(discovery, endpoint)+ websocket_url = version.get("webSocketDebuggerUrl")+ require(websocket_url, "The CDP server did not provide a browser WebSocket URL.")+ async with connect(+ websocket_url, proxy=None, max_size=None, open_timeout=args.timeout+ ) as websocket:+ page = CdpPage(websocket, args.timeout)+ try:+ await page.open(+ None if args.url == "-" else args.url, target_id=args.target_id+ )+ await page.settle(args.wait_for_tools)+ frame = frame_selection(page, args.frame_id)+ if args.action == "list":+ emit(page.all_tools(frame))+ return 0+ if args.action == "shell":+ return await shell(page, args.frame_id)+ tool = page.select_tool(args.tool, frame)+ manual = "backendNodeId" in tool and not tool.get("annotations", {}).get(+ "autosubmit"+ )+ require(+ not manual or args.confirm,+ "This form needs confirmation; use call --confirm, or use shell with call, confirm, and wait.",+ )+ invocation_id = await page.begin(+ args.tool, args.input, frame_id=tool["frameId"]+ )+ if manual:+ await page.until(+ lambda: (+ invocation_id in page.invoked or invocation_id in page.responded+ ),+ "form filling",+ )+ if invocation_id not in page.responded:+ await page.confirm(invocation_id)+ response = await page.response(invocation_id)+ emit(response)+ return int(response["status"] != "Completed")+ finally:+ try:+ await page.close()+ except (DemoError, OSError, ConnectionClosed):+ pass+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "url", help="Site URL, or - to keep an existing --target-id page"+ )+ parser.add_argument(+ "action", nargs="?", choices=["list", "call", "shell"], default="list"+ )+ parser.add_argument("tool", nargs="?", help="Tool name for the call action")+ parser.add_argument(+ "--input", default="{}", help="JSON object, @file.json, or - for stdin"+ )+ parser.add_argument(+ "--frame-id", help="Choose a frame, main, or all (default: all)"+ )+ parser.add_argument(+ "--confirm",+ action="store_true",+ help="Confirm a declarative form after filling",+ )+ parser.add_argument(+ "--wait-for-tools",+ type=float,+ default=2,+ help="Seconds to collect initial registrations after page load",+ )+ parser.add_argument(+ "--moli-bin", help="Release Moli binary (default: target/release/moli)"+ )+ parser.add_argument("--cdp-endpoint", help="Reuse an existing release Moli server")+ parser.add_argument(+ "--target-id", help="Attach to a page in --cdp-endpoint; leave it open on exit"+ )+ parser.add_argument(+ "--http-proxy", help="HTTP proxy for a server started by this script"+ )+ parser.add_argument(+ "--timeout", type=float, default=45, help="Command and event timeout in seconds"+ )+ parser.add_argument("--startup-timeout", type=float, default=15)+ args = parser.parse_args()+ if args.action == "call" and not args.tool:+ parser.error("call requires a tool name")+ if args.action != "call" and (args.tool or args.confirm or args.input != "{}"):+ parser.error("tool, --input, and --confirm are only supported with call")+ if args.target_id and not args.cdp_endpoint:+ parser.error("--target-id requires --cdp-endpoint")+ if args.url == "-" and not args.target_id:+ parser.error("URL - requires --target-id")+ if args.timeout <= 0 or args.startup_timeout <= 0 or args.wait_for_tools < 0:+ parser.error(+ "timeouts must be positive and --wait-for-tools must be nonnegative"+ )+ if args.action == "call":+ args.input = arguments(args.input)+ with moli_server(args) as endpoint:+ return asyncio.run(run(args, endpoint))+++if __name__ == "__main__":+ try:+ raise SystemExit(main())+ except (DemoError, OSError, TimeoutError, ConnectionClosed) as error:+ print(f"WebMCP failed: {error}", file=sys.stderr)+ raise SystemExit(1) from error+ except KeyboardInterrupt:+ raise SystemExit(130)