# Agent & MCP analytics

AI agents and MCP clients do not run browser JavaScript, so the browser client never sees them. `@visibling/sdk/agent` is a one-file middleware for the server edge: it classifies each request, records where the agent went, and reports the request where it stopped. It works in Cloudflare Workers, Next.js middleware, and Express, and it never stores a raw IP address or User-Agent string.

Use the Agent & MCP analytics dashboard when you need to answer questions such as "which agents are hitting my site?", "are they finding the docs?", and "why are agents failing to onboard?" The same data is available to a coding agent through the read-only `get_agent_analytics` and `get_agent_trail` MCP tools.

## Privacy-first daily nicknames

Every agent event carries a native distinct id shaped `agent:<utcDate>:<family>:<nickname>`, for example `agent:2026-12-04:claude-code:amber-falcon-4f`.

- The `nickname` is an HMAC of the caller's IP address and a coarse User-Agent signature (platform plus product/version). The HMAC input is used in memory and discarded.
- The default salt is derived from the server ingest key. Set `nicknameSecret` to rotate nicknames independently of the key.
- The id rotates at UTC midnight, so the same agent is a new daily identity tomorrow. This is deliberate: long-lived tracking of an IP address is exactly what the design avoids.
- The country and `cf_ray` are stored as separate columns. The query string is stripped from the stored path.
- Inbound `X-No-Telemetry: true|1|yes` skips telemetry with zero network I/O. Pass `respectNoTelemetry: false` to ignore the header.

Agent telemetry requires a server ingest key (`vis_srv_...`). Browser public keys are not accepted for the `agent` event type, so a visitor cannot forge agent analytics.

## Add the middleware

Install the SDK and add a server ingest key to the host's secret store:

```sh
npm install @visibling/sdk
```

All three adapters deliver off the response path and never throw into the host app. A Visibling outage cannot fail or delay a customer request.

### Cloudflare Workers

Wrap the `ExportedHandler` or a bare `fetch(request, env, ctx)` handler with `withVisiblingAgent`:

```ts
import { env } from "cloudflare:workers";
import { withVisiblingAgent } from "@visibling/sdk/agent";

interface Env {
  VISIBLING_SERVER_KEY: string;
}

const app = {
  async fetch(request: Request): Promise<Response> {
    return new Response("ok");
  },
};

export default withVisiblingAgent(app, {
  ingestKey: env.VISIBLING_SERVER_KEY, // vis_srv_...
});
```

The wrapper clones a potential MCP request body before the host consumes it, then schedules delivery in `ctx.waitUntil` after the upstream response is ready. The caller gets the response immediately.

### Next.js middleware

`createNextAgentMiddleware` returns a standalone middleware, or wraps an inner middleware when you pass one as the second argument:

```ts
// middleware.ts
import { createNextAgentMiddleware } from "@visibling/sdk/agent";

export const middleware = createNextAgentMiddleware({
  ingestKey: process.env.VISIBLING_SERVER_KEY!,
});

export const config = { matcher: "/:path*" };
```

It uses `event.waitUntil` when Next supplies it; otherwise the fire-and-forget delivery promise floats without extending the request.

### Express

Mount the middleware after `express.json()` so MCP JSON-RPC metadata can be read from the already-parsed `req.body`:

```ts
import express from "express";
import { createExpressAgentMiddleware } from "@visibling/sdk/agent";

const app = express();
app.use(express.json());
app.use(
  createExpressAgentMiddleware({
    ingestKey: process.env.VISIBLING_SERVER_KEY!,
  }),
);
```

The host continues through `next()` immediately. Delivery happens when the response emits `finish`, or `close` for a client disconnect.

### Service Binding mode

When the app and Visibling run in the same Cloudflare account, skip the public network hop and bind Visibling's ingest entrypoint. `app` is the `ExportedHandler` from the Workers example above:

```ts
import { env } from "cloudflare:workers";
import {
  withVisiblingAgent,
  type VisiblingAgentServiceBinding,
} from "@visibling/sdk/agent";

interface Env {
  VISIBLING_SERVER_KEY: string;
  VISIBLING: VisiblingAgentServiceBinding;
}

export default withVisiblingAgent(app, {
  ingestKey: env.VISIBLING_SERVER_KEY,
  serviceBinding: env.VISIBLING,
});
```

The binding must expose `ingestBatch(projectKey, batch, meta?)`. See [the first-party proxy guide](/docs/proxy) for the same-account pattern.

### Configuration

