|
| 1 | +""" |
| 2 | +MCP tools that drive a real browser via the WebRunner executor. |
| 3 | +
|
| 4 | +The executor already maps ~200 ``WR_*`` strings to callables (Selenium, |
| 5 | +Playwright, reporting, …); these tools simply hand a JSON-RPC ``arguments`` |
| 6 | +payload through to ``execute_action`` / ``execute_files``. |
| 7 | +
|
| 8 | +Two hazards are handled here so the rest of the protocol stays clean: |
| 9 | +
|
| 10 | +* ``execute_action`` prints each record to stdout. The MCP server speaks |
| 11 | + JSON-RPC over stdout, so stray prints corrupt the wire. We redirect stdout |
| 12 | + into a buffer for the duration of the call and surface it as ``stdout`` in |
| 13 | + the result. |
| 14 | +* Action return values may contain WebDriver / WebElement instances that |
| 15 | + ``json.dumps`` cannot serialise. ``_serialize_value`` reduces those to |
| 16 | + ``repr()`` strings before the server's encoder sees them. |
| 17 | +""" |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import io |
| 21 | +from contextlib import redirect_stdout |
| 22 | +from typing import Any, Dict, List |
| 23 | + |
| 24 | +from je_web_runner.mcp_server.server import McpServerError, Tool |
| 25 | + |
| 26 | + |
| 27 | +def _serialize_value(value: Any) -> Any: |
| 28 | + if value is None or isinstance(value, (bool, int, float, str)): |
| 29 | + return value |
| 30 | + if isinstance(value, (list, tuple)): |
| 31 | + return [_serialize_value(item) for item in value] |
| 32 | + if isinstance(value, dict): |
| 33 | + return {str(key): _serialize_value(item) for key, item in value.items()} |
| 34 | + return repr(value) |
| 35 | + |
| 36 | + |
| 37 | +def _serialize_record(record: Dict[Any, Any]) -> Dict[str, Any]: |
| 38 | + return {str(key): _serialize_value(value) for key, value in record.items()} |
| 39 | + |
| 40 | + |
| 41 | +def _tool_run_actions(arguments: Dict[str, Any]) -> Any: |
| 42 | + from je_web_runner.utils.executor.action_executor import execute_action |
| 43 | + actions = arguments.get("actions") |
| 44 | + if not isinstance(actions, list): |
| 45 | + raise McpServerError("'actions' must be a list of [name, params] entries") |
| 46 | + buffer = io.StringIO() |
| 47 | + with redirect_stdout(buffer): |
| 48 | + record = execute_action(actions) |
| 49 | + return {"stdout": buffer.getvalue(), "record": _serialize_record(record)} |
| 50 | + |
| 51 | + |
| 52 | +def _tool_run_action_files(arguments: Dict[str, Any]) -> Any: |
| 53 | + from je_web_runner.utils.executor.action_executor import execute_files |
| 54 | + files = arguments.get("files") |
| 55 | + if not isinstance(files, list): |
| 56 | + raise McpServerError("'files' must be a list of file paths") |
| 57 | + if not all(isinstance(path, str) for path in files): |
| 58 | + raise McpServerError("each entry in 'files' must be a string path") |
| 59 | + buffer = io.StringIO() |
| 60 | + with redirect_stdout(buffer): |
| 61 | + results = execute_files(files) |
| 62 | + return { |
| 63 | + "stdout": buffer.getvalue(), |
| 64 | + "records": [_serialize_record(record) for record in results], |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +def _tool_list_commands(_arguments: Dict[str, Any]) -> Any: |
| 69 | + from je_web_runner.utils.executor.action_executor import executor |
| 70 | + return sorted(name for name in executor.event_dict if name.startswith("WR_")) |
| 71 | + |
| 72 | + |
| 73 | +def build_browser_tools() -> List[Tool]: |
| 74 | + """Return the browser-execution MCP tools.""" |
| 75 | + return [ |
| 76 | + Tool( |
| 77 | + name="webrunner_run_actions", |
| 78 | + description=( |
| 79 | + "Execute a WebRunner action list against a real browser. Each" |
| 80 | + " entry is [command_name, params] where params is a dict of" |
| 81 | + " kwargs or a list of positional args. Common commands:" |
| 82 | + " WR_get_webdriver_manager, WR_to_url, WR_send_keys," |
| 83 | + " WR_click_element, WR_pw_launch, WR_pw_to_url, WR_quit." |
| 84 | + " Returns {'stdout': str, 'record': {action_repr: result}}." |
| 85 | + ), |
| 86 | + input_schema={ |
| 87 | + "type": "object", |
| 88 | + "properties": {"actions": {"type": "array"}}, |
| 89 | + "required": ["actions"], |
| 90 | + }, |
| 91 | + handler=_tool_run_actions, |
| 92 | + ), |
| 93 | + Tool( |
| 94 | + name="webrunner_run_action_files", |
| 95 | + description=( |
| 96 | + "Read one or more JSON action files from disk and execute" |
| 97 | + " them sequentially against a real browser. Returns" |
| 98 | + " {'stdout': str, 'records': [<per-file record>]}." |
| 99 | + ), |
| 100 | + input_schema={ |
| 101 | + "type": "object", |
| 102 | + "properties": { |
| 103 | + "files": {"type": "array", "items": {"type": "string"}}, |
| 104 | + }, |
| 105 | + "required": ["files"], |
| 106 | + }, |
| 107 | + handler=_tool_run_action_files, |
| 108 | + ), |
| 109 | + Tool( |
| 110 | + name="webrunner_list_commands", |
| 111 | + description=( |
| 112 | + "Return every WR_* command currently registered in the" |
| 113 | + " executor, so a caller can discover the action surface" |
| 114 | + " before composing webrunner_run_actions payloads." |
| 115 | + ), |
| 116 | + input_schema={"type": "object", "properties": {}}, |
| 117 | + handler=_tool_list_commands, |
| 118 | + ), |
| 119 | + ] |
0 commit comments