mcp_browser library

mcp_browser — Universal Web Automation Backbone.

Public surface re-exports the 4-Primitive Contract types from mcp_bundle plus the runtime modules implemented in this package.

Classes

AuditTrail
In-memory ring-buffered audit trail with redaction and a pluggable sink.
Auth0Helper
AuthProfileStore
Storage + lifecycle for browser auth profiles. Implements BrowserAuthProfilePort; profile injection into a live context is handled by applyProfileTo (top-level helper, kept separate so the store remains BrowserRuntime-agnostic).
BingSearchAdapter
BraveSearchAdapter
BrowserAction
A state-changing command targeting a browser context.
BrowserActionResult
Outcome of execute(BrowserAction).
BrowserAuditPort
Contract surfaced to the browser runtime.
BrowserAuditQuery
Query filter for audit retrieval.
BrowserAuditRecord
Immutable record of an auditable browser operation.
BrowserAuditSink
Persistence contract for BrowserAuditPort implementations.
BrowserAuthProfile
A bundle of credentials that can be injected into a browser context to impersonate a real user. Treated as immutable; refresh produces a new instance.
BrowserAuthProfileMeta
Lightweight metadata for AuthProfileStore.list — omits credential bytes.
BrowserAuthProfilePort
Storage and injection of BrowserAuthProfile instances.
BrowserContextHandle
Live handle to an engine-managed browser context.
BrowserContextPort
Lifecycle surface for browser contexts.
BrowserContextSpec
Request to acquire a browser context.
BrowserCookie
HTTP cookie that may be injected into a context.
BrowserCrawlPolicy
Crawl configuration.
BrowserCrawlProgressEvent
Emitted by CrawlScheduler during a run.
BrowserDescriptor
Top-level catalogue returned by BrowserRuntime.describe().
BrowserDownloadDescriptor
Persistable record of a single download attempt.
BrowserDownloadEvent
Progress / lifecycle event emitted while downloads are in flight.
BrowserDownloadPort
Surface for triggering and observing file downloads.
BrowserDownloadSpec
Identifier carriers for a download request. Either url (direct fetch) or contextId + trigger (browser-initiated) — direct fetch is the Phase 2 path; trigger mode is reserved for Phase 4.
BrowserEnginePort
Engine-side surface of the 4-Primitive Contract.
BrowserEvent
Event delivered by a subscribe() stream.
BrowserExtractionTemplate
Extraction template — mapping selectors to output fields with optional post-transforms and an output schema.
BrowserExtractionTemplateMeta
Lightweight metadata for listing templates without decoding every blob.
BrowserExtractionTemplatePort
Storage and evaluation surface for BrowserExtractionTemplate.
BrowserMonitorEvent
BrowserOperation
A single browser-side operation preset exposed by mcp_browser.
BrowserOperations
Built-in operation registry — 9 presets covering view, audit, search, extract, crawl, monitor, download, submit, and multi-actor compare.
BrowserOutputSchema
Minimal output schema — a required field list and a name→type map. Types: 'string', 'int', 'double', 'bool', 'array', 'object'.
BrowserPayloadEnvelope
Result of read() — bytes/text plus metadata.
BrowserPolicyDecision
Policy decision returned by BrowserPolicyPort.evaluate.
BrowserPolicyPort
Contract for evaluating browser actions against URL/quota/robots policy.
BrowserReadSpec
Specification of a non-mutating read against a page.
BrowserRedactionPolicy
Policy for masking sensitive fields before persisting an audit record.
BrowserResourceCaps
Default per-context resource caps. Hosts may override.
BrowserRuntime
Aggregator over the four primitives. Wires policy/audit and dispatches read/execute/subscribe to engine adapters via the registry.
BrowserSearchOptions
Options carried into a BrowserSearchPort.search call.
BrowserSearchPort
Search provider adapter. Implementations may be API-backed (Google CSE, Brave API, ...) or browser-backed (SERP scraping). The advertised mode(s) live on describe.
BrowserSearchProviderDescriptor
Self-description of a registered search adapter.
BrowserSearchResult
One search result.
BrowserSelectorRule
Single field selector with extraction and optional transform chain.
BrowserTopic
Topic descriptor passed to subscribe().
BrowserTransformStep
Post-selector transform applied to a named field's value.
BrowserVirusScanPort
Virus scan port — host wires ClamAV / VirusTotal / etc.
BrowserVirusScanResult
CdpClient
CdpConnection
Singleton CDP client shared across engine + context port.
CdpContextPort
CdpEngine
CdpEnginePayload
Engine-side payload — attached target session id + bookkeeping.
CdpEvent
A single CDP event (no id, has method).
ChromiumLauncher
ChromiumProcess
Return value of ChromiumLauncher.spawn.
ContextRegistry
Lifecycle manager for BrowserContextHandle instances.
CrawlHandle
Handle returned from CrawlScheduler.start. Hosts use it to observe progress and control lifecycle.
CrawlScheduler
Orchestrates crawl + monitor runs against a host-provided navigate callback. Honors policy, robots.txt, per-domain rate limits, and content-hash deduplication.
DomainQuotaTracker
Tracks per-domain request count and download volume per UTC day.
DownloadManager
File-system + KV backed implementation of BrowserDownloadPort.
DuckDuckGoSearchAdapter
EngineDescriptor
Self-description of a registered engine adapter.
EngineRegistry
In-process registry of engine adapters.
ExtractionRegistry
Registry-backed implementation of BrowserExtractionTemplatePort.
FileAuditSink
BrowserAuditSink implementation that appends JSONL records to a file. Rotation kicks in when the active file exceeds maxBytesPerFile: the current file is renamed to <base>.<n> and a fresh active file is opened.
FirebaseAuthHelper
Frontier
In-memory frontier. Lower priority wins; ties broken by insertion order.
FrontierItem
GoogleCseSearchAdapter
HarReplayFetcher
Replay fetcher that serves HTTP responses recorded in a HAR 1.2 file.
HttpFetcher
Streaming HTTP fetcher.
HttpFetchResponse
Result of a single fetch.
InMemoryAuditSink
In-memory sink suitable for tests and small deployments.
InMemoryKvStoragePort
In-memory KV storage for testing.
InMemoryStoragePort<T>
In-memory typed storage for testing.
IoHttpFetcher
dart:io backed implementation. Re-uses a single HttpClient.
KagiSearchAdapter
KvAuditSink
BrowserAuditSink implementation that persists records through a KvStoragePort. Keys are composed as <prefix><iso8601>/<id> so that a prefix scan yields chronological order.
KvStoragePort
Key-value storage port.
MatrixCell
Per-cell result of MatrixRunner.run.
MatrixRunner
Executes a MatrixSpec against a live BrowserRuntime + ContextRegistry.
MatrixSpec
Specification for a single matrix run.
McpIntegration
Bridges BrowserOperations to a host MCP server via host-supplied registration callbacks. The host is free to back the callbacks with mcp_server.Server or any compatible surface.
MonitorHandle
Handle for a periodic monitor (single URL change watcher).
OAuthFlowRunner
Drives a single OAuth authorization flow inside a transient browser context.
PolicyEngine
PolicyEngine evaluates state-changing actions against URL rules, domain quotas, resource caps, optional reputation lookups, and (for crawl) robots.txt.
RedactionOutcome
Result of a BrowserRedactionPolicy.redact call.
ReputationPort
Optional reputation/safety lookup. Hosts may wire in URLhaus, VirusTotal, or similar.
RobotsCache
Time-bounded cache for robots.txt per origin.
RobotsFetcher
Fetcher contract for robots.txt. Hosts provide an HTTP-backed implementation; tests pass a fake.
RobotsTxt
Parsed view of a robots.txt for a single origin.
SearchCache
In-memory + optional KV-backed result cache.
SearchRouter
Router over registered BrowserSearchPort adapters with caching and mode validation.
SearxngSearchAdapter
SecretBox
StoragePort<T>
Generic storage port for typed entities.
SupabaseAuthHelper
TransformRegistry
Registry of named transforms. Construct with TransformRegistry.defaults for the built-in set and register/override additional ones.
UrlAccessRules
URL allow/deny rules. When the allow list is empty, the default is to allow all URLs not matched by deny rules. When non-empty, the default is to deny anything not matched by an allow rule.
Viewport
Single viewport dimension.

