Examples & benchmarks / #91 · 2026-11-23 · Benchmark · Easy · for ai agents, llm data
Read a page from an AI assistant in one call: MCP Functions vs driving a browser
An MCP client reads the same two pages two ways through cdpfleet.com/mcp — one `scrape` call per page, or `launch_browser`, `navigate`, `evaluate`, `snapshot` and `close_browser` — and compares the thread-seconds each was billed, read back from the account's history. Then two agents share one API key, each driving its own browser by `browser_name`. In five languages, four of them on the official MCP SDK.
Run on production on 2026-11-23: ✓ Node.js ✓ Python ✓ Java ✓ C# ✓ Go
A benchmark: the results below are what this setup measured on the dates shown, on our own test runs. Sites, networks and browsers change, so rerun the code before you rely on the numbers.
The problem
An assistant that only needs to read a page — its text, a price, a date — has two ways to do it on cdpfleet's hosted MCP server. It can call scrape, one tool call that loads the page in a real browser and returns Markdown plus the values it asked for. Or it can drive a browser: launch_browser, navigate, evaluate or snapshot, and close_browser. Both are billed in thread-seconds. Which one costs less depends on how the assistant works, and this case measures it, including the time a model spends thinking between calls. It also checks what happens when two agents share one API key.
What we used, and why
| What | Why |
|---|---|
https://cdpfleet.com/mcp | The hosted MCP server, over Streamable HTTP. A script sends its API key as Authorization: Bearer <key>; assistants sign in with OAuth. |
scrape | One call per page: formats: ["markdown"] and extract with CSS selectors (title, price and stock on the book page; title and "last edited" line on the article). No browser to launch or close. |
launch_browser, navigate, evaluate, snapshot, close_browser | The same two reads with a browser: headless Chromium through your own proxy (PROXY_URL, record: false), the same selectors run by evaluate, and an accessibility snapshot of each page as its text. |
| A 3-second pause between browser calls | A stand-in for the model reading a result and deciding the next call. The browser is billed while it waits; a scrape call is billed only while it runs. |
browser_name | Two agents, each with its own MCP session on the same key: one launches research, the other checkout, at the same time. Every browser tool then takes the name. |
account and GET /v1/me/sessions | account shows the key's live sessions. The history lists each scrape call as a function:scrape record and each browser as a chromium session; billed thread-seconds = (ended_at − started_at) × weight. |
How it works
- Functions: in one MCP session, call
scrapefor the book page and then the Wikipedia article, with Markdown and the picked values. - Browser: in a new MCP session, launch headless Chromium, then for each page
navigate,evaluatethe same selectors and take asnapshot; close the browser. Calls back to back. - The same browser run again with 3 s before every call after the launch.
- Look up the two
function:scraperecords and the two browser sessions in the account's history and add up their billed thread-seconds. - Two agents at once on the same key: each launches a browser under its own
browser_nameand opens a different page. Then one of them callsnavigatewithout a name,accountcounts the live sessions, and each closes its own browser.
The code
The same program in five languages (also on GitHub, with the raw output). Set these environment variables first:
CDPFLEET_API_KEY— your API key (dashboard → API keys)PROXY_URL— your proxy, e.g.http://user:[email protected]:8000
// npm install @modelcontextprotocol/[email protected]
// env: CDPFLEET_API_KEY, PROXY_URL
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const MCP = new URL('https://cdpfleet.com/mcp');
const API = 'https://cdpfleet.com';
const KEY = process.env.CDPFLEET_API_KEY;
const PROXY = process.env.PROXY_URL;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const since = new Date(Date.now() - 60000).toISOString();
// The same two reads both ways: the page as text, plus a few values picked by CSS selector.
const TARGETS = [
{ name: 'book', url: 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html', pick: { title: 'h1', price: '.price_color', stock: '.availability' } },
{ name: 'wikipedia', url: 'https://en.wikipedia.org/wiki/Web_scraping', pick: { title: 'h1', updated: '#footer-info-lastmod' } },
];
// evaluate calls an arrow function given as text.
const pickIn = (pick) => `() => { const q = (s) => document.querySelector(s)?.textContent.trim() ?? null; return { ${Object.entries(pick).map(([k, s]) => `${k}: q(${JSON.stringify(s)})`).join(', ')} }; }`;
// A script authenticates with its API key as a bearer token (assistants use OAuth instead).
async function connect(name) {
const transport = new StreamableHTTPClientTransport(MCP, { requestInit: { headers: { authorization: `Bearer ${KEY}` } } });
const client = new Client({ name, version: '1.0.0' });
await client.connect(transport);
return { client, transport };
}
// One tool call, timed; the text of its result.
async function call(client, log, name, args = {}) {
const t = Date.now();
const r = await client.callTool({ name, arguments: args });
const text = r.content.filter((c) => c.type === 'text').map((c) => c.text).join('\n');
log.push({ tool: name, ms: Date.now() - t, error: Boolean(r.isError) });
return { text, error: Boolean(r.isError) };
}
// A shared proxy drops the odd connection: one retry of a failed page load.
async function retried(client, log, name, args) {
const r = await call(client, log, name, args);
return r.error ? call(client, log, name, args) : r;
}
// The account's history: a Function call is a "function:scrape" record, a browser its own session.
// Billed thread-seconds = (ended_at - started_at) × weight.
async function history(match) {
for (let i = 0; i < 30; i++) {
const r = await fetch(`${API}/v1/me/sessions?from=${encodeURIComponent(since)}&limit=200`, { headers: { 'x-api-key': KEY } });
const found = ((await r.json()).sessions || []).filter(match);
if (found.length && found.every((s) => s.ended_at)) return found.map((s) => ({ engine: s.engine, weight: s.weight, thread_seconds: Math.round((Date.parse(s.ended_at) - Date.parse(s.started_at)) * s.weight / 100) / 10 }));
await sleep(2000);
}
return [];
}
const total = (records) => Math.round(records.reduce((a, r) => a + r.thread_seconds, 0) * 10) / 10;
// ---- 1. Functions: one scrape call per page, no browser to drive.
async function functions() {
const log = [];
const { client, transport } = await connect('cdpfleet-case-91');
const start = new Date();
const reads = [];
for (const t of TARGETS) {
const r = await retried(client, log, 'scrape', { url: t.url, formats: ['markdown'], extract: t.pick });
// "200 <url>\n\nextract: {…}\n\n--- markdown ---\n…"
const extract = /extract: (\{[\s\S]*?\n\})/.exec(r.text)?.[1];
reads.push({ page: t.name, status: r.text.split(' ')[0], picked: extract ? JSON.parse(extract) : null, text_chars: r.text.split('--- markdown ---\n')[1]?.length ?? 0 });
}
const end = new Date();
await transport.terminateSession();
await client.close();
const billed = await history((s) => s.engine === 'function:scrape' && Date.parse(s.started_at) >= start - 1000 && Date.parse(s.started_at) <= end);
return { reads, wall_ms: end - start, records: billed.length, thread_seconds: total(billed), calls: log };
}
// ---- 2. Driving a browser: launch, then navigate + evaluate + snapshot per page, then close.
// pauseMs stands in for the model thinking between tool calls; the browser is billed meanwhile.
async function browser(pauseMs) {
const log = [];
const { client, transport } = await connect('cdpfleet-case-91');
const start = Date.now();
const launched = await call(client, log, 'launch_browser', { browser: 'chromium', headless: true, proxy: PROXY, record: false });
const sessionId = /session ([0-9a-f-]{36})/.exec(launched.text)?.[1] ?? null;
const reads = [];
for (const t of TARGETS) {
await sleep(pauseMs);
const nav = await retried(client, log, 'navigate', { url: t.url });
await sleep(pauseMs);
const picked = JSON.parse((await call(client, log, 'evaluate', { expression: pickIn(t.pick) })).text);
await sleep(pauseMs);
const snap = await call(client, log, 'snapshot');
reads.push({ page: t.name, status: nav.text.split(' ')[0], picked, text_chars: snap.text.length });
}
await sleep(pauseMs);
const closed = (await call(client, log, 'close_browser')).text.startsWith(`Session ${sessionId} ended`);
const wall = Date.now() - start;
await transport.terminateSession();
await client.close();
const billed = await history((s) => s.session_id === sessionId);
return { pause_ms: pauseMs, session_id: sessionId, launched: launched.text.split('. ')[0], closed, reads, wall_ms: wall, engine: billed[0]?.engine ?? null, weight: billed[0]?.weight ?? null, thread_seconds: total(billed), calls: log };
}
// ---- 3. Two agents on one key, each in its own MCP session, each with its own named browser.
async function agent(name, url) {
const log = [];
const { client, transport } = await connect(`cdpfleet-case-91-${name}`);
const launched = await call(client, log, 'launch_browser', { browser: 'chromium', headless: true, proxy: PROXY, record: false, browser_name: name });
const sessionId = /session ([0-9a-f-]{36})/.exec(launched.text)?.[1] ?? null;
await retried(client, log, 'navigate', { url, browser_name: name });
const seen = JSON.parse((await call(client, log, 'evaluate', { expression: '({ url: location.href, title: document.title })', browser_name: name })).text);
return { name, client, transport, log, mcp_session: transport.sessionId, session_id: sessionId, as_named: launched.text.includes(`as "${name}"`), seen };
}
async function named() {
const [a, b] = await Promise.all([agent('research', TARGETS[0].url), agent('checkout', TARGETS[1].url)]);
// Without browser_name, a tool drives "default" — which neither agent launched.
const unnamed = await call(b.client, b.log, 'navigate', { url: TARGETS[0].url });
const during = JSON.parse((await call(a.client, a.log, 'account')).text).live_sessions;
const closed = {};
for (const x of [a, b]) closed[x.name] = (await call(x.client, x.log, 'close_browser', { browser_name: x.name })).text.startsWith(`Session ${x.session_id} ended`);
// The live count follows the router's view of the key: read it until both are gone (up to 15 s).
let after;
const closedAt = Date.now();
for (let i = 0; i < 15; i++) {
after = JSON.parse((await call(a.client, a.log, 'account')).text).live_sessions;
if (after === 0) break;
await sleep(1000);
}
const zeroAfterMs = after === 0 ? Date.now() - closedAt : null;
for (const x of [a, b]) { await x.transport.terminateSession(); await x.client.close(); }
const billed = {};
for (const x of [a, b]) billed[x.name] = total(await history((s) => s.session_id === x.session_id));
return {
agents: [a, b].map((x) => ({ browser_name: x.name, as_named: x.as_named, session_id: x.session_id, seen: x.seen, calls: x.log })),
distinct_mcp_sessions: new Set([a.mcp_session, b.mcp_session]).size,
distinct_browser_sessions: new Set([a.session_id, b.session_id]).size,
unnamed: { error: unnamed.error, text: unnamed.text.split('\n')[0] },
live_sessions_during: during,
closed,
live_sessions_after: after,
live_zero_after_ms: zeroAfterMs,
thread_seconds: billed,
};
}
const fns = await functions();
const fast = await browser(0);
const paced = await browser(3000);
const two = await named();
console.log(JSON.stringify({ language: 'node', functions: fns, browser: fast, browser_paced: paced, named: two, measured_at: new Date().toISOString().slice(0, 10) }, null, 2));
# pip install mcp==2.3.0 requests
# env: CDPFLEET_API_KEY, PROXY_URL
import asyncio
import json
import os
import re
import time
from datetime import datetime, timedelta, timezone
import requests
from mcp import ClientSession
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client
MCP = "https://cdpfleet.com/mcp"
API = "https://cdpfleet.com"
KEY = os.environ["CDPFLEET_API_KEY"]
PROXY = os.environ["PROXY_URL"]
SINCE = (datetime.now(timezone.utc) - timedelta(minutes=1)).isoformat()
# The same two reads both ways: the page as text, plus a few values picked by CSS selector.
TARGETS = [
{"name": "book", "url": "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
"pick": {"title": "h1", "price": ".price_color", "stock": ".availability"}},
{"name": "wikipedia", "url": "https://en.wikipedia.org/wiki/Web_scraping",
"pick": {"title": "h1", "updated": "#footer-info-lastmod"}},
]
def pick_in(pick):
"""evaluate calls an arrow function given as text."""
fields = ", ".join(f"{k}: q({json.dumps(s)})" for k, s in pick.items())
return f"() => {{ const q = (s) => document.querySelector(s)?.textContent.trim() ?? null; return {{ {fields} }}; }}"
def ms(t):
return round((time.monotonic() - t) * 1000)
def parse(ts):
return datetime.fromisoformat(ts.replace("Z", "+00:00"))
class Connection:
"""One MCP session over Streamable HTTP; a script authenticates with its API key as a bearer token."""
def __init__(self):
self.session_id = None
async def __aenter__(self):
http = create_mcp_http_client(headers={"authorization": f"Bearer {KEY}"})
async def remember(response): # the server's MCP session id, from its response header
self.session_id = response.headers.get("mcp-session-id") or self.session_id
http.event_hooks["response"].append(remember)
self._http = http
self._streams = streamable_http_client(MCP, http_client=http, terminate_on_close=True)
read, write = await self._streams.__aenter__()
self._session = ClientSession(read, write)
self.client = await self._session.__aenter__()
await self.client.initialize()
return self
async def __aexit__(self, *exc):
await self._session.__aexit__(*exc)
await self._streams.__aexit__(*exc)
await self._http.aclose()
async def call(client, log, name, args=None):
t = time.monotonic()
r = await client.call_tool(name, args or {})
text = "\n".join(c.text for c in r.content if c.type == "text")
log.append({"tool": name, "ms": ms(t), "error": bool(r.is_error)})
return text, bool(r.is_error)
async def retried(client, log, name, args):
"""A shared proxy drops the odd connection: one retry of a failed page load."""
text, err = await call(client, log, name, args)
return await call(client, log, name, args) if err else (text, err)
def thread_seconds(s):
return round((parse(s["ended_at"]) - parse(s["started_at"])).total_seconds() * s["weight"], 1)
async def history(match):
"""The account's history: a Function call is a "function:scrape" record, a browser its own session.
Billed thread-seconds = (ended_at - started_at) × weight."""
for _ in range(30):
r = await asyncio.to_thread(requests.get, f"{API}/v1/me/sessions", params={"from": SINCE, "limit": 200},
headers={"x-api-key": KEY}, timeout=30)
found = [s for s in r.json().get("sessions", []) if match(s)]
if found and all(s["ended_at"] for s in found):
return [{"engine": s["engine"], "weight": s["weight"], "thread_seconds": thread_seconds(s)} for s in found]
await asyncio.sleep(2)
return []
def total(records):
return round(sum(r["thread_seconds"] for r in records), 1)
# ---- 1. Functions: one scrape call per page, no browser to drive.
async def functions():
log, reads = [], []
async with Connection() as c:
start = datetime.now(timezone.utc)
t = time.monotonic()
for tg in TARGETS:
text, _ = await retried(c.client, log, "scrape", {"url": tg["url"], "formats": ["markdown"], "extract": tg["pick"]})
# "200 <url>\n\nextract: {…}\n\n--- markdown ---\n…"
m = re.search(r"extract: (\{[\s\S]*?\n\})", text)
parts = text.split("--- markdown ---\n", 1)
reads.append({"page": tg["name"], "status": text.split(" ")[0], "picked": json.loads(m[1]) if m else None,
"text_chars": len(parts[1]) if len(parts) > 1 else 0})
wall = ms(t)
end = datetime.now(timezone.utc)
billed = await history(lambda s: s["engine"] == "function:scrape"
and start - timedelta(seconds=1) <= parse(s["started_at"]) <= end)
return {"reads": reads, "wall_ms": wall, "records": len(billed), "thread_seconds": total(billed), "calls": log}
# ---- 2. Driving a browser: launch, then navigate + evaluate + snapshot per page, then close.
# pause stands in for the model thinking between tool calls; the browser is billed meanwhile.
async def browser(pause_ms):
log, reads = [], []
pause = pause_ms / 1000
async with Connection() as c:
t = time.monotonic()
launched, _ = await call(c.client, log, "launch_browser", {"browser": "chromium", "headless": True, "proxy": PROXY, "record": False})
sid = re.search(r"session ([0-9a-f-]{36})", launched)
session_id = sid[1] if sid else None
for tg in TARGETS:
await asyncio.sleep(pause)
nav, _ = await retried(c.client, log, "navigate", {"url": tg["url"]})
await asyncio.sleep(pause)
picked = json.loads((await call(c.client, log, "evaluate", {"expression": pick_in(tg["pick"])}))[0])
await asyncio.sleep(pause)
snap, _ = await call(c.client, log, "snapshot")
reads.append({"page": tg["name"], "status": nav.split(" ")[0], "picked": picked, "text_chars": len(snap)})
await asyncio.sleep(pause)
closed = (await call(c.client, log, "close_browser"))[0].startswith(f"Session {session_id} ended")
wall = ms(t)
billed = await history(lambda s: s["session_id"] == session_id)
return {"pause_ms": pause_ms, "session_id": session_id, "launched": launched.split(". ")[0], "closed": closed,
"reads": reads, "wall_ms": wall, "engine": billed[0]["engine"] if billed else None,
"weight": billed[0]["weight"] if billed else None, "thread_seconds": total(billed), "calls": log}
# ---- 3. Two agents on one key, each in its own MCP session, each with its own named browser.
async def agent(c, name, url):
log = []
launched, _ = await call(c.client, log, "launch_browser",
{"browser": "chromium", "headless": True, "proxy": PROXY, "record": False, "browser_name": name})
sid = re.search(r"session ([0-9a-f-]{36})", launched)
await retried(c.client, log, "navigate", {"url": url, "browser_name": name})
seen = json.loads((await call(c.client, log, "evaluate",
{"expression": "({ url: location.href, title: document.title })", "browser_name": name}))[0])
return {"browser_name": name, "as_named": f'as "{name}"' in launched, "session_id": sid[1] if sid else None,
"seen": seen, "calls": log}
async def named():
async with Connection() as ca, Connection() as cb:
a, b = await asyncio.gather(agent(ca, "research", TARGETS[0]["url"]), agent(cb, "checkout", TARGETS[1]["url"]))
# Without browser_name, a tool drives "default" — which neither agent launched.
text, err = await call(cb.client, b["calls"], "navigate", {"url": TARGETS[0]["url"]})
during = json.loads((await call(ca.client, a["calls"], "account"))[0])["live_sessions"]
closed = {}
for c, x in ((ca, a), (cb, b)):
out, _ = await call(c.client, x["calls"], "close_browser", {"browser_name": x["browser_name"]})
closed[x["browser_name"]] = out.startswith(f"Session {x['session_id']} ended")
# The live count follows the router's view of the key: read it until both are gone (up to 15 s).
closed_at = time.monotonic()
after = None
for _ in range(15):
after = json.loads((await call(ca.client, a["calls"], "account"))[0])["live_sessions"]
if after == 0:
break
await asyncio.sleep(1)
zero_after = ms(closed_at) if after == 0 else None
mcp_sessions = {ca.session_id, cb.session_id}
billed = {}
for x in (a, b):
billed[x["browser_name"]] = total(await history(lambda s, i=x["session_id"]: s["session_id"] == i))
return {
"agents": [a, b],
"distinct_mcp_sessions": len(mcp_sessions),
"distinct_browser_sessions": len({a["session_id"], b["session_id"]}),
"unnamed": {"error": err, "text": text.split("\n")[0]},
"live_sessions_during": during,
"closed": closed,
"live_sessions_after": after,
"live_zero_after_ms": zero_after,
"thread_seconds": billed,
}
async def main():
fns = await functions()
fast = await browser(0)
paced = await browser(3000)
two = await named()
print(json.dumps({"language": "python", "functions": fns, "browser": fast, "browser_paced": paced, "named": two,
"measured_at": time.strftime("%Y-%m-%d", time.gmtime())}, indent=2, ensure_ascii=False))
asyncio.run(main())
// Maven: io.modelcontextprotocol.sdk:mcp:2.1.0, com.google.code.gson:gson:2.11.0
// env: CDPFLEET_API_KEY, PROXY_URL
import com.google.gson.*;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.regex.*;
import java.util.stream.*;
public class Main {
static final String API = "https://cdpfleet.com";
static final String KEY = System.getenv("CDPFLEET_API_KEY");
static final String PROXY = System.getenv("PROXY_URL");
static final String SINCE = Instant.now().minusSeconds(60).toString();
static final Pattern SESSION = Pattern.compile("session ([0-9a-f-]{36})");
static final HttpClient HTTP = HttpClient.newHttpClient();
// The same two reads both ways: the page as text, plus a few values picked by CSS selector.
record Target(String name, String url, Map<String, String> pick) {}
static final List<Target> TARGETS = List.of(
new Target("book", "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
orderedMap("title", "h1", "price", ".price_color", "stock", ".availability")),
new Target("wikipedia", "https://en.wikipedia.org/wiki/Web_scraping",
orderedMap("title", "h1", "updated", "#footer-info-lastmod")));
static Map<String, String> orderedMap(String... kv) {
var m = new LinkedHashMap<String, String>();
for (int i = 0; i < kv.length; i += 2) m.put(kv[i], kv[i + 1]);
return m;
}
// evaluate calls an arrow function given as text.
static String pickIn(Map<String, String> pick) {
String fields = pick.entrySet().stream().map(e -> e.getKey() + ": q(" + new Gson().toJson(e.getValue()) + ")").collect(Collectors.joining(", "));
return "() => { const q = (s) => document.querySelector(s)?.textContent.trim() ?? null; return { " + fields + " }; }";
}
// One MCP session over Streamable HTTP; a script authenticates with its API key as a bearer token.
// `seen` collects the MCP session ids the client sends (the transport adds the header itself).
static McpSyncClient connect(Set<String> seen) {
var transport = HttpClientStreamableHttpTransport.builder("https://cdpfleet.com")
.endpoint("/mcp")
.httpRequestCustomizer((builder, method, uri, body, ctx) -> {
builder.header("Authorization", "Bearer " + KEY);
builder.copy().build().headers().firstValue("mcp-session-id").ifPresent(seen::add);
})
.build();
var client = McpClient.sync(transport).requestTimeout(Duration.ofSeconds(120)).build();
client.initialize();
return client;
}
record Result(String text, boolean error) {}
static Result call(McpSyncClient client, List<Map<String, Object>> log, String name, Map<String, Object> args) {
long t = System.currentTimeMillis();
var r = client.callTool(new McpSchema.CallToolRequest(name, args));
String text = r.content().stream().filter(c -> c instanceof McpSchema.TextContent)
.map(c -> ((McpSchema.TextContent) c).text()).collect(Collectors.joining("\n"));
boolean error = Boolean.TRUE.equals(r.isError());
var entry = new LinkedHashMap<String, Object>();
entry.put("tool", name); entry.put("ms", System.currentTimeMillis() - t); entry.put("error", error);
synchronized (log) { log.add(entry); }
return new Result(text, error);
}
// A shared proxy drops the odd connection: one retry of a failed page load.
static Result retried(McpSyncClient client, List<Map<String, Object>> log, String name, Map<String, Object> args) {
var r = call(client, log, name, args);
return r.error() ? call(client, log, name, args) : r;
}
static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static String firstLine(String s) { return s.split("\n", 2)[0]; }
static String sessionId(String text) { var m = SESSION.matcher(text); return m.find() ? m.group(1) : ""; }
static Map<String, Object> with(Map<String, Object> base, String k, Object v) { var m = new LinkedHashMap<>(base); m.put(k, v); return m; }
static final Map<String, Object> LAUNCH = Map.of("browser", "chromium", "headless", true, "proxy", PROXY, "record", false);
// The account's history: a Function call is a "function:scrape" record, a browser its own session.
// Billed thread-seconds = (ended_at - started_at) × weight.
record Billed(String engine, int weight, double threadSeconds) {}
static List<Billed> history(Predicate<JsonObject> match) throws Exception {
for (int i = 0; i < 30; i++) {
var req = HttpRequest.newBuilder(URI.create(API + "/v1/me/sessions?limit=200&from=" + URLEncoder.encode(SINCE, StandardCharsets.UTF_8)))
.header("x-api-key", KEY).build();
var sessions = JsonParser.parseString(HTTP.send(req, HttpResponse.BodyHandlers.ofString()).body()).getAsJsonObject().getAsJsonArray("sessions");
var found = new ArrayList<JsonObject>();
for (var s : sessions) if (match.test(s.getAsJsonObject())) found.add(s.getAsJsonObject());
if (!found.isEmpty() && found.stream().allMatch(s -> !s.get("ended_at").isJsonNull())) {
return found.stream().map(s -> {
long ms = Duration.between(Instant.parse(s.get("started_at").getAsString()), Instant.parse(s.get("ended_at").getAsString())).toMillis();
int w = s.get("weight").getAsInt();
return new Billed(s.get("engine").getAsString(), w, Math.round(ms * w / 100.0) / 10.0);
}).toList();
}
Thread.sleep(2000);
}
return List.of();
}
static double total(List<Billed> records) { return Math.round(records.stream().mapToDouble(Billed::threadSeconds).sum() * 10) / 10.0; }
// ---- 1. Functions: one scrape call per page, no browser to drive.
static Map<String, Object> functions() throws Exception {
var log = new ArrayList<Map<String, Object>>();
var client = connect(new HashSet<>());
var start = Instant.now();
long t = System.currentTimeMillis();
var reads = new ArrayList<Map<String, Object>>();
for (var tg : TARGETS) {
var r = retried(client, log, "scrape", Map.of("url", tg.url(), "formats", List.of("markdown"), "extract", tg.pick()));
// "200 <url>\n\nextract: {…}\n\n--- markdown ---\n…"
var m = Pattern.compile("extract: (\\{[\\s\\S]*?\\n\\})").matcher(r.text());
var parts = r.text().split("--- markdown ---\n", 2);
var read = new LinkedHashMap<String, Object>();
read.put("page", tg.name());
read.put("status", r.text().split(" ", 2)[0]);
read.put("picked", m.find() ? JsonParser.parseString(m.group(1)) : null);
read.put("text_chars", parts.length > 1 ? parts[1].length() : 0);
reads.add(read);
}
long wall = System.currentTimeMillis() - t;
var end = Instant.now();
client.closeGracefully();
var billed = history(s -> s.get("engine").getAsString().equals("function:scrape")
&& !Instant.parse(s.get("started_at").getAsString()).isBefore(start.minusSeconds(1))
&& !Instant.parse(s.get("started_at").getAsString()).isAfter(end));
var out = new LinkedHashMap<String, Object>();
out.put("reads", reads); out.put("wall_ms", wall); out.put("records", billed.size()); out.put("thread_seconds", total(billed)); out.put("calls", log);
return out;
}
// ---- 2. Driving a browser: launch, then navigate + evaluate + snapshot per page, then close.
// pauseMs stands in for the model thinking between tool calls; the browser is billed meanwhile.
static Map<String, Object> browser(long pauseMs) throws Exception {
var log = new ArrayList<Map<String, Object>>();
var client = connect(new HashSet<>());
long t = System.currentTimeMillis();
var launched = call(client, log, "launch_browser", LAUNCH).text();
String sid = sessionId(launched);
var reads = new ArrayList<Map<String, Object>>();
for (var tg : TARGETS) {
sleep(pauseMs);
var nav = retried(client, log, "navigate", Map.of("url", tg.url()));
sleep(pauseMs);
var picked = JsonParser.parseString(call(client, log, "evaluate", Map.of("expression", pickIn(tg.pick()))).text());
sleep(pauseMs);
var snap = call(client, log, "snapshot", Map.of()).text();
var read = new LinkedHashMap<String, Object>();
read.put("page", tg.name()); read.put("status", nav.text().split(" ", 2)[0]); read.put("picked", picked); read.put("text_chars", snap.length());
reads.add(read);
}
sleep(pauseMs);
boolean closed = call(client, log, "close_browser", Map.of()).text().startsWith("Session " + sid + " ended");
long wall = System.currentTimeMillis() - t;
client.closeGracefully();
var billed = history(s -> s.get("session_id").getAsString().equals(sid));
var out = new LinkedHashMap<String, Object>();
out.put("pause_ms", pauseMs); out.put("session_id", sid); out.put("launched", launched.split("\\. ", 2)[0]); out.put("closed", closed);
out.put("reads", reads); out.put("wall_ms", wall);
out.put("engine", billed.isEmpty() ? null : billed.get(0).engine()); out.put("weight", billed.isEmpty() ? null : billed.get(0).weight());
out.put("thread_seconds", total(billed)); out.put("calls", log);
return out;
}
// ---- 3. Two agents on one key, each in its own MCP session, each with its own named browser.
record Agent(String name, McpSyncClient client, Set<String> mcp, List<Map<String, Object>> log, String sessionId, boolean asNamed, JsonElement seen) {}
static Agent agent(String name, String url) {
var log = new ArrayList<Map<String, Object>>();
var mcp = new HashSet<String>();
var client = connect(mcp);
var launched = call(client, log, "launch_browser", with(LAUNCH, "browser_name", name)).text();
retried(client, log, "navigate", Map.of("url", url, "browser_name", name));
var seen = JsonParser.parseString(call(client, log, "evaluate", Map.of("expression", "({ url: location.href, title: document.title })", "browser_name", name)).text());
return new Agent(name, client, mcp, log, sessionId(launched), launched.contains("as \"" + name + "\""), seen);
}
static Map<String, Object> named() throws Exception {
var fa = CompletableFuture.supplyAsync(() -> agent("research", TARGETS.get(0).url()));
var fb = CompletableFuture.supplyAsync(() -> agent("checkout", TARGETS.get(1).url()));
var a = fa.get();
var b = fb.get();
// Without browser_name, a tool drives "default" — which neither agent launched.
var unnamed = call(b.client(), b.log(), "navigate", Map.of("url", TARGETS.get(0).url()));
int during = JsonParser.parseString(call(a.client(), a.log(), "account", Map.of()).text()).getAsJsonObject().get("live_sessions").getAsInt();
var closed = new LinkedHashMap<String, Object>();
for (var x : List.of(a, b))
closed.put(x.name(), call(x.client(), x.log(), "close_browser", Map.of("browser_name", x.name())).text().startsWith("Session " + x.sessionId() + " ended"));
// The live count follows the router's view of the key: read it until both are gone (up to 15 s).
long closedAt = System.currentTimeMillis();
int after = -1;
for (int i = 0; i < 15; i++) {
after = JsonParser.parseString(call(a.client(), a.log(), "account", Map.of()).text()).getAsJsonObject().get("live_sessions").getAsInt();
if (after == 0) break;
sleep(1000);
}
Long zeroAfter = after == 0 ? System.currentTimeMillis() - closedAt : null;
for (var x : List.of(a, b)) x.client().closeGracefully();
var billed = new LinkedHashMap<String, Object>();
for (var x : List.of(a, b)) billed.put(x.name(), total(history(s -> s.get("session_id").getAsString().equals(x.sessionId()))));
var agents = new ArrayList<Map<String, Object>>();
for (var x : List.of(a, b)) {
var m = new LinkedHashMap<String, Object>();
m.put("browser_name", x.name()); m.put("as_named", x.asNamed()); m.put("session_id", x.sessionId()); m.put("seen", x.seen()); m.put("calls", x.log());
agents.add(m);
}
var mcpSessions = new HashSet<String>();
mcpSessions.addAll(a.mcp());
mcpSessions.addAll(b.mcp());
var out = new LinkedHashMap<String, Object>();
out.put("agents", agents);
out.put("distinct_mcp_sessions", mcpSessions.size());
out.put("distinct_browser_sessions", new HashSet<>(List.of(a.sessionId(), b.sessionId())).size());
out.put("unnamed", Map.of("error", unnamed.error(), "text", firstLine(unnamed.text())));
out.put("live_sessions_during", during);
out.put("closed", closed);
out.put("live_sessions_after", after);
out.put("live_zero_after_ms", zeroAfter);
out.put("thread_seconds", billed);
return out;
}
public static void main(String[] args) throws Exception {
var result = new LinkedHashMap<String, Object>();
result.put("language", "java");
result.put("functions", functions());
result.put("browser", browser(0));
result.put("browser_paced", browser(3000));
result.put("named", named());
result.put("measured_at", LocalDate.now(ZoneOffset.UTC).toString());
System.out.println(new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().create().toJson(result));
System.exit(0); // the SDK's HTTP client keeps non-daemon threads
}
}
// dotnet add package ModelContextProtocol --version 2.3.0
// env: CDPFLEET_API_KEY, PROXY_URL
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
var mcp = new Uri("https://cdpfleet.com/mcp");
const string Api = "https://cdpfleet.com";
var key = Environment.GetEnvironmentVariable("CDPFLEET_API_KEY")!;
var proxy = Environment.GetEnvironmentVariable("PROXY_URL")!;
var since = DateTime.UtcNow.AddMinutes(-1).ToString("o");
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Add("x-api-key", key);
// The same two reads both ways: the page as text, plus a few values picked by CSS selector.
var targets = new (string Name, string Url, (string Key, string Css)[] Pick)[]
{
("book", "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", new[] { ("title", "h1"), ("price", ".price_color"), ("stock", ".availability") }),
("wikipedia", "https://en.wikipedia.org/wiki/Web_scraping", new[] { ("title", "h1"), ("updated", "#footer-info-lastmod") }),
};
// evaluate calls an arrow function given as text.
static string PickIn((string Key, string Css)[] pick) =>
"() => { const q = (s) => document.querySelector(s)?.textContent.trim() ?? null; return { "
+ string.Join(", ", pick.Select(p => $"{p.Key}: q({JsonSerializer.Serialize(p.Css)})")) + " }; }";
// One MCP session over Streamable HTTP; a script authenticates with its API key as a bearer token.
Task<McpClient> Connect() => McpClient.CreateAsync(new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = mcp,
TransportMode = HttpTransportMode.StreamableHttp,
AdditionalHeaders = new Dictionary<string, string> { ["Authorization"] = $"Bearer {key}" },
OwnsSession = true,
}));
async Task<(string Text, bool Error)> Call(McpClient client, List<Dictionary<string, object?>> log, string name, Dictionary<string, object?>? args = null)
{
var sw = Stopwatch.StartNew();
var r = await client.CallToolAsync(name, args ?? new Dictionary<string, object?>());
var text = string.Join("\n", r.Content.OfType<TextContentBlock>().Select(c => c.Text));
lock (log) log.Add(new() { ["tool"] = name, ["ms"] = sw.ElapsedMilliseconds, ["error"] = r.IsError == true });
return (text, r.IsError == true);
}
// A shared proxy drops the odd connection: one retry of a failed page load.
async Task<(string Text, bool Error)> Retried(McpClient client, List<Dictionary<string, object?>> log, string name, Dictionary<string, object?> args)
{
var r = await Call(client, log, name, args);
return r.Error ? await Call(client, log, name, args) : r;
}
// The account's history: a Function call is a "function:scrape" record, a browser its own session.
// Billed thread-seconds = (ended_at - started_at) × weight.
async Task<List<(string Engine, int Weight, double ThreadSeconds)>> History(Func<JsonElement, bool> match)
{
for (var i = 0; i < 30; i++)
{
var body = await http.GetStringAsync($"{Api}/v1/me/sessions?limit=200&from={Uri.EscapeDataString(since)}");
var found = JsonDocument.Parse(body).RootElement.GetProperty("sessions").EnumerateArray().Where(match).ToList();
if (found.Count > 0 && found.All(s => s.GetProperty("ended_at").ValueKind == JsonValueKind.String))
return found.Select(s =>
{
var w = s.GetProperty("weight").GetInt32();
var ms = (s.GetProperty("ended_at").GetDateTime() - s.GetProperty("started_at").GetDateTime()).TotalMilliseconds;
return (s.GetProperty("engine").GetString()!, w, Math.Round(ms * w / 100) / 10);
}).ToList();
await Task.Delay(2000);
}
return new();
}
static double Total(List<(string Engine, int Weight, double ThreadSeconds)> records) => Math.Round(records.Sum(r => r.ThreadSeconds) * 10) / 10;
static string FirstLine(string s) => s.Split('\n')[0];
static JsonElement Json(string s) => JsonDocument.Parse(s).RootElement;
var sessionRe = new Regex("session ([0-9a-f-]{36})");
Dictionary<string, object?> LaunchArgs() => new() { ["browser"] = "chromium", ["headless"] = true, ["proxy"] = proxy, ["record"] = false };
// ---- 1. Functions: one scrape call per page, no browser to drive.
async Task<Dictionary<string, object?>> Functions()
{
var log = new List<Dictionary<string, object?>>();
var reads = new List<Dictionary<string, object?>>();
DateTime start, end;
long wall;
await using (var client = await Connect())
{
start = DateTime.UtcNow;
var sw = Stopwatch.StartNew();
foreach (var t in targets)
{
var (text, _) = await Retried(client, log, "scrape", new()
{
["url"] = t.Url, ["formats"] = new[] { "markdown" }, ["extract"] = t.Pick.ToDictionary(p => p.Key, p => p.Css),
});
// "200 <url>\n\nextract: {…}\n\n--- markdown ---\n…"
var m = Regex.Match(text, @"extract: (\{[\s\S]*?\n\})");
var parts = text.Split("--- markdown ---\n", 2);
reads.Add(new()
{
["page"] = t.Name, ["status"] = text.Split(' ')[0], ["picked"] = m.Success ? Json(m.Groups[1].Value) : null,
["text_chars"] = parts.Length > 1 ? parts[1].Length : 0,
});
}
wall = sw.ElapsedMilliseconds;
end = DateTime.UtcNow;
}
var billed = await History(s => s.GetProperty("engine").GetString() == "function:scrape"
&& s.GetProperty("started_at").GetDateTime().ToUniversalTime() >= start.AddSeconds(-1)
&& s.GetProperty("started_at").GetDateTime().ToUniversalTime() <= end);
return new() { ["reads"] = reads, ["wall_ms"] = wall, ["records"] = billed.Count, ["thread_seconds"] = Total(billed), ["calls"] = log };
}
// ---- 2. Driving a browser: launch, then navigate + evaluate + snapshot per page, then close.
// pauseMs stands in for the model thinking between tool calls; the browser is billed meanwhile.
async Task<Dictionary<string, object?>> Browser(int pauseMs)
{
var log = new List<Dictionary<string, object?>>();
var reads = new List<Dictionary<string, object?>>();
string launched, sid;
bool closed;
long wall;
await using (var client = await Connect())
{
var sw = Stopwatch.StartNew();
launched = (await Call(client, log, "launch_browser", LaunchArgs())).Text;
sid = sessionRe.Match(launched).Groups[1].Value;
foreach (var t in targets)
{
await Task.Delay(pauseMs);
var nav = await Retried(client, log, "navigate", new() { ["url"] = t.Url });
await Task.Delay(pauseMs);
var picked = Json((await Call(client, log, "evaluate", new() { ["expression"] = PickIn(t.Pick) })).Text);
await Task.Delay(pauseMs);
var snap = (await Call(client, log, "snapshot")).Text;
reads.Add(new() { ["page"] = t.Name, ["status"] = nav.Text.Split(' ')[0], ["picked"] = picked, ["text_chars"] = snap.Length });
}
await Task.Delay(pauseMs);
closed = (await Call(client, log, "close_browser")).Text.StartsWith($"Session {sid} ended");
wall = sw.ElapsedMilliseconds;
}
var billed = await History(s => s.GetProperty("session_id").GetString() == sid);
return new()
{
["pause_ms"] = pauseMs, ["session_id"] = sid, ["launched"] = launched.Split(". ")[0], ["closed"] = closed, ["reads"] = reads, ["wall_ms"] = wall,
["engine"] = billed.Count > 0 ? billed[0].Engine : null, ["weight"] = billed.Count > 0 ? billed[0].Weight : null,
["thread_seconds"] = Total(billed), ["calls"] = log,
};
}
// ---- 3. Two agents on one key, each in its own MCP session, each with its own named browser.
async Task<(string Name, McpClient Client, List<Dictionary<string, object?>> Log, string SessionId, bool AsNamed, JsonElement Seen)> Agent(string name, string url)
{
var log = new List<Dictionary<string, object?>>();
var client = await Connect();
var args = LaunchArgs();
args["browser_name"] = name;
var launched = (await Call(client, log, "launch_browser", args)).Text;
await Retried(client, log, "navigate", new() { ["url"] = url, ["browser_name"] = name });
var seen = Json((await Call(client, log, "evaluate", new() { ["expression"] = "({ url: location.href, title: document.title })", ["browser_name"] = name })).Text);
return (name, client, log, sessionRe.Match(launched).Groups[1].Value, launched.Contains($"as \"{name}\""), seen);
}
async Task<Dictionary<string, object?>> Named()
{
var both = await Task.WhenAll(Agent("research", targets[0].Url), Agent("checkout", targets[1].Url));
var (a, b) = (both[0], both[1]);
var mcpSessions = new HashSet<string?> { a.Client.SessionId, b.Client.SessionId };
// Without browser_name, a tool drives "default" — which neither agent launched.
var unnamed = await Call(b.Client, b.Log, "navigate", new() { ["url"] = targets[0].Url });
var during = Json((await Call(a.Client, a.Log, "account")).Text).GetProperty("live_sessions").GetInt32();
var closed = new Dictionary<string, object?>();
foreach (var x in both)
closed[x.Name] = (await Call(x.Client, x.Log, "close_browser", new() { ["browser_name"] = x.Name })).Text.StartsWith($"Session {x.SessionId} ended");
// The live count follows the router's view of the key: read it until both are gone (up to 15 s).
var sw = Stopwatch.StartNew();
var after = -1;
for (var i = 0; i < 15; i++)
{
after = Json((await Call(a.Client, a.Log, "account")).Text).GetProperty("live_sessions").GetInt32();
if (after == 0) break;
await Task.Delay(1000);
}
long? zeroAfter = after == 0 ? sw.ElapsedMilliseconds : null;
foreach (var x in both) await x.Client.DisposeAsync();
var billed = new Dictionary<string, object?>();
foreach (var x in both) billed[x.Name] = Total(await History(s => s.GetProperty("session_id").GetString() == x.SessionId));
return new()
{
["agents"] = both.Select(x => new Dictionary<string, object?> { ["browser_name"] = x.Name, ["as_named"] = x.AsNamed, ["session_id"] = x.SessionId, ["seen"] = x.Seen, ["calls"] = x.Log }).ToList(),
["distinct_mcp_sessions"] = mcpSessions.Count,
["distinct_browser_sessions"] = new HashSet<string> { a.SessionId, b.SessionId }.Count,
["unnamed"] = new Dictionary<string, object?> { ["error"] = unnamed.Error, ["text"] = FirstLine(unnamed.Text) },
["live_sessions_during"] = during,
["closed"] = closed,
["live_sessions_after"] = after,
["live_zero_after_ms"] = zeroAfter,
["thread_seconds"] = billed,
};
}
var fns = await Functions();
var fast = await Browser(0);
var paced = await Browser(3000);
var two = await Named();
Console.WriteLine(JsonSerializer.Serialize(new Dictionary<string, object?> { ["language"] = "csharp", ["functions"] = fns, ["browser"] = fast, ["browser_paced"] = paced, ["named"] = two, ["measured_at"] = DateTime.UtcNow.ToString("yyyy-MM-dd") },
new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }));
// No MCP SDK here: the official Go SDK needs Go 1.23+, so this speaks the protocol directly —
// JSON-RPC 2.0 over Streamable HTTP, with the standard library only.
// env: CDPFLEET_API_KEY, PROXY_URL
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
)
const mcpURL = "https://cdpfleet.com/mcp"
const api = "https://cdpfleet.com"
var key = os.Getenv("CDPFLEET_API_KEY")
var proxy = os.Getenv("PROXY_URL")
var httpc = &http.Client{Timeout: 120 * time.Second}
var since = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)
// The same two reads both ways: the page as text, plus a few values picked by CSS selector.
type Target struct {
Name, URL string
Pick [][2]string
}
var targets = []Target{
{"book", "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", [][2]string{{"title", "h1"}, {"price", ".price_color"}, {"stock", ".availability"}}},
{"wikipedia", "https://en.wikipedia.org/wiki/Web_scraping", [][2]string{{"title", "h1"}, {"updated", "#footer-info-lastmod"}}},
}
// evaluate calls an arrow function given as text.
func pickIn(pick [][2]string) string {
fields := []string{}
for _, p := range pick {
css, _ := json.Marshal(p[1])
fields = append(fields, fmt.Sprintf("%s: q(%s)", p[0], css))
}
return "() => { const q = (s) => document.querySelector(s)?.textContent.trim() ?? null; return { " + strings.Join(fields, ", ") + " }; }"
}
func pickMap(pick [][2]string) map[string]string {
m := map[string]string{}
for _, p := range pick {
m[p[0]] = p[1]
}
return m
}
type Call struct {
Tool string `json:"tool"`
Ms int64 `json:"ms"`
Error bool `json:"error"`
}
// One MCP session. A script authenticates with its API key as a bearer token.
type Conn struct {
session string
nextID int
}
// post sends one JSON-RPC message and returns the response for its id (the server answers
// with JSON or with a short event stream).
func (c *Conn) post(msg map[string]any) (map[string]any, error) {
body, _ := json.Marshal(msg)
req, _ := http.NewRequest("POST", mcpURL, bytes.NewReader(body))
req.Header.Set("authorization", "Bearer "+key)
req.Header.Set("content-type", "application/json")
req.Header.Set("accept", "application/json, text/event-stream")
req.Header.Set("mcp-protocol-version", "2025-06-18")
if c.session != "" {
req.Header.Set("mcp-session-id", c.session)
}
res, err := httpc.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if s := res.Header.Get("mcp-session-id"); s != "" {
c.session = s
}
if res.StatusCode == http.StatusAccepted { // a notification: nothing comes back
return nil, nil
}
if res.StatusCode != http.StatusOK {
b, _ := io.ReadAll(res.Body)
return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, b)
}
var payloads [][]byte
if strings.HasPrefix(res.Header.Get("content-type"), "text/event-stream") {
sc := bufio.NewScanner(res.Body)
sc.Buffer(make([]byte, 1<<20), 8<<20)
for sc.Scan() {
if line := sc.Text(); strings.HasPrefix(line, "data:") {
payloads = append(payloads, []byte(strings.TrimSpace(line[5:])))
}
}
} else {
b, _ := io.ReadAll(res.Body)
payloads = append(payloads, b)
}
for _, p := range payloads {
var m map[string]any
if json.Unmarshal(p, &m) == nil && m["id"] != nil && fmt.Sprint(m["id"]) == fmt.Sprint(msg["id"]) {
if e, ok := m["error"]; ok {
return nil, fmt.Errorf("JSON-RPC error: %v", e)
}
return m["result"].(map[string]any), nil
}
}
return nil, fmt.Errorf("no response for request %v", msg["id"])
}
func (c *Conn) request(method string, params map[string]any) (map[string]any, error) {
c.nextID++
return c.post(map[string]any{"jsonrpc": "2.0", "id": c.nextID, "method": method, "params": params})
}
func connect() (*Conn, error) {
c := &Conn{}
if _, err := c.request("initialize", map[string]any{
"protocolVersion": "2025-06-18", "capabilities": map[string]any{},
"clientInfo": map[string]any{"name": "cdpfleet-case-91", "version": "1.0.0"},
}); err != nil {
return nil, err
}
_, err := c.post(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"})
return c, err
}
// terminate ends the MCP session (DELETE), as a client does when it's done.
func (c *Conn) terminate() {
req, _ := http.NewRequest("DELETE", mcpURL, nil)
req.Header.Set("authorization", "Bearer "+key)
req.Header.Set("mcp-session-id", c.session)
if res, err := httpc.Do(req); err == nil {
res.Body.Close()
}
}
func (c *Conn) call(log *[]Call, name string, args map[string]any) (string, bool) {
t := time.Now()
r, err := c.request("tools/call", map[string]any{"name": name, "arguments": args})
if err != nil {
panic(err)
}
var parts []string
for _, item := range r["content"].([]any) {
if m := item.(map[string]any); m["type"] == "text" {
parts = append(parts, m["text"].(string))
}
}
isErr, _ := r["isError"].(bool)
*log = append(*log, Call{Tool: name, Ms: time.Since(t).Milliseconds(), Error: isErr})
return strings.Join(parts, "\n"), isErr
}
// A shared proxy drops the odd connection: one retry of a failed page load.
func (c *Conn) retried(log *[]Call, name string, args map[string]any) (string, bool) {
text, isErr := c.call(log, name, args)
if isErr {
return c.call(log, name, args)
}
return text, isErr
}
func firstLine(s string) string { return strings.SplitN(s, "\n", 2)[0] }
func parseJSON(s string) any { var v any; json.Unmarshal([]byte(s), &v); return v }
var sessionRe = regexp.MustCompile(`session ([0-9a-f-]{36})`)
var extractRe = regexp.MustCompile(`extract: (\{[\s\S]*?\n\})`)
func sessionID(text string) string {
if m := sessionRe.FindStringSubmatch(text); m != nil {
return m[1]
}
return ""
}
func launchArgs() map[string]any {
return map[string]any{"browser": "chromium", "headless": true, "proxy": proxy, "record": false}
}
// The account's history: a Function call is a "function:scrape" record, a browser its own session.
// Billed thread-seconds = (ended_at - started_at) × weight.
type Session struct {
SessionID string `json:"session_id"`
Engine string `json:"engine"`
Weight int `json:"weight"`
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at"`
}
func history(match func(Session) bool) []Session {
for i := 0; i < 30; i++ {
req, _ := http.NewRequest("GET", api+"/v1/me/sessions?limit=200&from="+url.QueryEscape(since), nil)
req.Header.Set("x-api-key", key)
res, err := httpc.Do(req)
if err != nil {
panic(err)
}
var body struct{ Sessions []Session }
json.NewDecoder(res.Body).Decode(&body)
res.Body.Close()
found, done := []Session{}, true
for _, s := range body.Sessions {
if match(s) {
found = append(found, s)
done = done && s.EndedAt != nil
}
}
if len(found) > 0 && done {
return found
}
time.Sleep(2 * time.Second)
}
return nil
}
func threadSeconds(s Session) float64 {
return math.Round(float64(s.EndedAt.Sub(s.StartedAt).Milliseconds()*int64(s.Weight))/100) / 10
}
func total(records []Session) float64 {
sum := 0.0
for _, s := range records {
sum += threadSeconds(s)
}
return math.Round(sum*10) / 10
}
// ---- 1. Functions: one scrape call per page, no browser to drive.
func functions() map[string]any {
log := []Call{}
c, err := connect()
if err != nil {
panic(err)
}
start := time.Now()
reads := []map[string]any{}
for _, tg := range targets {
text, _ := c.retried(&log, "scrape", map[string]any{"url": tg.URL, "formats": []string{"markdown"}, "extract": pickMap(tg.Pick)})
// "200 <url>\n\nextract: {…}\n\n--- markdown ---\n…"
var picked any
if m := extractRe.FindStringSubmatch(text); m != nil {
picked = parseJSON(m[1])
}
chars := 0
if parts := strings.SplitN(text, "--- markdown ---\n", 2); len(parts) > 1 {
chars = len([]rune(parts[1]))
}
reads = append(reads, map[string]any{"page": tg.Name, "status": strings.SplitN(text, " ", 2)[0], "picked": picked, "text_chars": chars})
}
wall := time.Since(start).Milliseconds()
end := time.Now()
c.terminate()
billed := history(func(s Session) bool {
return s.Engine == "function:scrape" && !s.StartedAt.Before(start.Add(-time.Second)) && !s.StartedAt.After(end)
})
return map[string]any{"reads": reads, "wall_ms": wall, "records": len(billed), "thread_seconds": total(billed), "calls": log}
}
// ---- 2. Driving a browser: launch, then navigate + evaluate + snapshot per page, then close.
// pause stands in for the model thinking between tool calls; the browser is billed meanwhile.
func browser(pause time.Duration) map[string]any {
log := []Call{}
c, err := connect()
if err != nil {
panic(err)
}
t := time.Now()
launched, _ := c.call(&log, "launch_browser", launchArgs())
sid := sessionID(launched)
reads := []map[string]any{}
for _, tg := range targets {
time.Sleep(pause)
nav, _ := c.retried(&log, "navigate", map[string]any{"url": tg.URL})
time.Sleep(pause)
picked, _ := c.call(&log, "evaluate", map[string]any{"expression": pickIn(tg.Pick)})
time.Sleep(pause)
snap, _ := c.call(&log, "snapshot", map[string]any{})
reads = append(reads, map[string]any{"page": tg.Name, "status": strings.SplitN(nav, " ", 2)[0], "picked": parseJSON(picked), "text_chars": len([]rune(snap))})
}
time.Sleep(pause)
closedText, _ := c.call(&log, "close_browser", map[string]any{})
wall := time.Since(t).Milliseconds()
c.terminate()
billed := history(func(s Session) bool { return s.SessionID == sid })
out := map[string]any{"pause_ms": pause.Milliseconds(), "session_id": sid, "launched": strings.SplitN(launched, ". ", 2)[0],
"closed": strings.HasPrefix(closedText, "Session "+sid+" ended"), "reads": reads, "wall_ms": wall,
"engine": nil, "weight": nil, "thread_seconds": total(billed), "calls": log}
if len(billed) > 0 {
out["engine"], out["weight"] = billed[0].Engine, billed[0].Weight
}
return out
}
// ---- 3. Two agents on one key, each in its own MCP session, each with its own named browser.
type Agent struct {
name, sessionID string
conn *Conn
log []Call
asNamed bool
seen any
}
func agent(name, pageURL string) *Agent {
c, err := connect()
if err != nil {
panic(err)
}
a := &Agent{name: name, conn: c}
args := launchArgs()
args["browser_name"] = name
launched, _ := c.call(&a.log, "launch_browser", args)
a.sessionID, a.asNamed = sessionID(launched), strings.Contains(launched, `as "`+name+`"`)
c.retried(&a.log, "navigate", map[string]any{"url": pageURL, "browser_name": name})
seen, _ := c.call(&a.log, "evaluate", map[string]any{"expression": "({ url: location.href, title: document.title })", "browser_name": name})
a.seen = parseJSON(seen)
return a
}
func liveSessions(a *Agent) int {
text, _ := a.conn.call(&a.log, "account", map[string]any{})
var acc struct {
LiveSessions int `json:"live_sessions"`
}
json.Unmarshal([]byte(text), &acc)
return acc.LiveSessions
}
func named() map[string]any {
var a, b *Agent
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); a = agent("research", targets[0].URL) }()
go func() { defer wg.Done(); b = agent("checkout", targets[1].URL) }()
wg.Wait()
// Without browser_name, a tool drives "default" — which neither agent launched.
unnamed, unnamedErr := b.conn.call(&b.log, "navigate", map[string]any{"url": targets[0].URL})
during := liveSessions(a)
closed := map[string]bool{}
for _, x := range []*Agent{a, b} {
text, _ := x.conn.call(&x.log, "close_browser", map[string]any{"browser_name": x.name})
closed[x.name] = strings.HasPrefix(text, "Session "+x.sessionID+" ended")
}
// The live count follows the router's view of the key: read it until both are gone (up to 15 s).
closedAt := time.Now()
after := -1
for i := 0; i < 15; i++ {
if after = liveSessions(a); after == 0 {
break
}
time.Sleep(time.Second)
}
var zeroAfter any
if after == 0 {
zeroAfter = time.Since(closedAt).Milliseconds()
}
mcpSessions := map[string]bool{a.conn.session: true, b.conn.session: true}
billed := map[string]float64{}
agents := []map[string]any{}
for _, x := range []*Agent{a, b} {
x.conn.terminate()
id := x.sessionID
billed[x.name] = total(history(func(s Session) bool { return s.SessionID == id }))
agents = append(agents, map[string]any{"browser_name": x.name, "as_named": x.asNamed, "session_id": x.sessionID, "seen": x.seen, "calls": x.log})
}
return map[string]any{
"agents": agents,
"distinct_mcp_sessions": len(mcpSessions),
"distinct_browser_sessions": len(map[string]bool{a.sessionID: true, b.sessionID: true}),
"unnamed": map[string]any{"error": unnamedErr, "text": firstLine(unnamed)},
"live_sessions_during": during,
"closed": closed,
"live_sessions_after": after,
"live_zero_after_ms": zeroAfter,
"thread_seconds": billed,
}
}
func main() {
out := map[string]any{"language": "go", "functions": functions(), "browser": browser(0), "browser_paced": browser(3 * time.Second)}
out["named"] = named()
out["measured_at"] = time.Now().UTC().Format("2006-01-02")
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
enc.Encode(out)
}
What we got
| Way | Tool calls | Time | Billed | What came back | Measured |
|---|---|---|---|---|---|
| Functions: scrape per page | 2 calls: scrape 5.7 s, scrape 7.6 s | 13.3 s | 13 thread-s (2 function:scrape records) | the book page: A Light in the Attic £51.77, In stock (22 available), Markdown 2,140 chars; the Wikipedia article: Web scraping, Markdown 24,872 chars | 2026-11-23 |
| Browser, calls back to back | 8 calls: launch_browser 0.6 s, navigate 2.6 s and 0.7 s, evaluate/snapshot/close 22–368 ms | 4.6 s | 4.3 thread-s (chromium, weight 1, launch to close) | the book page: A Light in the Attic £51.77, snapshot 2,615 chars; the Wikipedia article: Web scraping, snapshot 25,056 chars | 2026-11-23 |
| Browser, 3 s between calls | 8 calls: launch_browser 0.6 s, navigate 3.0 s and 1.7 s, evaluate/snapshot/close 22–234 ms | 26.8 s | 26.5 thread-s (chromium, weight 1, launch to close) | the book page: A Light in the Attic £51.77, snapshot 2,615 chars; the Wikipedia article: Web scraping, snapshot 25,056 chars | 2026-11-23 |
| Two agents on one key: browser_name "research" | 6 calls in its own MCP session | 4.8 thread-s | A Light in the Attic | Books to Scrape - Sandbox (closed its own browser) | 2026-11-23 | |
| Two agents on one key: browser_name "checkout" | 5 calls in its own MCP session | 4.9 thread-s | Web scraping - Wikipedia (closed its own browser) | 2026-11-23 | |
| Two agents on one key: a call without browser_name | navigate | refused: No browser named "default". Open: checkout, research (pass browser_name).; live sessions 2 while both ran, 0 after both closed | 2026-11-23 |
From the Node.js run on 2026-11-23. IP addresses are replaced with placeholders (203.0.113.x); equal addresses stay equal. The other languages produced the same findings.
Raw output (Node.js)
{
"language": "node",
"functions": {
"reads": [
{
"page": "book",
"status": "200",
"picked": {
"title": "A Light in the Attic",
"price": "£51.77",
"stock": "In stock (22 available)"
},
"text_chars": 2140
},
{
"page": "wikipedia",
"status": "200",
"picked": {
"title": "Web scraping",
"updated": "This page was last edited on 16 November 2026, at 04:13 (UTC)."
},
"text_chars": 24872
}
],
"wall_ms": 13290,
"records": 2,
"thread_seconds": 13,
"calls": [
{
"tool": "scrape",
"ms": 5654,
"error": false
},
{
"tool": "scrape",
"ms": 7636,
"error": false
}
]
},
"browser": {
"pause_ms": 0,
"session_id": "1c875bb8-0947-405d-88d9-67b6158dfcb5",
"launched": "Launched chromium 148.0.7778.96 (linux_headless, 1 thread(s)), session 1c875bb8-0947-405d-88d9-67b6158dfcb5",
"closed": true,
"reads": [
{
"page": "book",
"status": "200",
"picked": {
"title": "A Light in the Attic",
"price": "£51.77",
"stock": "In stock (22 available)"
},
"text_chars": 2615
},
{
"page": "wikipedia",
"status": "200",
"picked": {
"title": "Web scraping",
"updated": "This page was last edited on 16 November 2026, at 04:13 (UTC)."
},
"text_chars": 25056
}
],
"wall_ms": 4610,
"engine": "chromium",
"weight": 1,
"thread_seconds": 4.3,
"calls": [
{
"tool": "launch_browser",
"ms": 622,
"error": false
},
{
"tool": "navigate",
"ms": 2599,
"error": false
},
{
"tool": "evaluate",
"ms": 64,
"error": false
},
{
"tool": "snapshot",
"ms": 151,
"error": false
},
{
"tool": "navigate",
"ms": 711,
"error": false
},
{
"tool": "evaluate",
"ms": 64,
"error": false
},
{
"tool": "snapshot",
"ms": 368,
"error": false
},
{
"tool": "close_browser",
"ms": 22,
"error": false
}
]
},
"browser_paced": {
"pause_ms": 3000,
"session_id": "bc220d64-0c8e-4353-afbb-1e4200c73784",
"launched": "Launched chromium 148.0.7778.96 (linux_headless, 1 thread(s)), session bc220d64-0c8e-4353-afbb-1e4200c73784",
"closed": true,
"reads": [
{
"page": "book",
"status": "200",
"picked": {
"title": "A Light in the Attic",
"price": "£51.77",
"stock": "In stock (22 available)"
},
"text_chars": 2615
},
{
"page": "wikipedia",
"status": "200",
"picked": {
"title": "Web scraping",
"updated": "This page was last edited on 16 November 2026, at 04:13 (UTC)."
},
"text_chars": 25056
}
],
"wall_ms": 26832,
"engine": "chromium",
"weight": 1,
"thread_seconds": 26.5,
"calls": [
{
"tool": "launch_browser",
"ms": 594,
"error": false
},
{
"tool": "navigate",
"ms": 2968,
"error": false
},
{
"tool": "evaluate",
"ms": 67,
"error": false
},
{
"tool": "snapshot",
"ms": 128,
"error": false
},
{
"tool": "navigate",
"ms": 1747,
"error": false
},
{
"tool": "evaluate",
"ms": 72,
"error": false
},
{
"tool": "snapshot",
"ms": 234,
"error": false
},
{
"tool": "close_browser",
"ms": 22,
"error": false
}
]
},
"named": {
"agents": [
{
"browser_name": "research",
"as_named": true,
"session_id": "5a516f09-b0a8-4d89-b1ee-4907ef613225",
"seen": {
"url": "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
"title": "A Light in the Attic | Books to Scrape - Sandbox"
},
"calls": [
{
"tool": "launch_browser",
"ms": 769,
"error": false
},
{
"tool": "navigate",
"ms": 4178,
"error": false
},
{
"tool": "evaluate",
"ms": 58,
"error": false
},
{
"tool": "account",
"ms": 109,
"error": false
},
{
"tool": "close_browser",
"ms": 37,
"error": false
},
{
"tool": "account",
"ms": 103,
"error": false
}
]
},
{
"browser_name": "checkout",
"as_named": true,
"session_id": "e229eae4-d13a-45ef-9e7d-4a3ac0900917",
"seen": {
"url": "https://en.wikipedia.org/wiki/Web_scraping",
"title": "Web scraping - Wikipedia"
},
"calls": [
{
"tool": "launch_browser",
"ms": 432,
"error": false
},
{
"tool": "navigate",
"ms": 1861,
"error": false
},
{
"tool": "evaluate",
"ms": 29,
"error": false
},
{
"tool": "navigate",
"ms": 36,
"error": true
},
{
"tool": "close_browser",
"ms": 22,
"error": false
}
]
}
],
"distinct_mcp_sessions": 2,
"distinct_browser_sessions": 2,
"unnamed": {
"error": true,
"text": "No browser named \"default\". Open: checkout, research (pass browser_name)."
},
"live_sessions_during": 2,
"closed": {
"research": true,
"checkout": true
},
"live_sessions_after": 0,
"live_zero_after_ms": 103,
"thread_seconds": {
"research": 4.8,
"checkout": 4.9
}
},
"measured_at": "2026-11-23"
}Takeaways
- Back to back, the browser was 2–3× cheaper. On 2026-11-23, across five runs (one per language), the two
scrapecalls were billed 11.6–25.1 thread-seconds. The browser run reading the same two pages with calls back to back was billed 4.3–11.7: 2.1–3.0× less in every run.launch_browsertook 0.5–0.9 s,navigate0.7–8.7 s, andevaluate,snapshotandclose_browser22–400 ms each. Ascrapecall took 4.4–7.1 s for the book page and 6.9–20.9 s for the article: each call loads its page from scratch in a pooled browser, through an exit in a random country unless you setcountry. - At a model's pace,
scrapewas cheaper in all five runs. With 3 s before each of the seven calls after the launch, the browser run was billed 26.0–28.7 thread-seconds, against 11.6–25.1 for the twoscrapecalls. A browser is billed from launch to close, including the time a model spends reading a result and choosing the next call. Ascrapecall is billed only while it runs, so the thinking time costs nothing. - Billed time is wall time × one thread, both ways. The two
scrapecalls appeared in the history as twofunction:scraperecords, and each browser as onechromiumsession with weight 1. Each was billed 0.1–0.5 s less than the client waited. - Same values, similar amounts of text.
extractonscrapeand the same selectors inevaluatereturned identical title, price (£51.77) and stock ("In stock (22 available)") in every run. The book page came back as 2,140 characters of Markdown against a 2,615-character snapshot. The article came back as 24,834–24,872 characters of Markdown against a 25,056-character snapshot. That text is what the assistant reads, and it costs about the same either way. browser_namelets agents share a key. Two agents, each in its own MCP session on the same API key, launchedresearchandcheckoutat the same moment and drove them independently.accountshowed 2 live sessions. A call without a name was refused at once with "No browser named "default"", followed by the names of the open browsers. Each agent closed its own browser, and the live count was 0 within 77–156 ms. A key can hold up to 5 named browsers, and each counts against the plan's threads (MCP setup).- Which to use. Use
scrapewhen an assistant reads pages between conversation turns, when it needs a page from another country (country), or when it should not have to remember to close anything. Use a browser when one script makes calls back to back, when the agent needs several steps on one page, or when it has to log in or click through a site. To run several such agents on one key, give each its ownbrowser_name.