AI agents
Assistants such as ChatGPT, Claude and Perplexity now read pages, compare products and act for the people who ask them. AI crawlers collect pages for training and for AI search. Millimetry keeps every request an agent makes out of your visitors, sessions and funnels, and shows them on their own AI agents page. It shows which agent made each request, what it did, whether that worked, and for how many people.
How an agent is told from a person
Section titled “How an agent is told from a person”Millimetry uses four signals, strongest first. Only the first can be verified. Everything Millimetry reads off a request itself is a claim, because anyone can send a header.
| Signal | Example | Shown as |
|---|---|---|
| Your server says so | An agent signed in to your API over OAuth, or called your MCP server | Verified |
| A Web Bot Auth signature | Signature-Agent: "https://chatgpt.com" |
Claimed, or verified when Cloudflare has verified the bot (on plans that expose it to Workers) |
| A declared user-agent | ChatGPT-User/1.0, GPTBot/1.2, Claude-User |
Claimed |
| A browser driven by a script | navigator.webdriver, HeadlessChrome |
Automated browser |
What nobody can see. Some agents drive an ordinary browser and send an ordinary user-agent: Perplexity’s Comet, Claude for Chrome, Copilot Actions, and reportedly Grok. To Millimetry they look exactly like people, so they are counted as visitors. Telling them apart would take fingerprinting, which Millimetry does not do.
Three ways agents are seen
Section titled “Three ways agents are seen”The tracker (already on)
Section titled “The tracker (already on)”If your site has the tracker, assistants that run your pages’ JavaScript are already recorded as agents. So are browsers driven by a script, which is how most agent frameworks work. The tracker flags those as automated ("a": 1). There is nothing to set up.
Many agents never run JavaScript, though: a ChatGPT fetch, a crawler, a call to your API. The other two ways see those.
Your edge: the Cloudflare Worker
Section titled “Your edge: the Cloudflare Worker”The proxy Worker from Serve the tracker from your own domain can also report AI agents. Route it over the whole site (example.com/* instead of example.com/a/*) and set your site’s key. It passes every page through untouched and reports agents’ page loads in the background, not the scripts, stylesheets and images a browser fetches with them. It sends the host and path only: no query string, no address, no cookie.
"routes": [{ "pattern": "example.com/*", "zone_name": "example.com" }],"vars": { "MILLIMETRY_SITE_KEY": "wk_…", // all: every AI agent; people: only agents acting for a person; off: none "MILLIMETRY_AGENTS": "all"}A Worker on every route runs on every request, and that counts toward Cloudflare’s Workers pricing.
Your server: the middleware
Section titled “Your server: the middleware”Agents that call your API or your MCP server never touch a web page. A small middleware reports them, with what they did and whether it worked. It is one TypeScript file with no dependencies. It runs on Node 20+, Bun, Deno and Cloudflare Workers. Copy it into your project from the end of this page.
It authenticates with the app’s forwarding secret: in the app’s settings, under Forwarding secret, choose Create a secret. Apps and sites both have one. Keep it on your server, in an environment variable or a secret store, never in a browser or an app binary.
A fetch-style API (Hono, Cloudflare Workers, Next.js route handlers, Bun, Deno). People are never reported. Agents are recognised by their headers, or by your identify function when they sign in:
import { createAgentReporter, withAgentAnalytics } from "./millimetry-agents";
const agents = createAgentReporter({ key: "wk_…", secret: process.env.MILLIMETRY_FORWARDING_SECRET!,});
export default { fetch: withAgentAnalytics(agents, app.fetch, { // Your OAuth server knows which clients are agents and who they act for. identify: async (request) => { const token = await verifyAccessToken(request.headers.get("authorization")); if (!token?.client.isAgent) return undefined; // a person: not reported return { agent: token.client.name, // "ChatGPT", "acme-concierge" verified: true, scope: token.scopes.includes("orders:write") ? "write" : "read", principal: token.userId, // hashed before it leaves your server protocol: "oauth", }; }, }),};Each request is recorded as METHOD /path with the query string dropped, and identifiers in the path become :id. On Workers, the report goes out through ctx.waitUntil, so it is not cut off when the response is sent.
An MCP server. Every caller of an MCP server is an agent, so every tool call is reported, named by the client:
import { McpServer } from "@modelcontextprotocol/server";import { z } from "zod";import { createAgentReporter, trackTool } from "./millimetry-agents";
const agents = createAgentReporter({ key: "wk_…", secret: process.env.MILLIMETRY_FORWARDING_SECRET! });const server = new McpServer({ name: "shop", version: "1.0.0" });// Clients older than MCP 2026-07-28 name themselves once, in the initialize handshake.const client = () => server.server.getClientVersion()?.name; // "claude-ai", "ChatGPT", …
server.registerTool( "search_products", { description: "Search the catalog", inputSchema: z.object({ query: z.string() }) }, trackTool(agents, "search_products", async ({ query }) => ({ content: [{ type: "text", text: await search(query) }], }), { client }),);A tool result with isError: true, or a thrown error, is recorded as failed. When your MCP server checks bearer tokens, the call is marked verified and its scopes come from the SDK’s authInfo. The agent is named by the first of these that it has:
- Its OAuth client, when it is one Millimetry knows. MCP 2026-07-28 prefers Client ID Metadata Documents to dynamic registration, and the document’s URL is the client id:
https://claude.ai/oauth/mcp-oauth-client-metadatais Claude (claude.ai, the Claude apps and Cowork),https://claude.ai/oauth/claude-code-client-metadatais Claude Code, and ChatGPT’s documents underhttps://chatgpt.com/oauth/are ChatGPT. Your authorization server checked that client, so it outranks the name a client gives itself. - The name the client sends with each request, in
_meta["io.modelcontextprotocol/clientInfo"]. MCP 2026-07-28 clients send it instead of theinitializehandshake. client, for clients that still useinitialize.
Any other OAuth client id is never sent: with dynamic registration it is a lasting identifier for one install. agentFromClientId is exported too, for an identify of your own. trackTool works with the TypeScript SDK’s v2 (@modelcontextprotocol/server) and v1 (@modelcontextprotocol/sdk, where McpServer comes from @modelcontextprotocol/sdk/server/mcp.js and inputSchema is a plain object of fields).
Anything else (Express, Fastify, a queue worker): call agents.record() yourself.
app.use((req, res, next) => { const identity = identifyAgent(req); // undefined for people if (!identity) return next(); const started = Date.now(); res.on("finish", () => agents.record({ ...identity, action: `${req.method} ${req.route?.path ?? req.path}`, status: res.statusCode, ms: Date.now() - started, }), ); next();});Who the agent acts for
Section titled “Who the agent acts for”Pass your own user id as principal, and the dashboard counts how many people your agents served. The middleware hashes it with SHA-256 before it leaves your server. Millimetry then hashes that again with the same salt it uses for visitors, which changes every day. So People served counts each person once a day, and nobody can be followed from one day to the next. Leave principal out and the agent is still counted.
What is stored
Section titled “What is stored”| Kept | Never kept |
|---|---|
| The agent’s name, its operator (OpenAI, Anthropic, …) and kind (assistant, agentic browser, crawler, automation) | The user-agent string |
| Where it came in: web, API, MCP, or your own agent | IP addresses |
The page path, endpoint or tool, with identifiers as :id |
Query strings |
The status, and whether it worked, failed, was denied, or asked for something you don’t offer (missing) |
Your user ids (only a hash that rotates daily) |
| Read or write access, the protocol, how long it took | Request or response bodies |
Agent requests are kept for 25 months, like events, and deleted with the app. They are never mixed into visitors, sessions, funnels, paths or exports of events.
How requests ended, and what was proved
Section titled “How requests ended, and what was proved”The agents table says, for each agent, how its requests ended (ok, errors, denied) and how many were verified. Only your server, when the agent signed in, or Cloudflare’s verified-bot flag can prove who an agent is; a user-agent or a Signature-Agent header Millimetry read is a claim, because anyone can send one. The page and the MCP tool keep the two apart, and so should you when you read them.
Asked for, not offered
Section titled “Asked for, not offered”When an agent calls a tool your MCP server does not have, or an endpoint that does not exist, that is not a failure: it is a list of what to build next. Report it with outcome: "missing", and the agents page lists those requests on their own under Asked for, not offered, with how many agents asked. The middleware does it in one call, where your server answers a tools/call for an unknown name:
unknownTool(agents, request.params.name, ctx);Funnels across tools
Section titled “Funnels across tools”“Of the agents that called search, how many went on to checkout?” POST /api/v1/apps/{id}/agents/funnel (the run_agent_funnel tool) takes 2 to 8 targets as the agents report lists them and counts the people the agents acted for who reached each one within the window, the way a funnel counts sessions. It follows a principal, so requests with none (crawlers, and servers that report none) are left out, and the window is a day at most: a principal’s hash rotates daily.
ChatGPT apps
Section titled “ChatGPT apps”A ChatGPT app is an MCP server ChatGPT calls, and ChatGPT ships no analytics for it. withAppAnalytics is trackTool for that case: the agent is ChatGPT whenever the request carries an openai/ metadata key or ChatGPT’s client metadata document, and the person the app acts for is your token check’s OAuth subject, hashed before it leaves your server:
const app = withAppAnalytics(agents);server.registerTool("search", { inputSchema }, app.tool("search", handler));// where your server answers an unknown tool:app.unknown(request.params.name, ctx);Millimetry reports on itself
Section titled “Millimetry reports on itself”Millimetry’s own MCP server reports every tool call to Millimetry’s own account the same way, as verified requests on the mcp channel: the client’s name, the tool, how it went and the scope, never the arguments or the answer. The agents page on the landing page is that data.
Visitors from answers
Section titled “Visitors from answers”Agents are one half. The other is the people an assistant’s answer sends to the site: they arrive as visitors, with the assistant as their referrer, and are filed under the AI assistants channel. The AI traffic page puts the two side by side: crawled, fetched for people, visitors from answers, and what those visitors did.
Counting toward your plan
Section titled “Counting toward your plan”Every agent request Millimetry stores counts as one event. Other bots are dropped and do not count. AI crawlers can make a lot of requests. To keep them out, set the Worker’s MILLIMETRY_AGENTS to people, or send "skip": ["crawler"] from your own code.
Agents Millimetry names
Section titled “Agents Millimetry names”| Acting for a person | Crawling for training or AI search |
|---|---|
ChatGPT (ChatGPT-User), the ChatGPT agent (signed) |
GPTBot, OAI-SearchBot (OpenAI) |
Claude (Claude-User), Claude Code |
ClaudeBot, Claude-SearchBot (Anthropic) |
Perplexity (Perplexity-User) |
PerplexityBot |
Meta AI (Meta-ExternalFetcher) |
Meta-ExternalAgent |
Le Chat (MistralAI-User) |
CCBot (Common Crawl), Bytespider, Amazonbot |
| Google Agent, NotebookLM, Firecrawl | Google-CloudVertexBot, DuckAssistBot, Cohere, Diffbot, AI2Bot |
Search engines’ own crawlers, like Googlebot and Bingbot, are ordinary bots: dropped, never stored. A name your server reports that isn’t on this list is shown as you sent it, and common spellings are folded together (chatgpt and OpenAI both become ChatGPT).
Agents that sign in
Section titled “Agents that sign in”Agents increasingly sign in to the businesses they act for, so your server knows exactly which agent and which customer it is dealing with. That happens over OAuth, MCP, or the Personal Agent Protocol that Sierra and Meta announced in October 2026. Report those requests with verified: true and the protocol’s name ("pap", "mcp", "oauth"). The Personal Agent Protocol’s specification hasn’t been published yet. Until it is, send the client’s name and the protocol yourself, as above.
The API behind it
Section titled “The API behind it”The middleware and the Worker post to POST /v1/agent/events, and the dashboard reads GET /api/v1/apps/{id}/agents. Both are documented in the reference.
The middleware file
Section titled “The middleware file”// Millimetry agents: report the AI agents that use your API or MCP server (spec §7.5).//// One file, no dependencies: copy it into your server. It runs anywhere with fetch and Web Crypto// (Node 20+, Bun, Deno, Cloudflare Workers). Requests from people are never reported, only agents,// and nothing here sends an address, a cookie, a query string or a raw user id://// const agents = createAgentReporter({ key: "wk_…", secret: process.env.MILLIMETRY_FORWARDING_SECRET });// export default withAgentAnalytics(agents, handler, { identify }); // fetch-style handlers// server.registerTool("search", config, trackTool(agents, "search", search, { client })); // MCP//// The secret is the app's forwarding secret from the Millimetry dashboard. It proves the reports// come from your server, so keep it there: never in a browser, an app binary or source control.
/** Where the agent reached you: the website, your API, your MCP server, or your own agent. */export type Channel = "web" | "api" | "mcp" | "agent";
/** Who is calling, as far as your server knows. */export interface AgentIdentity { /** The agent's name as your server knows it: an OAuth client, an MCP client's name. */ agent?: string; /** True when your server verified the agent: it signed in, or its signature checked out. */ verified?: boolean; /** The access the person granted it. */ scope?: "read" | "write"; /** * Who the agent acts for: your own user id. It is hashed with SHA-256 here, before it leaves * your server, and Millimetry hashes that again with a salt that changes every day, so it can * count people per day and never follow one. */ principal?: string; /** The protocol the agent used: `pap`, `mcp`, `oauth`, `a2a`, … */ protocol?: string;}
/** One agent request. Everything is optional; send what you know. */export interface AgentEvent extends AgentIdentity { channel?: Channel; /** The agent's user-agent: Millimetry reads it to name the agent, then drops it. */ userAgent?: string; /** The `Signature-Agent` header (Web Bot Auth), read to name the agent and dropped. */ signatureAgent?: string; /** A page or endpoint URL: only its host and path are kept. */ url?: string; /** What the agent did when there is no URL: a tool name, `orders.create`, `GET /orders/:id`. */ action?: string; /** The HTTP status the agent got. */ status?: number; /** Derived from `status` when absent. */ /** `missing`: the agent asked for a tool, endpoint or page you don't offer (what to build next). */ outcome?: "ok" | "error" | "denied" | "missing"; /** How long the request took, in milliseconds. */ ms?: number; /** When it happened; now by default. */ ts?: Date;}
export interface AgentReporterOptions { /** The app's or site's key: `ak_…` or `wk_…`. */ key: string; /** The app's forwarding secret (`fs_…`). Server-side only. */ secret: string; /** The ingest host; Millimetry's by default. */ host?: string; /** Send to the Debug view (kept 30 days) instead of the real one. */ debug?: boolean; /** Events per request, at most 100. */ batchSize?: number; /** How long to gather events before sending; 0 sends each one at once. */ flushIntervalMs?: number; /** Events held at most while Millimetry is unreachable; newer ones are dropped past it. */ maxQueue?: number; /** Reports are never thrown at your code; they come here instead. */ onError?: (error: unknown) => void; /** For tests. */ fetch?: typeof fetch;}
export interface AgentReporter { /** Queues one agent request. Never throws, never blocks. */ record(event: AgentEvent): void; /** * Sends one agent request now, apart from the queue: for platforms where each request is its own * world (Cloudflare Workers), hand it to `ctx.waitUntil(agents.send(event))`. Never rejects. */ send(event: AgentEvent): Promise<void>; /** * Sends what is queued. On Cloudflare Workers and other platforms that stop work when the * response is sent, hand it to `ctx.waitUntil(agents.flush())`. */ flush(): Promise<void>; /** Sends what is queued and stops the timer. */ close(): Promise<void>;}
/** The wire shape of `POST /v1/agent/events` (one event). */interface WireEvent { ts: string; via: "server"; agent?: string; ua?: string; signature_agent?: string; verified?: boolean; channel?: Channel; protocol?: string; url?: string; action?: string; status?: number; outcome?: string; scope?: string; principal?: string; ms?: number;}
const MAX_BATCH = 100;
/** SHA-256 of `value`, as lowercase hex, so a raw user id never leaves the server. */export async function hashPrincipal(value: string): Promise<string> { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}
async function toWire(event: AgentEvent): Promise<WireEvent> { return { ts: (event.ts ?? new Date()).toISOString(), via: "server", agent: event.agent, ua: event.userAgent?.slice(0, 512), signature_agent: event.signatureAgent?.slice(0, 512), verified: event.verified, channel: event.channel, protocol: event.protocol, url: event.url, action: event.action, status: event.status, outcome: event.outcome, scope: event.scope, principal: event.principal === undefined ? undefined : await hashPrincipal(event.principal), ms: event.ms === undefined ? undefined : Math.max(0, Math.round(event.ms)), };}
export function createAgentReporter(options: AgentReporterOptions): AgentReporter { const host = (options.host ?? "https://e.millimetry.app").replace(/\/$/, ""); const batchSize = Math.min(MAX_BATCH, Math.max(1, options.batchSize ?? 50)); const interval = options.flushIntervalMs ?? 5_000; const maxQueue = options.maxQueue ?? 1_000; const fetcher = options.fetch ?? fetch; const onError = options.onError ?? (() => {}); let queue: Promise<WireEvent | undefined>[] = []; let timer: ReturnType<typeof setTimeout> | undefined;
// An event that cannot be put on the wire (an invalid date, no Web Crypto) is reported to // onError and left out; it never becomes an unhandled rejection in the host process. const wire = (event: AgentEvent): Promise<WireEvent | undefined> => toWire(event).catch((error: unknown) => { onError(error); return undefined; });
const post = async (events: WireEvent[]): Promise<void> => { if (events.length === 0) return; try { const response = await fetcher(`${host}/v1/agent/events`, { method: "POST", headers: { "content-type": "application/json", "x-forwarding-secret": options.secret, }, body: JSON.stringify({ k: options.key, debug: options.debug ?? false, events }), }); await response.body?.cancel(); if (!response.ok) onError(new Error(`millimetry: agent events answered ${response.status}`)); } catch (error) { // At most once: a report lost to an outage is not retried, so nothing is counted twice. onError(error); } };
const flush = async (): Promise<void> => { if (timer !== undefined) { clearTimeout(timer); timer = undefined; } const taken = queue; queue = []; const events = (await Promise.all(taken)).filter((e): e is WireEvent => e !== undefined); for (let i = 0; i < events.length; i += batchSize) { await post(events.slice(i, i + batchSize)); } };
return { record(event) { if (queue.length >= maxQueue) { onError(new Error("millimetry: agent event queue is full; event dropped")); return; } queue.push(wire(event)); if (queue.length >= batchSize || interval === 0) { void flush(); } else if (timer === undefined) { timer = setTimeout(() => void flush(), interval); // A pending report must not keep a Node process alive. (timer as { unref?: () => void }).unref?.(); } }, async send(event) { const one = await wire(event); if (one) await post([one]); }, flush, close: flush, };}
// ------------------------------------------------------------------------------- HTTP handlers
/** * A first look at whether a request comes from an AI agent: the tokens of the agents Millimetry * knows (a test keeps this in step with the server), a headless browser, or a Web Bot Auth * signature. Millimetry names the agent; requests from people are never sent. */const AGENT_TOKENS = /chatgpt-user|claude-user|claude-code|perplexity-user|mistralai-user|meta-externalfetcher|google-agent|google-notebooklm|firecrawlagent|oai-searchbot|claude-searchbot|perplexitybot|duckassistbot|google-cloudvertexbot|gptbot|claudebot|anthropic-ai|meta-externalagent|ccbot|bytespider|amazonbot|cohere-ai|cohere-training-data-crawler|diffbot|ai2bot|headlesschrome/i;
/** The agent behind a request, from its headers alone, or undefined for anyone else. */export function agentFromHeaders(headers: Headers): AgentEvent | undefined { const userAgent = headers.get("user-agent") ?? ""; const signatureAgent = headers.get("signature-agent") ?? undefined; if (!AGENT_TOKENS.test(userAgent) && signatureAgent === undefined) return undefined; return { userAgent, signatureAgent };}
/** `GET /orders/8231`: the method and path, never the query string. */function defaultAction(request: Request): string { return `${request.method} ${new URL(request.url).pathname}`;}
export interface HandlerOptions { /** * Who is calling. Return the agent's identity (an OAuth client you know is an agent, the user it * acts for), or undefined for a person, who is then not reported. By default, agents are told * from their headers (`agentFromHeaders`). */ identify?: (request: Request) => AgentIdentity | undefined | Promise<AgentIdentity | undefined>; /** What to record as the action; `METHOD /path` by default (Millimetry turns ids into `:id`). */ action?: (request: Request) => string; /** `api` by default. */ channel?: Channel; /** Called when `identify` or `action` throws; the request is still served. */ onError?: (error: unknown) => void;}
/** The execution context Cloudflare Workers (and Hono on Workers) pass after the request. */interface WaitUntil { waitUntil(promise: Promise<unknown>): void;}
function waitUntilOf(args: readonly unknown[]): WaitUntil | undefined { for (const arg of args) { if (typeof (arg as Partial<WaitUntil> | null)?.waitUntil === "function") { return arg as WaitUntil; } } return undefined;}
/** * Wraps a fetch-style handler (`(request) => Response`: Hono, Cloudflare Workers, Next.js route * handlers, Bun, Deno) so each request an AI agent makes is reported with its status and timing. * When the platform passes an execution context (Workers' `ctx`), the report is sent through its * `waitUntil`, so it is not cut off when the response goes out. */export function withAgentAnalytics<Rest extends unknown[]>( reporter: AgentReporter, handler: (request: Request, ...rest: Rest) => Response | Promise<Response>, options: HandlerOptions = {},): (request: Request, ...rest: Rest) => Promise<Response> { return async (request, ...rest) => { const fromHeaders = agentFromHeaders(request.headers); let identity: AgentIdentity | undefined; try { identity = options.identify ? await options.identify(request) : fromHeaders; } catch (error) { // An identify function that fails must not take the request down: it goes through unreported. options.onError?.(error); } if (identity === undefined) return handler(request, ...rest);
let action: string; try { action = (options.action ?? defaultAction)(request); } catch (error) { options.onError?.(error); action = defaultAction(request); } const base: AgentEvent = { ...fromHeaders, ...identity, channel: options.channel ?? "api", action, }; // On Workers each request sends its own report through waitUntil; elsewhere it is queued. const ctx = waitUntilOf(rest); const report = (event: AgentEvent) => ctx ? ctx.waitUntil(reporter.send(event)) : reporter.record(event); const started = Date.now(); try { const response = await handler(request, ...rest); report({ ...base, status: response.status, ms: Date.now() - started }); return response; } catch (error) { report({ ...base, status: 500, ms: Date.now() - started }); throw error; } };}
// ------------------------------------------------------------------------------------- MCP tools
/** * What an MCP server's tool handler receives as its last argument, as far as this file reads it: * `extra` in the TypeScript SDK's v1 (`@modelcontextprotocol/sdk`), `ctx` in v2 * (`@modelcontextprotocol/server`). *//** The SDKs' `AuthInfo`, as far as the middleware reads it. */export interface ToolAuthInfo { clientId?: string; scopes?: string[]; /** What your token check put there: an OAuth `sub`, say. */ extra?: Record<string, unknown>;}
export interface ToolExtra { /** v1: set when the server checks bearer tokens. */ authInfo?: ToolAuthInfo; /** v1: the request's `_meta`, where a client on MCP 2026-07-28 names itself. */ _meta?: unknown; /** v2: the request; `envelope` holds the 2026-07-28 keys, lifted out of its `_meta`. */ mcpReq?: { envelope?: unknown }; /** v2: set when the server checks bearer tokens. */ http?: { authInfo?: ToolAuthInfo };}
export interface ToolOptions<Extra> { /** Who is calling; by default verified when the SDK's `authInfo` carries an OAuth client. */ identify?: (extra: Extra) => AgentIdentity | undefined; /** * The client's name for clients older than MCP 2026-07-28, which name themselves once, in the * `initialize` handshake: `() => server.server.getClientVersion()?.name` (`claude-ai`, * `ChatGPT`). Newer clients name themselves on every request, and that name comes first. */ client?: () => string | undefined;}
/** The `_meta` key under which an MCP 2026-07-28 client names itself on every request. */const CLIENT_INFO = "io.modelcontextprotocol/clientInfo";
/** * OAuth clients that identify with a Client ID Metadata Document, which MCP 2026-07-28 prefers to * dynamic registration. The document's URL is the client id and is the same for every install, so * it names the client. `*` stands for one path segment (ChatGPT's documents per callback). A test * keeps this in step with the server; any other client id never leaves your server. */const CLIENT_METADATA: readonly (readonly [url: string, name: string])[] = [ ["https://claude.ai/oauth/mcp-oauth-client-metadata", "Claude"], ["https://claude.ai/oauth/claude-code-client-metadata", "Claude Code"], ["https://chatgpt.com/oauth/client.json", "ChatGPT"], ["https://chatgpt.com/oauth/*/client.json", "ChatGPT"],];
/** The one path segment a `*` in `CLIENT_METADATA` stands for. */const CLIENT_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
/** * The client an OAuth client id names when it is a known Client ID Metadata Document * (`https://claude.ai/oauth/claude-code-client-metadata` is `Claude Code`), compared exactly, as * authorization servers compare client ids. Undefined for any other id: under dynamic registration * a client id is a lasting per-install identifier, never a name. */export function agentFromClientId(clientId: string | undefined): string | undefined { if (typeof clientId !== "string") return undefined; for (const [url, name] of CLIENT_METADATA) { const [prefix = "", suffix] = url.split("*"); const matches = suffix === undefined ? clientId === url : clientId.startsWith(prefix) && clientId.endsWith(suffix) && CLIENT_SEGMENT.test(clientId.slice(prefix.length, clientId.length - suffix.length)); if (matches) return name; } return undefined;}
/** A lone UTF-16 surrogate: JSON can carry it, but Millimetry refuses the whole report over it. */const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
/** * The name a client gives itself (`claude-ai`, `ChatGPT`). Any client can send anything here, so * only a short, well-formed string counts, and one client cannot spoil the reports its calls travel * with. Millimetry keeps 64 characters of a name. */function selfReportedName(value: unknown): string | undefined { if (typeof value !== "string") return undefined; const name = value.trim(); return name !== "" && name.length <= 128 && !LONE_SURROGATE.test(name) ? name : undefined;}
/** The name the client gave on this request, in `_meta["io.modelcontextprotocol/clientInfo"]`. */function requestClientName(extra: ToolExtra | undefined): string | undefined { // v2 lifts the key out of `_meta` into `ctx.mcpReq.envelope`; v1 hands `_meta` over as sent. for (const meta of [extra?.mcpReq?.envelope, extra?._meta]) { const info = (meta as Record<string, unknown> | null | undefined)?.[CLIENT_INFO]; const name = selfReportedName((info as { name?: unknown } | null | undefined)?.name); if (name !== undefined) return name; } return undefined;}
/** `read()`, or undefined when it throws: naming an agent never takes a tool call down. */function safely<T>(read: () => T): T | undefined { try { return read(); } catch { return undefined; }}
function scopeOf(scopes: string[] | undefined): "read" | "write" | undefined { if (!scopes || scopes.length === 0) return undefined; return scopes.some((s) => /write/i.test(s)) ? "write" : "read";}
/** * Who is calling a tool: your `identify` if it gave an identity; else verified when the SDK's * `authInfo` carries an OAuth client, with the scope the scopes say. The name: yours if identify * gave one; else the client a known metadata document names, which your authorization server * checked; else the name the client gives itself, on this request (MCP 2026-07-28) or at * `initialize` (`client`). Never any other OAuth client id. */export function identityOf<Extra extends ToolExtra>( extra: Extra | undefined, options: ToolOptions<Extra> = {},): AgentIdentity { const auth = extra?.authInfo ?? extra?.http?.authInfo; const custom = safely(() => (extra === undefined ? undefined : options.identify?.(extra))); const agent = custom?.agent ?? agentFromClientId(auth?.clientId) ?? safely(() => requestClientName(extra)) ?? safely(() => selfReportedName(options.client?.())); const identity: AgentIdentity = custom ?? { verified: auth?.clientId !== undefined, scope: scopeOf(auth?.scopes), }; return { ...identity, agent };}
/** * Reports a request for a tool your server does not offer (`outcome: missing`): the Millimetry * dashboard lists what agents asked for and did not get, which is what to build next. Call it * where your server answers a `tools/call` for an unknown name (the SDK's not-found path), then * answer as you did before. */export function unknownTool<Extra extends ToolExtra>( reporter: AgentReporter, name: string, extra?: Extra, options: ToolOptions<Extra> = {},): void { reporter.record({ protocol: "mcp", ...identityOf(extra, options), channel: "mcp", action: name, status: 404, outcome: "missing", });}
/** * For a ChatGPT app (OpenAI's Apps SDK, an MCP server ChatGPT calls): the same as `trackTool`, * with the agent named ChatGPT whenever the request carries an `openai/` metadata key or * ChatGPT's metadata document, and the person the app acts for taken from your token check's * OAuth subject (`authInfo.extra.sub`), hashed before it leaves your server. `tool` wraps a * handler; `unknown` reports a tool ChatGPT asked for that you don't offer. */export function withAppAnalytics<Extra extends ToolExtra>( reporter: AgentReporter, options: ToolOptions<Extra> = {},): { tool: <Args, Result>( name: string, handler: (args: Args, extra: Extra) => Result | Promise<Result>, ) => (args: Args, extra: Extra) => Promise<Result>; unknown: (name: string, extra?: Extra) => void;} { const identify = (extra: Extra): AgentIdentity => { const base = identityOf(extra, options); const auth = extra?.authInfo ?? extra?.http?.authInfo; const sub = auth?.extra?.sub ?? auth?.extra?.subject; const fromChatGPT = base.agent === "ChatGPT" || [extra?.mcpReq?.envelope, extra?._meta].some( (meta) => meta !== null && typeof meta === "object" && Object.keys(meta as object).some((key) => key.startsWith("openai/")), ); return { ...base, agent: fromChatGPT ? "ChatGPT" : base.agent, principal: typeof sub === "string" && sub !== "" ? sub : base.principal, }; }; const wrapped: ToolOptions<Extra> = { ...options, identify }; return { tool: (name, handler) => trackTool(reporter, name, handler, wrapped), unknown: (name, extra) => unknownTool(reporter, name, extra, wrapped), };}
/** * Wraps an MCP tool handler so every call is reported: on an MCP server every caller is an agent. * A result with `isError: true` or a thrown error is recorded as an error. Works with the * TypeScript SDK's v1 and v2. */export function trackTool<Args, Extra extends ToolExtra, Result>( reporter: AgentReporter, name: string, handler: (args: Args, extra: Extra) => Result | Promise<Result>, options: ToolOptions<Extra> = {},): (args: Args, extra: Extra) => Promise<Result> { return async (args, extra) => { const base: AgentEvent = { protocol: "mcp", ...identityOf(extra, options), channel: "mcp", action: name, }; const started = Date.now(); try { const result = await handler(args, extra); const failed = (result as { isError?: unknown } | undefined)?.isError === true; reporter.record({ ...base, outcome: failed ? "error" : "ok", ms: Date.now() - started }); return result; } catch (error) { reporter.record({ ...base, outcome: "error", ms: Date.now() - started }); throw error; } };}