@fetchproxy/server
v3.8.0
Published
Localhost WebSocket bridge an MCP server uses to relay fetches through the user's signed-in browser via the fetchproxy extension.
Readme
@fetchproxy/server
Node library MCP servers depend on to relay HTTP through the user's signed-in browser via the fetchproxy browser extension, ContextMint Bridge.
┌────────────────────┐
MCP request │ FetchproxyServer │ ws://127.0.0.1:37149 ┌─────────────┐
────────────▶ │ • host or peer │ ──────────────────────▶ │ fetchproxy │
│ • crypto + routing│ │ extension │
└────────────────────┘ └──────┬──────┘
│ fetch()
▼
signed-in tab
on declared domainFetchproxyServer is the only export most callers need. Construct it with a server name, version, and a non-empty domains array; call listen() once at startup; then issue requests with the verb shortcuts (get, post, getJson, postJson, getHtml) or raw fetch(). Call close() on shutdown.
The library handles host/peer election automatically — the first MCP to call listen() binds the port and routes frames for everyone else. Identity keys live on disk at ~/.fetchproxy/identity/<serverName>.json so trust survives restarts.
See the top-level README for the full picture: extension install, architecture, threat model.
Install
npm install @fetchproxy/serverThe user also needs the fetchproxy browser extension, ContextMint Bridge, installed — download it from the contextmint-bridge releases; see the top-level README.
Quickstart
import { FetchproxyServer } from '@fetchproxy/server';
const fp = new FetchproxyServer({
serverName: 'opentable-mcp',
version: '0.10.0',
domains: ['opentable.com'],
});
await fp.listen();
// First run prints a pair code to stderr; the user approves it in the
// extension popup. Same identity → same code, every restart.
const html = await fp.getHtml('/user/dining-dashboard', { subdomain: 'www' });
// fetched from https://www.opentable.com/user/dining-dashboard
// through the signed-in opentable.com tab.
const data = await fp.postJson('/dapi/fe/gql', {
operationName: 'Autocomplete',
variables: { term: 'state of confusion' },
}, { subdomain: 'www' });
await fp.close();Server options
Every public field on FetchproxyServerOpts at a glance — defaults
plus a one-liner on what each option does. The same information is
mirrored as JSDoc on the type itself, so editors and hover help reach
parity with this table. For longer "when to override" guidance, see
Choosing the right options below.
| Option | Type | Default | What it does |
|---|---|---|---|
| serverName | string | — (required) | Stable MCP identifier. Used in the pair popup, identity-key filename, and mcpId. |
| version | string | — (required) | Your MCP's package version. Surfaced in the pair popup. |
| domains | string[] | — (required) | Trust boundary. The extension refuses any fetch outside this set or its subdomains. |
| capabilities | Capability[] | ['fetch'] | Opt-in verb set. Add 'read_cookies' / 'read_local_storage' / 'capture_request_header' / etc. Changing this forces a re-pair. |
| port | number | 37149 (or FETCHPROXY_WS_PORT) | Localhost concentrator port; falls back to FETCHPROXY_WS_PORT when the option is omitted, which is the only route for a @fetchproxy/bootstrap consumer. On one machine every MCP shares the concentrator, so move it for ALL of them or not at all — a port per MCP is meaningful only in a hosted deployment, where a relay agent dials each child and the browser reaches them through a remote target. |
| host | string | '127.0.0.1' (or FETCHPROXY_WS_HOST) | Bind interface. Keep on loopback — the threat model assumes single-user trust. Falls back to FETCHPROXY_WS_HOST (a literal IP only; anything else is ignored) when the option is omitted, which exists for ONE topology: a hosted child in its own network namespace, where the relay agent dials it on a private veth address (see SECURITY.md). |
| identityDir | string | ~/.fetchproxy/identity/ (or FETCHPROXY_IDENTITY_DIR) | Where to store the long-term identity keypair. Falls back to FETCHPROXY_IDENTITY_DIR (an absolute path only; anything else is ignored) when the option is omitted, which is the only route for a @fetchproxy/bootstrap consumer. That exists for ONE topology: a host that runs a separate child per CALLER, where each child gets its own $HOME and therefore its own identity — so the extension, whose trust store is keyed by the sha256 of that identity, asks to pair with every one of them. The identity answers which MCP the browser is talking to, so a host that knows the callers are one MCP points them all at one directory. (#316) |
| trustDir | string | identityDir (or FETCHPROXY_TRUST_DIR) | Where to keep this MCP's pin on the EXTENSION's identity (<trustDir>/<serverName>.extension-trust.json, mode 0600; the directory is created 0700). Falls back to FETCHPROXY_TRUST_DIR (an absolute path only; anything else is ignored, with a warning) and then to identityDir, so setting neither leaves the pin exactly where it has always been. It exists because a host that PROVISIONS the identity mounts that directory read-only, and the pin is the one file this package writes: with nowhere writable the write is logged (could not persist the extension pin) and the session continues, so every boot is trust-on-first-use and the pin refuses nothing. On such a deployment this is a precondition, not a tuning option — see docs/SECURITY.md §T-fake-extension. |
| onPairCode | (code: string) => void | (off by default) | Invoked once with the joint pair code on extension hello, so an MCP can surface it via stderr / MCP logging. |
| fetchTimeoutMs | number | 30_000 | Per-request timeout for fetch(). 0 opts back into legacy hang-forever. (#58) |
| verbDeadlineGraceMs | number | 15_000 | How much longer than a verb's OWN timeoutMs the server waits for that verb's reply. You should not need it; a hosted bridge with a long round trip is the case it exists for. (#237) |
| bridgeReviveDelayMs | number | 2_000 | Delay before the one-shot retry on the SW-eviction cold-start symptom — content_script_unreachable, plus a fetch() timeout of an idempotent request (#90; writes are not re-sent after a timeout unless the call passes retryOnTimeout: true). Gives Chrome a moment to wake the evicted MV3 SW. 0 disables. (#58) |
| keepAliveIntervalMs | number | 20_000 | Server-initiated ping cadence that keeps the MV3 SW resident across activity bursts. Below Chrome's ~30s eviction threshold with real margin. Pass 0 to disable. Default flipped from undefined in 0.10.0 (#71), tightened from 25_000 → 20_000 in #90 (25s still lost the cold-start race). (#67) |
| keepAliveMaxIdleMs | number | 300_000 (5 min) | How long after the most-recent activity the keep-alive pings keep firing. No-op when keepAliveIntervalMs is 0. (#67) |
| cookieKeys | string[] | [] | Declared cookie names for readCookies({ keys }). Gates the call site (gate #1) before the extension re-checks (gate #2). |
| localStorageKeys | string[] | [] | Declared localStorage keys for readLocalStorage. |
| sessionStorageKeys | string[] | [] | Declared sessionStorage keys for readSessionStorage. |
| captureHeaders | CaptureHeaderDecl[] | [] | Declared (urlPattern, headerName) pairs for captureRequestHeader. |
| indexedDbScopes | IndexedDbScopeDecl[] | [] | Declared IndexedDB (origin, database, store, keys) scopes for readIndexedDb. |
| localStoragePointers | StoragePointerDecl[] | [] | Declared (key, jsonPointer) extractions over localStorage. |
| sessionStoragePointers | StoragePointerDecl[] | [] | Same shape as localStoragePointers, against sessionStorage. |
Environment
FETCHPROXY_WS_PORT, FETCHPROXY_WS_HOST, FETCHPROXY_IDENTITY_DIR and
FETCHPROXY_TRUST_DIR are the ambient halves of the options above (see each
row). One variable has no option beside it:
| Variable | Default | What it does |
|---|---|---|
| FETCHPROXY_ALLOW_LOCAL_ORIGINS | unset | Admit WebSocket upgrades carrying the opaque null origin or an http(s):// loopback page origin (localhost, 127.0.0.1, [::1]), which are otherwise refused with 403. Only 1 turns it on; any other value is ignored with a warning, and a public origin — or a page on a scheme that is not one of the three extension schemes — stays refused either way: this admits local origins, it does not turn the origin gate off or widen what counts as the extension. A development escape: while it is set, any page the browser has open on localhost can reach the concentrator and raise a pair prompt of its own. The extension is unaffected (it dials with an extension scheme — chrome-extension://, moz-extension://, safari-web-extension://) and so is a peer MCP (no Origin header), so an ordinary install never needs it. See docs/SECURITY.md §T2 and §Which origins may open the socket. |
Choosing the right options
A per-call
timeoutMsgoverns its own verb.captureRequestHeader,captureRedirectanddownloadtake their own window, and the server waits that window plusverbDeadlineGraceMsfor the reply — it does not cap them atfetchTimeoutMs. That cap was removed in 3.0.0: the only way past it was to raisefetchTimeoutMs, which bounds EVERY verb, so buying a longer capture window also lengthened ordinary fetches and storage reads. A consumer that exposes its request timeout as a setting could not pay that, which made the documented workaround unusable for exactly the callers who needed it. The grace exists because the extension runs its own timer on the window and then ANSWERS; the server has to outlast it for that answer to arrive, or a window equal to the transport bound loses the reason to a race.fetchTimeoutMs. The default30_000matches what every realty / dining MCP was already wrapping. Tighten for latency-sensitive interactive tool calls; loosen for known-slow endpoints (large downloads, long-running search). Pass0to opt back into the legacy hang-forever behavior. On timeout,fetch()returns{ ok: false, kind: 'timeout' }and the convenience methods throwFetchproxyTimeoutError.bridgeReviveDelayMs. Chrome MV3 evicts extension service workers after ~30s idle. The default2_000ms is the same delay the zillow/onehome cohort had been hand-rolling in their transport adapters before the option existed. The one-shot retry fires on the cold-start symptom:content_script_unreachable, plus afetch()server-sidetimeout(#90 — a fully-cold worker often surfaces the first post-idlefetch()as a timeout while Chrome spins the SW up, so a cold-start never surfaces to the caller). The timeout retry only re-sends idempotent requests (GET/HEAD/OPTIONS). A timeout means the reply is late, not that the request never ran, so a POST/PUT/PATCH/DELETE is sent exactly once and itsFetchproxyTimeoutErrorcarriesretrySafe: false(whichretryOnceOnTimeouthonours). PassretryOnTimeout: trueon the call (request()/post()/postJson()/requestJson()/… options, orfetch(init, { retryOnTimeout })) for a POST that only reads — a search, a GraphQL query sent as a POST — or a write you know is safe to repeat; without it such a POST loses the cold-start retry. Passfalseto keep a read from being retried. The other verbs follow the same rule throughFetchproxyTimeoutError.retrySafe, whichretryOnceOnTimeouthonours: a timed-outdownload()(a second one saves a duplicate "file (1)") orwriteCookies()is markedretrySafe: false, and so is agraphqlQuery()— a declared operation may be a mutation, and the server holds only its name, not the document, so it cannot tell. PassgraphqlQuery({ …, retryOnTimeout: true })for an operation you know is a query.content_script_unreachable— the request never reached a tab — is retried for every method. Lengthen on slow machines where 2s isn't enough for the SW to wake; shorten if the caller is willing to surface the bridge-down error sooner. Pass0to disable the retry entirely.keepAliveIntervalMs. Default20_000(tightened from the 0.10.0 default of25_000in #90 — 25s left only ~5s of slack under Chrome's ~30s eviction window, which timer drift, a busy host event loop, and ping round-trip latency routinely ate, so the SW evicted and the next call cold-started). Keeps the MV3 SW resident across activity bursts (a user opens a search, thinks for 30s, runs another tool). Pass0to disable. Pairs withkeepAliveMaxIdleMs(default 5 min) so the pings self-quiesce on idle processes. (The extensionchrome.alarmsbackstop is clamped by Chrome to a 30s minimum period — it fires at the eviction edge, so the server ping is the real defense against a sub-30s race.)domains. Trust boundary, required. Use the apex hostname ('opentable.com') and let the extension match subdomains automatically. Multi-domain MCPs (HoneyBook, Resy two-host setups) pass every declared domain on every per-call request via{ domain: 'x.com' }. An entry that is a public suffix (com,co.uk,github.io) is refused by the constructor, naming the entry: it is matched exact-or-subdomain like any other, so it would claim every site anybody can register under it. The extension refuses the same entry when it validates the hello frame, but that refusal is a dropped frame and a line in the service worker's own console — this one fails where the declaration is written. Heuristic, not the Mozilla Public Suffix List;packages/protocol/src/public-suffix.tssays what it covers and what it does not.port/host. The defaults are load-bearing — the browser extension's connect target is hard-coded to127.0.0.1:37149, so every MCP that wants to share the concentrator needs to keep the defaults. Override only for local development or test isolation.When the host exits. Whichever MCP process binds the port first becomes the host, and that is often a short-lived one — a
@fetchproxy/bootstraplift (which opens and closes a server per lift) or anfpxcommand. When it exits, every peer re-elects: the in-flight requests that are safe to repeat (reads, header/redirect captures,fetches of GET/HEAD/OPTIONS, andfetches orgraphqlQuerys withretryOnTimeout: true) are sent again through the new bridge under their original deadline; the ones that may already have run in the browser (otherfetchmethods,writeCookies,download, and agraphqlQuerynot markedretryOnTimeout: true) fail with an error saying so, rather than being repeated. A request that was still waiting in this process — never written to the old host's socket — fails withrequest not sent … It is safe to retryinstead, since nothing reached the browser. Before this, every in-flight call on every peer failed withextension disconnected.
API
new FetchproxyServer(opts)
See Server options for the full table. Three
fields are required: serverName, version, domains. Everything
else has a default.
fp.bridgeHealth() exposes a snapshot of the bridge's process-wide
freshness counters — downstream MCPs surface this through their
healthcheck tool. As of 0.10.0 (#73)
the return shape includes keepAlive and swEviction sub-objects
so consumers can verify the keep-alive is actually preventing
Chrome MV3 service-worker eviction. As of 0.11.0 (#82)
the resolved fetchTimeoutMs and bridgeReviveDelayMs are also
top-level fields so cohort healthcheck tools can drop their local
DEFAULT_FETCH_TIMEOUT_MS / DEFAULT_BRIDGE_REVIVE_DELAY_MS
constants and read the resolved value directly:
As of 2.5.0 h.session says where the extension link stands, so a
healthcheck can name the missing leg instead of showing a bare
session-ready timeout: 'not_listening' (no listen()), 'linked'
(session key derived), 'pair_pending' (the user has yet to approve
pairCode in the popup), 'extension_disconnected' (port bound, no
extension attached), or 'no_session' (extension attached, hello sent,
nothing came back — the hello was dropped somewhere).
As of 3.3.0 (#418)
h.session also names the browser behind the current session
(platform) and the capabilities it said it cannot serve
(unavailableCapabilities — Safari has no chrome.downloads, so
download is the usual one). The extension grants an MCP the servable
subset instead of refusing it outright, and a verb that needs one of these
is refused locally, with no round trip, as
FetchproxyCapabilityUnavailableError. The list is taken from the
extension hello the accepted ready was verified against and cleared on
disconnect; it is empty while unlinked or when the extension predates the
field. It is unsigned and advisory — see docs/SECURITY.md
§T-unavailable-caps.
const h = fp.bridgeHealth();
// h.session: {
// state: 'not_listening' | 'linked' | 'pair_pending' | 'extension_disconnected' | 'no_session';
// pairCode: string | null; // set while state === 'pair_pending'
// extensionConnected: boolean; // a peer learns arrivals from the host's relayed hello (1.12.0+) and departures from its extension-disconnected notice (2.5.0+)
// unavailableCapabilities: Capability[]; // 3.3.0+: known names this browser cannot serve, sorted; [] when unknown
// platform: Platform | null; // 3.3.0+: 'chrome' | 'safari' | …; null while unlinked
// };
// h.fetchTimeoutMs: number; // resolved (30_000 default, or override; 0 = disabled)
// h.bridgeReviveDelayMs: number; // resolved (2_000 default, or override; 0 = disabled)
// h.keepAlive: {
// enabled: boolean; // true when intervalMs > 0
// intervalMs: number; // resolved (20_000 default)
// maxIdleMs: number; // resolved (300_000 default)
// lastPingAt: number | null; // epoch ms; null until first tick
// totalPings: number; // monotonic across the process lifetime
// idleSinceMs: number | null;// elapsed ms since lastActiveAt
// };
// h.swEviction: {
// lazyReviveAttempts: number;
// lazyReviveSuccesses: number;
// lastEvictionDetectedAt: number | null; // latest content_script_unreachable (overwritten on each detection)
// };await fp.listen(): Promise<void>
Loads or creates the identity keypair, races the port, and stands up either a host (binds the port) or peer (dials the host) connection. Idempotent only in the sense that it leaves role populated on success; calling listen() twice without close() is a programming error.
fp.role: 'host' | 'peer' | null
Set after listen() succeeds. Callers should NOT branch on this — behaviour is identical across roles — but it's exposed for testability and metrics.
Verb shortcuts
All verb shortcuts accept the same per-call options:
interface BodylessRequestOpts {
headers?: Record<string, string>;
expectStatus?: number | number[]; // throws FetchproxyHttpError on mismatch
subdomain?: string; // prepended to the chosen base domain
domain?: string; // required when multiple `domains` declared
}| Method | Returns | Default expectStatus | Notes |
|---|---|---|---|
| get(path, opts?) | HttpResponse | none | Raw GET. Does not parse the body. |
| post(path, body?, opts?) | HttpResponse | none | Raw POST. body is a string; no Content-Type is set. |
| put(path, body?, opts?) | HttpResponse | none | |
| patch(path, body?, opts?) | HttpResponse | none | |
| delete(path, opts?) | HttpResponse | none | No body — the bridge doesn't support DELETE-with-body. |
| getHtml(path, opts?) | string | [200, 201, 202, 204] | GET + return body as string. |
| getJson<T>(path, opts?) | T | [200, 201, 202, 204] | GET + JSON.parse(body). |
| postJson<T>(path, body?, opts?) | T | [200, 201, 202, 204] | JSON.stringify's body, sets Content-Type: application/json unless the caller already set one, parses the response body as JSON. |
HttpResponse:
interface HttpResponse {
status: number;
body: string;
url: string; // final URL after redirects, as seen by the browser
}Path resolution
- Absolute URL (
https://...) — used as-is. Still guarded against leaving the declared domain set. - Relative path — joined with
https://${subdomain}.${baseDomain}${path}(orhttps://${baseDomain}${path}when nosubdomain). - Base domain —
domains[0]when only one is declared;opts.domainis required and must exactly equal one of the declared entries when more than one is.
Error model
| Condition | Behaviour |
|---|---|
| Bridge failed (no tab, extension offline, transport error) | Throws FetchproxyProtocolError. |
| HTTP status outside expectStatus (when set) | Throws FetchproxyHttpError with the full HttpResponse attached. |
| Any successful HTTP exchange when no expectStatus is set | Resolves; the caller inspects response.status themselves. |
| Programmer error (bad subdomain, undeclared domain, missing capability) | Throws a plain Error synchronously at the call site. |
| The paired extension predates binary fetch (3.7.0+, #460) | requestBytes() / getBytes() throw FetchproxyExtensionUpdateRequiredError (hinted: update ContextMint Bridge) — locally when the extension hello lacks fetch_base64, or when the answer comes back without the bodyEncoding marker. fetch() returns { ok: false, kind: 'extension_update_required' }. |
| A binary body over the 16 MiB cap (3.7.0+, #460) | Throws FetchproxyResponseTooLargeError (.limitBytes, .declaredBytes). |
| This browser cannot serve the verb's capability (3.3.0+, #418) | Throws FetchproxyCapabilityUnavailableError (a hinted FetchproxyProtocolError) — locally when the session listed it, or from the extension's capability_unavailable reply. fetch() returns { ok: false, kind: 'capability_unavailable' } instead. |
await fp.requestBytes(method, path, opts?) / fp.getBytes(path, opts?) — binary downloads (3.7.0+, #460)
The text shortcuts decode the body as UTF-8, which corrupts a PDF, an office file or an image beyond repair. These return the body's bytes, intact:
const file = await fp.getBytes('https://files.example.com/signed/123?sig=…');
// { status: 200, url: <final url after redirects>,
// headers: { 'content-type': 'application/pdf', 'content-length': '48213',
// 'content-disposition': 'attachment; filename="report.pdf"' },
// bytes: Uint8Array }- Same path resolution, declared-domain guard,
expectStatus,credentialsand error model asrequest();inPageandviaTabare not accepted (BinaryRequestOpts). - The extension runs it from its background worker, not a tab, so a file host that sends no CORS headers is readable, and redirects are followed. Both the request URL and the final URL must be on the declared
domains— to read a signed CDN host, declare it (that is a scope change, so the user re-approves once). Seedocs/SECURITY.md§T-binary-fetch for why this does not widen what the extension can reach. - Bodies are capped at
MAX_BINARY_RESPONSE_BYTES(16 MiB, exported) — derived from the hosted relay's 32 MiB message limit. Over it:FetchproxyResponseTooLargeError. - Needs a ContextMint Bridge build that lists
fetch_base64inbridgeHealth().session.features; otherwiseFetchproxyExtensionUpdateRequiredError, with no round trip. - Only
content-type,content-lengthandcontent-dispositionare relayed, each only when present. Check them before trusting the body.
The low-level equivalent is fetch({ ...init, responseType: 'base64' }), whose ok envelope then carries bodyEncoding: 'base64', headers, and body as base64 — but requestBytes() also refuses an answer without the marker and re-checks the final URL, so prefer it.
await fp.fetch(init): Promise<FetchResult | FetchResultError>
The raw, single-shot escape hatch behind the verb shortcuts. Use it when you already have a FetchInit ready or need to fully control tabUrl independently of the request URL.
interface FetchInit {
url: string; // absolute; must be on a declared domain
method: string;
headers?: Record<string, string>;
body?: string;
tabUrl: string; // prefix-matched against open tabs
}fetch() returns a discriminated union — { ok: true, status, url, body } on any successful upstream HTTP exchange (any 2xx/3xx/4xx/5xx — status alone does NOT turn this into ok: false), or { ok: false, error } only when the bridge itself failed. It does NOT throw on non-2xx.
Consumer helpers
Two convenience methods that consolidate boilerplate the Pattern-A cohort (zillow / redfin / compass / homes) had been hand-rolling identically in their own src/client.ts / src/tools/healthcheck.ts.
await fp.requestJson<T>(method, path, opts?): Promise<{ data: T | null; result: FetchResult }>
Method-generic JSON helper. Sets Accept: application/json; adds Content-Type: application/json for a non-GET request that carries a body (unless the caller set one); JSON.stringifys the body; treats 204, an empty body or a whitespace-only body as data: null (the same rule as getJson / postJson); otherwise JSON.parses.
const { data, result } = await fp.requestJson<MyShape>('POST', '/api/x', {
body: { q: 'foo' },
subdomain: 'api',
retryOnTimeout: true, // a read-only search: safe to re-send after a timeout
});Its scope is serialization + header defaults + 204-handling + JSON.parse only. It deliberately does NOT assert on the HTTP status or detect a sign-in interstitial — those guards differ per site — so it returns BOTH the parsed data and the raw result: FetchResult, leaving the consumer to run its own throwIfNotOk / throwIfSignInPage over result. Bridge-level failures still throw the typed errors (via request()); only successful round-trips return.
opts is { subdomain?, domain?, headers?, body?, retryOnTimeout? } (same domain/subdomain semantics as the verb shortcuts; body is any JSON-serializable value). retryOnTimeout works as on request(): a POST/PUT/PATCH/DELETE that times out is sent once unless it is true, so pass true for a POST that only reads (a search, a GraphQL query) to keep the cold-start timeout retry.
await fp.runProbe(fetchFn, probePath): Promise<BridgeProbeResult>
Runs one healthcheck probe through the caller's fetchFn, measures elapsed ms, classifies any thrown error with classifyBridgeError, and projects the post-probe bridgeHealth() into a snake-cased bridge sub-object:
const probe = await fp.runProbe((path) => client.fetchHtml(path), '/robots.txt');
// { ok, elapsed_ms, bridge: { role, port, server_version, ..., session_state, pending_pair_code, extension_connected, last_extension_message_at, unavailable_capabilities, platform }, error?: { kind, message } }As of 2.5.0 the bridge projection carries session_state,
pending_pair_code and extension_connected (from bridgeHealth().session)
and last_extension_message_at, and error.kind can be
'session_not_ready' — FetchproxySessionNotReadyError, which used to
fall through to 'other'. As of 3.3.0 it also carries
unavailable_capabilities and platform (#418).
runProbe only does probe execution + classification + the bridge projection. The healthcheck tool registration and the site-specific hint text stay in the consumer, which wraps this result with its own plain-English next-step guidance.
await fp.readCookies(opts?): Promise<string>
const fp = new FetchproxyServer({
serverName: 'creditkarma-mcp',
version: '0.1.0',
domains: ['creditkarma.com'],
capabilities: ['fetch', 'read_cookies'], // must include 'read_cookies'
});
await fp.listen();
const cookies = await fp.readCookies({ subdomain: 'www' });
// "sid=...; csrf=...; ..."opts accepts { domain?, subdomain? } (same semantics as the verb shortcuts).
Without keys, returns the raw document.cookie string from a tab on the chosen host (non-HttpOnly cookies only). With keys (each must be in the declared cookieKeys), the extension reads each named cookie with chrome.cookies.get, which does return HttpOnly cookies, including login-session cookies. The pair popup lists the names and warns the user; see docs/SECURITY.md §T-cookie-exfil.
Throws synchronously if the MCP did not declare 'read_cookies' in capabilities (this is a programming mistake, not a runtime condition). Throws FetchproxyProtocolError if the bridge could not deliver the request.
await fp.close(): Promise<void>
Closes the WS / extension connection. Safe to call before listen() (no-op) and twice in a row.
Errors
| Class | Origin |
|---|---|
| FetchproxyProtocolError | Bridge-side failure (no signed-in tab, extension offline, transport error, capability not granted at the extension layer). |
| FetchproxyHttpError | Upstream HTTP status was outside expectStatus. Carries the full HttpResponse. |
| FetchproxyCapabilityUnavailableError | 3.3.0+ (#418): THIS BROWSER cannot serve the capability (.capability, .platform; .hint blames the browser, not the MCP). classifyFetchError returns 'capability_unavailable', distinct from 'capability_denied'; classifyBridgeError buckets it 'protocol'. |
| FetchproxyHelloRejectedError | The extension refused the hello. When the reason starts unsupported-capability: (every declared capability is unavailable in this browser), .unavailableCapabilities lists them and .hint names the browser (3.3.0+). When it starts awaiting-approval: (an approval card is waiting in the browser), .retryable is true, classifyBridgeError returns 'awaiting_approval', .hint says to approve it there, and the session opens once the person does. .retryable is false for every other reason. |
Resilience helpers
Pure, I/O-free utilities for rate-limit / bot-wall resilience, hoisted from the portal-MCP cohort so every consumer imports one shared implementation. All are independent and tree-shakeable.
| Export | What it does |
|---|---|
| classifyBotWall(body, status, headers?) | Detects a bot-wall / CAPTCHA interstitial → { blocked: true, vendor } \| { blocked: false }. Vendors: perimeterx, aws_waf, cloudflare, datadome, unknown. Body-keyed first (a PerimeterX wall can be HTTP 200), with status/headers as additional signal. Cloudflare is recognised by the cf-mitigated header, the "Attention Required! | Cloudflare" block page, or the "Just a moment…" JS-challenge interstitial (_cf_chl_opt, or a <title> opening with "Just a moment", case-insensitive — the same markers as mcp-utils isCloudflareChallenge) at any status. Pairs with the bot_challenge FetchErrorKind — distinct from not-found / bridge-down / timeout. |
| TokenBucket | Per-host requests-per-minute governor. new TokenBucket({ ratePerMinute, burst?, now? }); await bucket.acquire() resolves when a token is free. Governs total request volume, complementing the concurrency cap. Inject now for deterministic tests. |
| backoffDelayMs(attempt, { baseMs, capMs, rng?, retryAfterMs? }) | Exponential backoff (baseMs * 2^attempt, capped at capMs) with full jitter, floored at an optional retryAfterMs hint. Inject rng for deterministic schedules. |
| withDeadline(promise, ms) | Races a promise against a timer → { timedOut: false, value } \| { timedOut: true }. Clears and unrefs the timer; inner rejections propagate (not folded into a timeout). For bulk partial-results below the MCP request deadline. |
import {
classifyBotWall,
TokenBucket,
backoffDelayMs,
withDeadline,
} from '@fetchproxy/server';
const wall = classifyBotWall(res.body, res.status, res.headers);
if (wall.blocked) {
// back off + retry rather than treating it as "not found"
await new Promise((r) => setTimeout(r, backoffDelayMs(attempt, { baseMs: 500, capMs: 30_000 })));
}Parsing helpers
Pure, dependency-free string utilities for SSR-scraping MCPs, hoisted
from the portal-MCP cohort so every consumer imports one shared
implementation instead of re-hand-rolling them. Anything portal-specific
— the window.X variable names, CDN-host filters, GraphQL bodies —
stays in the consumer.
| Export | What it does |
|---|---|
| extractGlobalAssign(html, varName) | Lift a window.<varName> = {…} / global.<varName> = {…} / var <varName> = {…} JSON object out of inline-script HTML via string-aware balanced-brace walking → the parsed object, or null. Skips an unparseable same-named occurrence and keeps scanning; the name is matched literally with an identifier-boundary guard (so uc won't match myuc). |
| extractBalancedObject(text, startIndex) | Lower-level brace walker behind extractGlobalAssign. startIndex must point at a {. String-aware: braces inside double-quoted strings and \" / \\ escapes don't move the depth counter; stops at the first balanced close (a trailing ; is ignored) → the parsed object, or null on imbalance / parse error. |
| extractImgTags(html) | Regex-scrape <img> tags → { src, alt }[]. Attribute-order agnostic, single/double quotes, case-insensitive. Tags with no src are skipped; alt is omitted when absent but a present-but-empty alt="" is kept as ''. Host/CDN filtering and dedup stay in the caller. |
| lastPathSegment(urlOrPath) | Strip scheme/host, then ?query / #fragment, and return the final non-empty path segment (the canonical opaque-id extractor — <zpid>_zpid, a base36 hash, <id>_lid, …). Tolerates trailing slashes and // runs; '' when there is no path segment. |
import { extractGlobalAssign, extractImgTags, lastPathSegment } from '@fetchproxy/server';
const state = extractGlobalAssign(html, '__INITIAL_DATA__'); // variable name stays caller-side
const photos = extractImgTags(html).filter((img) => img.src.includes('cdn.example.com'));
const id = lastPathSegment(listing.url ?? listing['@id']); // pick the fragment-free field firstBatch-paging primitives
Pair with the fan-out kit (mapWithConcurrency / TokenBucket /
backoffDelayMs): split a big id list into safe-sized pages, dispatch
one page at a time, and space them out — so a single bulk-get tool call
doesn't stampede the upstream.
| Export | What it does |
|---|---|
| chunk(arr, size) | Split arr into pages of at most size, in order. size <= 0 collapses to a single page (never loops forever). Returns fresh slices; the input is never mutated. [] for an empty input. |
| sleep(ms) | Promise-based sleep — resolves after ms ms. Spaces out paged dispatches. |
import { chunk, sleep, mapWithConcurrency, BRIDGE_CONCURRENCY } from '@fetchproxy/server';
for (const page of chunk(ids, 20)) {
await mapWithConcurrency(page, BRIDGE_CONCURRENCY, (id) => fetchOne(id));
await sleep(250); // breathe between pages
}License
MIT.
