Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.
Python ai-agent-toolsai-toolsanthropicanti-bot-bypassautomation-toolsbrowser-automationchrome-devtoolsclaude-mcpcloudflare-bypassdeveloper-toolsfastmcpmcp-servermodel-context-protocolnetwork-interceptionnodriverpythonstealth-browserundetectable-browserweb-automationweb-scraping
Guard stdio transport from stray stdout and bound script results
Vibhek Soni2bebd82a9239
diff --git a/src/server.py b/src/server.pyindex b5ad386..17c6a34 100644--- a/src/server.py+++ b/src/server.py@@ -42,6 +42,7 @@ from dynamic_hook_ai_interface import dynamic_hook_aifrom persistent_storage import persistent_storagefrom progressive_element_cloner import progressive_element_clonerfrom response_handler import response_handler+from stdio_guard import install_stdio_guardfrom platform_utils import validate_browser_environment, get_platform_infofrom process_cleanup import process_cleanup@@ -711,9 +712,10 @@ async def execute_script(raise Exception(f"Instance not found: {instance_id}")try:result = await dom_handler.execute_script(tab, script, args)+ bounded = response_handler.handle_response(result, "script_result")return {"success": True,- "result": result,+ "result": bounded,"error": None}except Exception as e:@@ -2995,4 +2997,5 @@ if __name__ == "__main__":if args.transport == "http":mcp.run(transport="http", host=args.host, port=args.port)else:+ install_stdio_guard()mcp.run(transport="stdio")diff --git a/src/stdio_guard.py b/src/stdio_guard.pynew file mode 100644index 0000000..e65ad52--- /dev/null+++ b/src/stdio_guard.py@@ -0,0 +1,117 @@+"""Guard the MCP stdio transport against stray stdout writes.++Under stdio transport, file descriptor 1 is the JSON-RPC channel. Any+Python-level print() from this repo or a third-party dependency (nodriver+included) lands on that channel, corrupts the protocol framing, and makes+the client drop the connection to protect itself.++Install the guard right before starting the stdio transport. After that,+print() goes to stderr while the transport keeps working, because the+transport wraps the saved stdout buffer, not the replaced sys.stdout.+"""++import sys+from typing import Optional+++class TransportSafeStdout:+ """sys.stdout replacement that keeps the stdio transport intact.++ Write calls are routed to stderr. The ``buffer`` attribute still+ exposes the original stdout buffer, so the MCP stdio server, which+ wraps ``sys.stdout.buffer`` at startup, keeps writing framed+ JSON-RPC messages to the real transport.+ """++ def __init__(self, real_stdout):+ """Keep the original stdout and expose its buffer to the transport."""+ self._real_stdout = real_stdout+ try:+ self._transport_buffer = real_stdout.buffer+ except Exception:+ self._transport_buffer = None++ @property+ def buffer(self):+ """Return the original stdout buffer used by the MCP transport."""+ return self._transport_buffer++ def write(self, data) -> int:+ """Route text writes to stderr so stdout stays protocol-clean."""+ try:+ return sys.stderr.write(data)+ except Exception:+ try:+ return len(data)+ except Exception:+ return 0++ def writelines(self, lines) -> None:+ """Route multi-line writes to stderr."""+ for line in lines:+ self.write(line)++ def flush(self) -> None:+ """Flush stderr."""+ try:+ sys.stderr.flush()+ except Exception:+ pass++ @property+ def encoding(self) -> str:+ """Report the original stdout encoding."""+ return getattr(self._real_stdout, "encoding", "utf-8")++ @property+ def errors(self) -> str:+ """Report the original stdout error handling."""+ return getattr(self._real_stdout, "errors", "strict")++ def isatty(self) -> bool:+ """Never claim a terminal; the transport pipe is not interactive."""+ return False++ def fileno(self) -> int:+ """Return the original stdout file descriptor."""+ return self._real_stdout.fileno()++ def __getattr__(self, name):+ """Delegate anything else to the original stdout object."""+ return getattr(object.__getattribute__(self, "_real_stdout"), name)+++_guard_installed = False+++def install_stdio_guard() -> bool:+ """Replace sys.stdout with the transport-safe proxy.++ Returns:+ bool: True when the guard was installed, False when stdout has+ no usable buffer or the guard is already active.+ """+ global _guard_installed+ if _guard_installed:+ return False+ real_stdout = sys.stdout+ if real_stdout is None or isinstance(real_stdout, TransportSafeStdout):+ return False+ if getattr(real_stdout, "buffer", None) is None:+ return False+ sys.stdout = TransportSafeStdout(real_stdout)+ _guard_installed = True+ return True+++def is_guard_active() -> bool:+ """Check whether the stdio guard is currently installed."""+ return _guard_installed and isinstance(sys.stdout, TransportSafeStdout)+++def reset_stdio_guard_for_tests(original_stdout: Optional[object] = None) -> None:+ """Restore stdout after a test. Test helper only, not runtime code."""+ global _guard_installed+ if original_stdout is not None:+ sys.stdout = original_stdout+ _guard_installed = Falsediff --git a/tests/test_stdio_guard.py b/tests/test_stdio_guard.pynew file mode 100644index 0000000..838084e--- /dev/null+++ b/tests/test_stdio_guard.py@@ -0,0 +1,70 @@+import io+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "src"))++from response_handler import ResponseHandler+from stdio_guard import install_stdio_guard, is_guard_active, reset_stdio_guard_for_tests+++class FakeStdout:+ def __init__(self):+ self.buffer = io.BytesIO(b"transport")+ self.written = []++ def write(self, data):+ self.written.append(data)+ return len(data)++ def flush(self):+ pass+++class FakeStderr:+ def __init__(self):+ self.written = []++ def write(self, data):+ self.written.append(data)+ return len(data)++ def flush(self):+ pass+++class StdioGuardTests(unittest.TestCase):+ def test_stray_print_goes_to_stderr_and_transport_buffer_survives(self):+ real_stdout = sys.stdout+ real_stderr = sys.stderr+ fake_stdout = FakeStdout()+ fake_stderr = FakeStderr()+ sys.stdout = fake_stdout+ sys.stderr = fake_stderr+ try:+ self.assertTrue(install_stdio_guard())+ self.assertTrue(is_guard_active())+ self.assertFalse(install_stdio_guard())+ self.assertIs(sys.stdout.buffer, fake_stdout.buffer)+ print("dependency leak")+ self.assertEqual(fake_stdout.written, [])+ self.assertIn("dependency leak", "".join(fake_stderr.written))+ finally:+ reset_stdio_guard_for_tests(real_stdout)+ sys.stderr = real_stderr+ self.assertFalse(is_guard_active())++ def test_large_tool_result_spills_to_file_instead_of_inline(self):+ import tempfile++ with tempfile.TemporaryDirectory() as clone_dir:+ handler = ResponseHandler(max_tokens=1, clone_dir=clone_dir)+ result = handler.handle_response("x" * 1000, "script_result")+ self.assertIn("file_path", result)+ self.assertIn("reason", result)+++if __name__ == "__main__":+ unittest.main()