Skip to main content

Type safe generator/client library for CDP

Project description

CDP Use

A type-safe Python client generator for the Chrome DevTools Protocol (CDP). This library automatically generates Python bindings with full TypeScript-like type safety from the official CDP protocol specifications.

๐Ÿš€ Features

  • ๐Ÿ”’ Type Safety: Full type hints with TypedDict classes for all CDP commands, parameters, and return types
  • ๐ŸŽฏ Event Registration: Typesafe event handlers with full IDE support
  • ๐Ÿ—๏ธ Auto-Generated: Code generated directly from official Chrome DevTools Protocol specifications
  • ๐ŸŽฏ IntelliSense Support: Perfect IDE autocompletion and type checking
  • ๐Ÿ“ฆ Domain Separation: Clean organization with separate modules for each CDP domain
  • ๐Ÿ”„ Always Up-to-Date: Easy regeneration from latest protocol specs

๐Ÿ› ๏ธ Installation & Setup

  1. Clone and install dependencies:
git clone https://github.com/browser-use/cdp-use
cd cdp-use
uv sync  # or pip install -r requirements.txt
  1. Generate the CDP client library:
python -m cdp_use.generator

This automatically downloads the latest protocol specifications and generates all type-safe bindings.

๐Ÿ“– Usage Examples

Basic Usage

import asyncio
from cdp_use.client import CDPClient

async def main():
    # Connect to Chrome DevTools
    async with CDPClient("ws://localhost:9222/devtools/browser/...") as cdp:
        # Get all browser targets with full type safety
        targets = await cdp.send.Target.getTargets()
        print(f"Found {len(targets['targetInfos'])} targets")

        # Navigate to a page
        await cdp.send.Page.navigate({"url": "https://example.com"})

asyncio.run(main())

Type Safety in Action

# โœ… Fully typed parameters
await cdp.send.Runtime.evaluate(params={
    "expression": "document.title",
    "returnByValue": True
})

# โœ… Return types are fully typed
result = await cdp.send.DOM.getDocument(params={"depth": 1})
node_id: int = result["root"]["nodeId"]  # Full IntelliSense support

# โŒ Type errors caught at development time
await cdp.send.DOM.getDocument(params={"invalid": "param"})  # Type error!

๐ŸŽง Event Registration

The library provides typesafe event registration with full IDE support:

Basic Event Registration

import asyncio
from cdp_use.client import CDPClient
from cdp_use.cdp.page.events import FrameAttachedEvent, DomContentEventFiredEvent
from cdp_use.cdp.runtime.events import ConsoleAPICalledEvent
from typing import Optional

def on_frame_attached(event: FrameAttachedEvent, session_id: Optional[str]) -> None:
    print(f"Frame {event['frameId']} attached to {event['parentFrameId']}")

def on_dom_content_loaded(event: DomContentEventFiredEvent, session_id: Optional[str]) -> None:
    print(f"DOM content loaded at: {event['timestamp']}")

def on_console_message(event: ConsoleAPICalledEvent, session_id: Optional[str]) -> None:
    print(f"Console: {event['type']}")

async def main():
    async with CDPClient("ws://localhost:9222/devtools/page/...") as client:
        # Register event handlers with camelCase method names (matching CDP)
        client.register.Page.frameAttached(on_frame_attached)
        client.register.Page.domContentEventFired(on_dom_content_loaded)
        client.register.Runtime.consoleAPICalled(on_console_message)

        # Enable domains to start receiving events
        await client.send.Page.enable()
        await client.send.Runtime.enable()

        # Navigate and receive events
        await client.send.Page.navigate({"url": "https://example.com"})
        await asyncio.sleep(5)  # Keep listening for events

Event Registration Features

โœ… Type Safety: Event handlers are validated at compile time
โœ… IDE Support: Full autocomplete for domains and event methods
โœ… Parameter Validation: Callback signatures are type-checked
โœ… Event Type Definitions: Each event has its own TypedDict interface

Registration Syntax

client.register.Domain.eventName(callback_function)

Where:

  • Domain is any CDP domain (Page, Runtime, Network, etc.)
  • eventName is the camelCase CDP event name (matching CDP specs)
  • callback_function must accept (event_data, session_id) parameters

Available Event Domains

  • Page: client.register.Page.* - Page lifecycle, navigation, frames
  • Runtime: client.register.Runtime.* - JavaScript execution, console, exceptions
  • Network: client.register.Network.* - HTTP requests, responses, WebSocket
  • DOM: client.register.DOM.* - DOM tree changes, attributes
  • CSS: client.register.CSS.* - Stylesheet changes, media queries
  • Debugger: client.register.Debugger.* - Breakpoints, script parsing
  • Performance: client.register.Performance.* - Performance metrics
  • Security: client.register.Security.* - Security state changes
  • And many more...