Enums

AuthApplyPhase
Which parts of a profile applyProfileTo seeds.
BrowserActionKind
Kind of state-changing browser action.
BrowserAuditEntryType
Discriminator for the audit entry kind.
BrowserCrawlEventKind
Reason a page was skipped (or visited).
BrowserCrawlState
Lifecycle of a BrowserCrawlHandle analogue.
BrowserDedupStrategy
Deduplication strategy during a crawl.
BrowserDownloadStatus
Lifecycle state of a download.
BrowserMonitorEventKind
Emitted by a monitor when the observed URL changes or fails.
BrowserReadKind
Kind of read extraction.
BrowserSearchIntent
Search intent / vertical.
BrowserSearchMode
Mode an adapter uses to talk to a search provider.
BrowserSelectorMode
Selector dialect used by BrowserSelectorRule.
BrowserTopicKind
Discriminator for subscribable streams.
ContextLifecycleState
Lifecycle state of a BrowserContextHandle.
EngineCapability
Capability flags an engine adapter advertises.

Functions

applyProfileTo({required BrowserContextHandle handle, required BrowserAuthProfile profile, required BrowserEnginePort engine, required BrowserContextPort contextPort, AuthApplyPhase phase = AuthApplyPhase.all}) → Future<void>
Apply profile to handle using engine + contextPort.
ddgDecode(String value) → String
Tiny helper so the file doesn't need dart:convert import noise for single-use base64 work. Exposed for tests.
sha256HexOf(List<int> bytes) → String
Helper: SHA-256 hex digest of bytes.
sha256HexOfText(String text) → String
Helper: SHA-256 hex digest of text encoded as UTF-8.

