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
fix(browser-management): make get_instance_state work again
JosueM110955962426cc7c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f912c3d..0fc55f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.The format is based on Keep a Changelog and adheres to Semantic Versioning where practical.+## [Unreleased]+### Fixed+- **`get_instance_state()` always failed** with `'list' object has no attribute 'get'`. nodriver returns `Network.getCookies` results as a list of `Cookie` dataclasses, but `get_page_state` treated the value as the raw JSON dict. Cookies are now normalized to plain dicts and both shapes are accepted. The `viewport` and storage-key reads also came back deep-serialized instead of as plain values; they are now read through `JSON.stringify` in the page, and storage access errors on opaque origins no longer abort the call.+## [0.2.5] - 2026-02-10### Fixed- **MCP JSON-RPC Protocol Corruption** - All debug `print()` calls redirected from stdout to stderr, fixing tool hangs after `spawn_browser` and `navigate` (#8)diff --git a/src/browser_manager.py b/src/browser_manager.pyindex 85ea493..3d7ab36 100644--- a/src/browser_manager.py+++ b/src/browser_manager.py@@ -1,5 +1,6 @@"""Browser instance management with nodriver."""+import jsonimport asyncioimport osimport sys@@ -1072,6 +1073,57 @@ class BrowserManager:instance.title = titleawait self.touch_instance(instance_id)+ @staticmethod+ async def _evaluate_json(tab: Any, expression: str) -> Any:+ """+ Evaluate an expression and return its value as plain Python data.++ ``Tab.evaluate`` always sends CDP serialization options, so Chrome ignores+ ``returnByValue`` and objects come back as deep-serialized property lists.+ Stringifying inside the page and parsing here sidesteps that.++ Args:+ tab (Any): The nodriver tab.+ expression (str): A JavaScript expression producing a JSON-serializable value.++ Returns:+ Any: The decoded value, or None if the page returned nothing.+ """+ raw = await tab.evaluate(f"JSON.stringify(({expression}))")+ if raw is None or not isinstance(raw, str):+ return None+ return json.loads(raw)++ @staticmethod+ def _cookies_to_dicts(raw: Any) -> List[Dict[str, Any]]:+ """+ Normalize the result of ``Network.getCookies`` into plain dicts.++ nodriver parses the CDP response into ``cdp.network.Cookie`` dataclasses+ and returns them as a list. Older code expected the raw JSON dict with a+ ``cookies`` key, so both shapes are accepted here.++ Args:+ raw (Any): A list of Cookie objects or dicts, or a dict with a+ ``cookies`` key, or None.++ Returns:+ List[Dict[str, Any]]: Cookies as JSON-serializable dicts.+ """+ if raw is None:+ return []+ if isinstance(raw, dict):+ raw = raw.get('cookies', [])+ cookies: List[Dict[str, Any]] = []+ for cookie in raw:+ if isinstance(cookie, dict):+ cookies.append(cookie)+ elif hasattr(cookie, 'to_json'):+ cookies.append(cookie.to_json())+ else:+ cookies.append(dict(vars(cookie)))+ return cookies+async def get_page_state(self, instance_id: str) -> Optional[PageState]:"""Get complete page state for an instance.@@ -1091,25 +1143,25 @@ class BrowserManager:title = await tab.evaluate("document.title")ready_state = await tab.evaluate("document.readyState")- cookies = await tab.send(uc.cdp.network.get_cookies())+ cookies = self._cookies_to_dicts(await tab.send(uc.cdp.network.get_cookies()))local_storage = {}session_storage = {}try:- local_storage_keys = await tab.evaluate("Object.keys(localStorage)")- for key in local_storage_keys:+ local_storage_keys = await self._evaluate_json(tab, "Object.keys(localStorage)")+ for key in local_storage_keys or []:value = await tab.evaluate(f"localStorage.getItem('{key}')")local_storage[key] = value- session_storage_keys = await tab.evaluate("Object.keys(sessionStorage)")- for key in session_storage_keys:+ session_storage_keys = await self._evaluate_json(tab, "Object.keys(sessionStorage)")+ for key in session_storage_keys or []:value = await tab.evaluate(f"sessionStorage.getItem('{key}')")session_storage[key] = valueexcept Exception:pass- viewport = await tab.evaluate("""+ viewport = await self._evaluate_json(tab, """({width: window.innerWidth,height: window.innerHeight,@@ -1122,10 +1174,10 @@ class BrowserManager:url=url,title=title,ready_state=ready_state,- cookies=cookies.get('cookies', []),+ cookies=cookies,local_storage=local_storage,session_storage=session_storage,- viewport=viewport+ viewport=viewport or {})except Exception as e:diff --git a/tests/test_page_state.py b/tests/test_page_state.pynew file mode 100644index 0000000..6370d7a--- /dev/null+++ b/tests/test_page_state.py@@ -0,0 +1,164 @@+import asyncio+import os+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "src"))++import nodriver as uc++from browser_manager import BrowserManager+from models import PageState++RUN_BROWSER_TESTS = os.getenv("STEALTH_BROWSER_TESTS", "").strip().lower() in {+ "1",+ "true",+ "yes",+}++HEADLESS_USER_AGENT = (+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"+)++SAMPLE_COOKIE_JSON = {+ "name": "session",+ "value": "abc123",+ "domain": "example.com",+ "path": "/",+ "expires": -1,+ "size": 13,+ "httpOnly": True,+ "secure": True,+ "session": True,+ "priority": "Medium",+ "sameParty": False,+ "sourceScheme": "Secure",+ "sourcePort": 443,+}+++class FakeTab:+ """Stand-in tab that answers evaluate() from a table and send() with a fixed value."""++ def __init__(self, send_result):+ self.send_result = send_result+ self.evaluations = {+ "window.location.href": "https://example.com/",+ "document.title": "Example Domain",+ "document.readyState": "complete",+ "Object.keys(localStorage)": [],+ "Object.keys(sessionStorage)": [],+ }++ async def send(self, command):+ # Drain the generator the way nodriver's Connection.send does, then+ # hand back whatever shape the test wants get_page_state to receive.+ try:+ next(command)+ except StopIteration:+ pass+ return self.send_result++ async def evaluate(self, expression, *args, **kwargs):+ import json++ if expression.startswith("JSON.stringify("):+ inner = expression[len("JSON.stringify("):-1].strip()+ while inner.startswith("(") and inner.endswith(")"):+ inner = inner[1:-1].strip()+ if inner.startswith("{"):+ return json.dumps({"width": 1920, "height": 1080, "devicePixelRatio": 1})+ return json.dumps(self.evaluations.get(inner))+ return self.evaluations.get(expression)+++def _manager_with_tab(tab):+ manager = BrowserManager()++ async def get_tab(instance_id):+ return tab++ manager.get_tab = get_tab+ return manager+++class CookiesToDictsTests(unittest.TestCase):+ def test_list_of_cookie_dataclasses(self):+ cookie = uc.cdp.network.Cookie.from_json(SAMPLE_COOKIE_JSON)+ result = BrowserManager._cookies_to_dicts([cookie])+ self.assertEqual(len(result), 1)+ self.assertIsInstance(result[0], dict)+ self.assertEqual(result[0]["name"], "session")+ self.assertEqual(result[0]["value"], "abc123")++ def test_raw_json_dict_shape(self):+ result = BrowserManager._cookies_to_dicts({"cookies": [SAMPLE_COOKIE_JSON]})+ self.assertEqual(result, [SAMPLE_COOKIE_JSON])++ def test_list_of_dicts_passes_through(self):+ result = BrowserManager._cookies_to_dicts([SAMPLE_COOKIE_JSON])+ self.assertEqual(result, [SAMPLE_COOKIE_JSON])++ def test_none_and_empty(self):+ self.assertEqual(BrowserManager._cookies_to_dicts(None), [])+ self.assertEqual(BrowserManager._cookies_to_dicts([]), [])+ self.assertEqual(BrowserManager._cookies_to_dicts({}), [])+++class GetPageStateTests(unittest.TestCase):+ def test_page_state_with_cookie_dataclasses(self):+ cookie = uc.cdp.network.Cookie.from_json(SAMPLE_COOKIE_JSON)+ manager = _manager_with_tab(FakeTab([cookie]))++ state = asyncio.run(manager.get_page_state("instance-1"))++ self.assertIsInstance(state, PageState)+ self.assertEqual(state.url, "https://example.com/")+ self.assertEqual(state.title, "Example Domain")+ self.assertEqual(state.ready_state, "complete")+ self.assertEqual(state.cookies[0]["name"], "session")+ self.assertEqual(state.viewport["width"], 1920)++ def test_page_state_with_legacy_dict_shape(self):+ manager = _manager_with_tab(FakeTab({"cookies": [SAMPLE_COOKIE_JSON]}))++ state = asyncio.run(manager.get_page_state("instance-1"))++ self.assertEqual(state.cookies, [SAMPLE_COOKIE_JSON])+++ RUN_BROWSER_TESTS,+ "Set STEALTH_BROWSER_TESTS=1 to run tests that launch a real browser.",+)+class GetPageStateBrowserTests(unittest.TestCase):+ def test_real_page_state(self):+ from models import BrowserOptions++ async def run():+ manager = BrowserManager()+ instance = await manager.spawn_browser(+ BrowserOptions(headless=True, user_agent=HEADLESS_USER_AGENT)+ )+ try:+ await manager.navigate(+ instance.instance_id,+ "data:text/html,<title>state-test</title><p>hi</p>",+ )+ return await manager.get_page_state(instance.instance_id)+ finally:+ await manager.close_instance(instance.instance_id)++ state = asyncio.run(run())++ self.assertIsInstance(state, PageState)+ self.assertEqual(state.title, "state-test")+ self.assertEqual(state.ready_state, "complete")+ self.assertIsInstance(state.cookies, list)+++if __name__ == "__main__":+ unittest.main()