Type Safety Examples

โœ… Correct Usage:

def handle_console(event: ConsoleAPICalledEvent, session_id: Optional[str]) -> None:
    print(f"Console: {event['type']}")

client.register.Runtime.consoleAPICalled(handle_console)

โŒ Type Error - Wrong signature:

def bad_handler(event):  # Missing session_id parameter
    pass

client.register.Runtime.consoleAPICalled(bad_handler)  # Type error!

๐Ÿ“‹ What Gets Generated

cdp_use/cdp/
โ”œโ”€โ”€ library.py                    # Main CDPLibrary class
โ”œโ”€โ”€ registry.py                   # Event registry system
โ”œโ”€โ”€ registration_library.py       # Event registration interface
โ”œโ”€โ”€ dom/                          # DOM domain
โ”‚   โ”œโ”€โ”€ types.py                 # DOM-specific types
โ”‚   โ”œโ”€โ”€ commands.py              # Command parameter/return types
โ”‚   โ”œโ”€โ”€ events.py                # Event types
โ”‚   โ”œโ”€โ”€ library.py               # DOMClient class
โ”‚   โ””โ”€โ”€ registration.py          # DOM event registration
โ”œโ”€โ”€ page/                         # Page domain
โ”‚   โ””โ”€โ”€ ...
โ””โ”€โ”€ ... (50+ domains total)

๐Ÿ›๏ธ Architecture

Main Components

class CDPClient:
    def __init__(self, url: str):
        self.send: CDPLibrary                    # Send commands
        self.register: CDPRegistrationLibrary    # Register events

# Domain-specific clients
class CDPLibrary:
    def __init__(self, client: CDPClient):
        self.DOM = DOMClient(client)           # DOM operations
        self.Network = NetworkClient(client)   # Network monitoring
        self.Runtime = RuntimeClient(client)   # JavaScript execution
        # ... 50+ more domains

# Event registration
class CDPRegistrationLibrary:
    def __init__(self, registry: EventRegistry):
        self.Page = PageRegistration(registry)
        self.Runtime = RuntimeRegistration(registry)
        # ... all domains with events

๐Ÿ”ง Development

Regenerating Types

python -m cdp_use.generator

This will:

  1. Download the latest protocol files from Chrome DevTools repository
  2. Generate all Python type definitions and event registrations
  3. Create domain-specific client classes
  4. Format the code

Project Structure

cdp-use/
โ”œโ”€โ”€ cdp_use/
โ”‚   โ”œโ”€โ”€ client.py              # Core CDP WebSocket client
โ”‚   โ”œโ”€โ”€ generator/             # Code generation tools
โ”‚   โ””โ”€โ”€ cdp/                   # Generated CDP library (auto-generated)
โ”œโ”€โ”€ simple.py                  # Example usage
โ””โ”€โ”€ README.md

๐Ÿค Contributing

  1. Fork the repository
  2. Make changes to generator code (not the generated cdp_use/cdp/ directory)
  3. Run python -m cdp_use.generator to regenerate
  4. Test with python simple.py
  5. Submit a pull request

๐Ÿ”— Related


Generated from Chrome DevTools Protocol specifications โ€ข Type-safe โ€ข Zero runtime overhead

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cdp_use-1.4.4.tar.gz (185.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cdp_use-1.4.4-py3-none-any.whl (340.8 kB view details)

Uploaded Python 3

File details

Details for the file cdp_use-1.4.4.tar.gz.

File metadata

  • Download URL: cdp_use-1.4.4.tar.gz
  • Upload date:
  • Size: 185.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.19

File hashes

Hashes for cdp_use-1.4.4.tar.gz
Algorithm Hash digest
SHA256 330a848b517006eb9ad1dc468aa6434d913cf0c6918610760c36c3fdfdba0fab
MD5 0c4d063bfdadd6c3a54b6b32cb7b1d8f
BLAKE2b-256 d6485143e381a6e24f4cc7a678f1c9657ba3e3d0061b79175bb1db987850fb51

See more details on using hashes here.

File details

Details for the file cdp_use-1.4.4-py3-none-any.whl.

File metadata

  • Download URL: cdp_use-1.4.4-py3-none-any.whl
  • Upload date:
  • Size: 340.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.19

File hashes

Hashes for cdp_use-1.4.4-py3-none-any.whl
Algorithm Hash digest
SHA256 e37e80e067db2653d6fdf953d4ff9e5d80d75daa27b7c6d48c0261cccbef73e1
MD5 496d71578207a64c2215b635be67906e
BLAKE2b-256 68dbb97d06a6032d63808636f84b7d0dc0eb3bff79a61471ea8eab8a11a293f7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page