| Option | Default | Purpose |
| --- | --- | --- |
| `ingestKey` | required | Server ingest key (`vis_srv_...`). |
| `endpoint` | `https://visibling.com/api/v1/ingest` | Ingest URL used without a Service Binding. |
| `serviceBinding` | none | Same-account transport (see above). |
| `nicknameSecret` | derived from the key | Salt for daily nicknames. |
| `mcpPaths` | `["/mcp"]` | Path prefixes inspected for JSON-RPC; `[]` disables MCP path detection, though MCP session headers or an MCP User-Agent still classify a request as MCP. |
| `resolveClient` | none | Resolve an OAuth `azp` or custom client name for stateless MCP endpoints. A thrown resolver is treated as unknown. |
| `clientHeader` | none | Parse a `kind/version` header when `resolveClient` is not set. |
| `respectNoTelemetry` | `true` | Honour `X-No-Telemetry: true\|1\|yes`. |
| `maxBodyInspectBytes` | `16384` | Largest cloned body inspected for JSON-RPC metadata. |
| `ignorePaths` | built-ins | Extra path prefixes to skip; `/_v`, `/_next`, `/favicon.ico` and static assets are always ignored. |
| `environment`, `release` | none | Attached to every agent event when set. |

Client names are allowlist-normalised (`claude`, `claude-code`, `chatgpt`, `cursor`, `vscode`, `zed`, `cline`, `windsurf`, `continue`, `roo`, `gemini`, `antigravity`, `codex`, `perplexity`); anything else becomes `mcp-other`, so an arbitrary caller string is never stored.

## What is captured

Each observed agent or MCP request becomes one `$agent_request` or `$mcp_call` event. Request bodies are not stored; for MCP endpoints the SDK inspects a bounded JSON-RPC envelope and keeps only:

- `mcp_method` — the JSON-RPC method, normalised to a fixed list (`initialize`, `tools/list`, `tools/call`, `resources/read`, and so on; anything unknown becomes `other`).
- `mcp_tool` — `params.name` on `tools/call` only. `params.arguments` (tool inputs) is never read, copied, or returned.
- The client name — `params.clientInfo.name` on `initialize`, or the value returned by `resolveClient` / parsed from `clientHeader`. It is normalised against the allowlist and only the resulting family is stored.
- `content_type` — the request media type.

HTTP fields include the method, path, status, `duration_ms`, `outcome`, country, and `cf_ray`. The SDK never stores the Authorization header, cookies, query strings, or raw request bodies.

## The Agents dashboard

Open `/app/<org-slug>/<project-slug>/agents`:

- The KPI strip shows daily agents, agent requests, MCP calls, and the rate of agents whose terminal request failed with a 4xx/5xx status or a JSON-RPC error.
- **Where agents stopped** ranks terminal routes and MCP calls by the number of daily agents that ended there, with each stop's share of agents.
- **Recent daily agents** lists the nickname, family, UTC date, request count, MCP call count, and the request where that agent stopped.

Select a daily agent to open its trail at `/app/<org-slug>/<project-slug>/agents/<distinctId>`. The trail is chronological and highlights the terminal request with a **Stopped here** marker; a 401, 403, 404, 405, 429, or 500 on that request is the usual answer to "why did the agent stop?". A trail that is longer than the page size reports that it was truncated rather than claiming the last shown step is terminal.

Ranges are 24 hours, 7 days, or 30 days, clamped to the plan's retention window, with an optional agent-family filter.

## Query agent analytics over MCP

A connected coding agent can read the same analytics with two read-only tools. Both are listed in the `/mcp` discovery card and require the usual `vis_usr_` token or OAuth access token.

`get_agent_analytics` takes `{ orgSlug, projectSlug, rangeDays?, family?, limit? }` and returns:

- project-wide `requestCount`, `uniqueAgents`, and `mcpCallCount`; `blockedStopCount` and `blockedStopRate` follow the family filter,
- the daily trend and the top stop points (at most 20),
- up to `limit` recent daily agents (default 20, maximum 50), with `total` (the matching count among the most recent 200 agent rows fetched, before the display limit) and `truncated` so a client knows the page was cut. Because the count is bounded to those 200 rows, a family filter can report `total: 0` while matching agents exist earlier in the window.

`get_agent_trail` takes `{ orgSlug, projectSlug, distinctId, rangeDays?, limit? }` and returns the parsed identity plus the chronological request trail (default 50 steps, maximum 100). `total` is every request in the window; the final step carries `isTerminal: true` only when the trail was complete, and `truncated: true` means more requests exist beyond the returned prefix, so the true stop was not fetched. `blocked` is the terminal request's failure state and stays `false` for a truncated trail.

Limits above the tool maximum are rejected rather than silently clamped: pass at most 50 recent agents to `get_agent_analytics` and at most 100 steps to `get_agent_trail`. Each call spends the calling user's Basin query budget.

## Verify the integration

1. Add a server ingest key to the app (see [Getting started](/docs/getting-started) if the project has none yet).
2. Deploy the middleware, then request the site with an agent, a crawler, or an MCP client.
3. Open the Agents dashboard, or call `get_agent_analytics` over `/mcp`, and confirm a daily agent appears within the selected range.
4. If no event arrives, check that the key starts with `vis_srv_`, that the request path is not ignored, and that the deployment has Web Crypto available (Cloudflare Workers, Node 20+, Bun, and Deno all do).

For the MCP server itself, see [MCP and coding agents](/docs/mcp). For server-side product events and daily anonymous ids, see [Server SDK](/docs/server-sdk).