Typedefs

BrowserAuthRefreshCallback = Future<BrowserAuthProfile> Function(BrowserAuthProfile expired)
Refresh callback signature. Implementations may consult an IdP to mint a new profile carrying fresh credentials. May throw on failure.
DownloadAuditTrail = AuditTrail
Compatibility re-exports kept light so test files can stay in package scope.
DownloadPolicyEngine = PolicyEngine
IngestForwarder = Future<void> Function(BrowserPayloadEnvelope envelope)
Forward callback for mcp_ingest hand-off. Hosts wire it to feed read() envelopes into the ingest pipeline. Failures inside this callback are logged but never block the read result.
McpResourceRegistrar = void Function(String uri, Future reader())
Callback that registers a single MCP resource with the host server.
McpToolRegistrar = void Function(String name, {required String description, required bool destructive, required Future<Map<String, dynamic>> handler(Map<String, dynamic> args), required bool readOnly})
Callback that registers a single MCP tool with the host server.
Callback injected by the host: fetch a URL and return its envelope.
Transform = dynamic Function(dynamic input, Map<String, dynamic> context)
Signature of a transform. input is the current value (may be null when a previous transform produced null). context carries page-level data such as pageUrl. Throws on invalid input — the registry catches and keeps the original value, per DDD 07-extraction §6.

Exceptions / Errors

AuthExpiredError
Error thrown when an expired profile cannot be refreshed.
AuthInjectionFailedError
Error thrown when applying a profile to a context fails at the engine.
AuthProfileNotFoundError
Error thrown when no profile exists for (tenantId, id).
BrowserExtractionSchemaError
Error thrown when a template's output fails schema validation.
CdpError
Error thrown when CDP returns an error payload.
ContextLimitExceededError
Error thrown when ContextRegistry.acquire cannot satisfy the concurrency cap within the configured timeout.
ContextNotFoundError
Error thrown when a BrowserContextHandle cannot be located.
CrawlDomainBlacklistedError
Error mapped to E7003 — seed domain on deny list.
CrawlPolicyInvalidError
Error mapped to E7001 — invalid crawl policy.
DownloadFailedError
Error mapped to E8001 — fetch / disk failure during download.
DownloadQuarantinedError
Error mapped to E8002 — virus scan rejected the file (it has been quarantined; the descriptor reports the quarantine path).
EngineNotRegisteredError
Error thrown when an engine identifier cannot be resolved.
ExtractionTemplateInvalidError
Error thrown on invalid template inputs (missing id/version, malformed selector rules, etc.).
HarParseError
Error thrown when the underlying HAR document is not a HAR 1.2 file or the structure is malformed.
OAuthFlowError
Error thrown for any OAuth failure (timeout, exchange exception, missing context). Maps to SDD §6.2 E4003.
SearchProviderNotRegisteredError
Error thrown when a provider id is missing or doesn't support the requested mode. Maps to E6001.
SearchProviderRateLimitException
Marker interface adapters may implement to opt into the router's rate-limit handling (otherwise plain exceptions are passed through).
SearchRateLimitedError
Error thrown when an external provider rate-limited us. Maps to E6002.
SearchSerpParseError
Error thrown when browser-mode SERP parsing fails. Maps to E6003.