Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(mcp): record which AI client opens each MCP session and chart it on an admin /mcp-clients board
nirholase8381ce9c723
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex b5e74d7c7..056eb0a12 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -192,6 +192,7 @@ bottom.| Likeness bench (Phase 1 verification metric) | Scoring core [api/_lib/likeness-score.js](api/_lib/likeness-score.js), face-embedding runtime [api/_lib/face-embed.js](api/_lib/face-embed.js), store + distribution queries [api/_lib/likeness-store.js](api/_lib/likeness-store.js) ([schema](api/_lib/migrations/20260814000000_avatar_likeness_scores.sql)), weekly sweep [api/cron/likeness-eval.js](api/cron/likeness-eval.js) (`47 3 * * 1`), by-hand runner [scripts/likeness-eval.mjs](scripts/likeness-eval.mjs), internal board [api/likeness-bench.js](api/likeness-bench.js) + [pages/likeness-bench.html](pages/likeness-bench.html) `→ /likeness-bench` (admin or `x-ops-secret`, not in `data/pages.json`) | Live · applied 2026-08-14 (this file alone, via `apply-migrations.mjs --apply --file`, because `db:migrate` would have applied seven other agents' pending migrations with it). The header comment still reads "Draft, NOT applied" and must stay that way: an applied migration is an immutable record and editing its bytes trips the drift guard | The number the roadmap gates Phase 1 on, measured instead of asserted. The realism bench scores whether a generation looks real and never asks whose face it is; the reconstruction worker's ISE eval scores face *shape* offline against a synthetic set and stores nothing. This closes the gap: it renders a finished reconstruction head-framed at three yaws (head-on 0°, three-quarter 35°, profile 65°) with the platform's own `headshot` preset, embeds every render and every input capture with OSS face recognition (YuNet detection, MIT + SFace 128-d identity, Apache-2.0, both hash-pinned from OpenCV Zoo and run on `onnxruntime-web`'s WASM backend so there is no native install step), and files a 1-5 score against the generation record in `forge_creations`. The 1-5 mapping is anchored on SFace's own published decision boundary (cosine 0.363 = 3.0, so the roadmap's 4/5 gate is cosine 0.68, roughly twice the same-identity threshold) rather than on taste. **Refuses rather than fabricates:** `captures_unusable`, `render_unusable` and a genuinely low score are three separate statuses, and a budget-truncated sweep is withheld from the distribution. Reports `turn_falloff` (identity lost between head-on and the worst view), which is the only place a frontally-flattering texture transfer is visible. **Stores no biometrics:** no capture URLs, no crops, no embeddings, only the measurement. Docs: [docs/likeness-eval.md](docs/likeness-eval.md). Tests: [tests/likeness-score.test.js](tests/likeness-score.test.js) || Payment-outcome board (x402 failure visibility) | Endpoint [api/ops/payment-outcomes.js](api/ops/payment-outcomes.js), page [pages/payment-outcomes.html](pages/payment-outcomes.html) `-> /payment-outcomes` (admin session or `x-ops-secret`, `noindex`, not in `data/pages.json`), sensors [api/_lib/ops/x402-settle-health.js](api/_lib/ops/x402-settle-health.js) + [api/_lib/x402/wallet-balance-monitor.js](api/_lib/x402/wallet-balance-monitor.js) + [api/_lib/x402/sponsor-runway.js](api/_lib/x402/sponsor-runway.js) + [api/_lib/custodial-key-health.js](api/_lib/custodial-key-health.js) | Live | Every way an x402 payment can fail, in one read, before it halts the economy. The 2026-07-11 audit found the griefing classes (verify-reject floods, settle failures, sponsor-fee starvation) were only visible after the economy stopped: `recordPaymentMetric` was already emitting the events and nothing surfaced them. Four panels: inbound rates over 1h/3h/24h from the durable `x402_audit_log` (settle success, verify reject, replay reject with its own `inbound_attempts` denominator, top failure reasons by stage, replay stage split), the outbound ring settle sensor with its triage hint, every configured ring wallet against **its own** floor plus the measured sponsor runway, and stranded custody. The wallet panel is per-wallet on purpose: settle-floor starvation and dry wallets look identical from outside and have opposite fixes, and a board showing only the sponsor renders a starved payer as healthy. Panels are read independently and a failed one names itself in `degraded` (207 Multi-Status) rather than blanking the board; on the page a rate with no attempts renders `n/a` and an unmeasured custody total renders `not measured`, because a green zero on a reading that never happened is worse than no board. Docs: [docs/ops/payment-outcomes.md](docs/ops/payment-outcomes.md). || Forge funnel board (does anyone keep what Forge makes) | Report [api/_lib/forge-funnel.js](api/_lib/forge-funnel.js), endpoint [api/ops/forge-funnel.js](api/ops/forge-funnel.js), page [pages/forge-funnel.html](pages/forge-funnel.html) `-> /forge-funnel` (admin session or `x-ops-secret`, `noindex`, not in `data/pages.json`), CLI [scripts/forge-funnel-report.mjs](scripts/forge-funnel-report.mjs) (`npm run forge:funnel`), destination list [src/shared/forge-destinations.js](src/shared/forge-destinations.js) + composer chips [src/shared/forge-destination-picker.js](src/shared/forge-destination-picker.js), columns from migration `20260921120000_forge_destination.sql` | Built, needs migration applied and a deploy | The generation health sensor says whether a mesh came back. This says whether anyone kept it: useful-output rate (accepted or downloaded over finished), first and second asset rates for new makers, D7/D30 return, acceptance by what the model was for, attempts and generation seconds per kept model by engine, and x402 revenue per kept model. Forge recorded the verdict columns from its first migration and nothing read them until this board. The destination is asked once in a chip row under a finished model on `/forge` and `/forge-studio`, remembered per browser and sent on later requests; API callers send `destination`. Platform-generated rows (seeder, quality benchmark) are flagged `internal` and excluded. Docs: [docs/ops/forge-funnel.md](docs/ops/forge-funnel.md). Tests: [tests/forge-funnel.test.js](tests/forge-funnel.test.js) |+| MCP clients board (which AI clients use the MCP servers) | Recorder [api/_lib/mcp-client-analytics.js](api/_lib/mcp-client-analytics.js) (called from every hosted MCP handler and [api/_mcp-studio/handler.js](api/_mcp-studio/handler.js)), report [api/_lib/mcp-client-report.js](api/_lib/mcp-client-report.js), endpoint [api/ops/mcp-clients.js](api/ops/mcp-clients.js), page [pages/mcp-clients.html](pages/mcp-clients.html) `-> /mcp-clients` (admin session, `noindex`, not in `data/pages.json`), tables from migration `20261008200000_mcp_client_analytics.sql` | Built, needs migration applied and a deploy | Every MCP `initialize` carries `clientInfo`. The servers now issue an `Mcp-Session-Id` on initialize, record the normalized client name, version, surface and auth kind per session, and count each echoed `tools/call` by tool. Daily aggregates are kept; raw session rows expire after 30 days idle (db-retention). Docs: [docs/ops/mcp-clients.md](docs/ops/mcp-clients.md). Tests: [tests/mcp-client-analytics.test.js](tests/mcp-client-analytics.test.js), [tests/api/ops-mcp-clients.test.js](tests/api/ops-mcp-clients.test.js) || Sketchfab showcase (community models → official account) | Cron [api/cron/sketchfab-showcase.js](api/cron/sketchfab-showcase.js), lib [api/_lib/sketchfab.js](api/_lib/sketchfab.js), ledger migration [api/_lib/migrations/20260714130000_sketchfab_uploads.sql](api/_lib/migrations/20260714130000_sketchfab_uploads.sql) | Live · dormant until `SKETCHFAB_API_TOKEN` is set | Publishes the best community forge models to the official three.ws Sketchfab account, prompt and backlink included. Selection order: forge-board winners (now populated by the [Forge-Off](docs/forge-off.md) crown cron), then top-voted (>=1 vote), then creator-accepted (accepted or downloaded, refinement children excluded, title-quality heuristic). Brand safety is two layers: a SQL denylist plus NemoGuard re-moderation; blocked rows park as `blocked` in the `sketchfab_uploads` ledger (states `pending`/`uploaded`/`live`/`failed`/`blocked`). `?dry_run=1` exercises selection before the token is wired; `SKETCHFAB_UPLOADS_PER_RUN` clamps 1-5 (default 2). Docs: [docs/sketchfab.md](docs/sketchfab.md) || Third-party display-name safety | [api/_lib/display-name-safety.js](api/_lib/display-name-safety.js), applied at ERC-8004 metadata hydration in [api/cron/[name].js](api/cron/%5Bname%5D.js) | Live | The ERC-8004 crawler indexes 126k+ on-chain agents and renders each one's `name`/`description`/`image` from attacker-controlled metadata. Visibility used to be decided solely by the agent's own `meta.active`, so a Base-registered agent whose name was a racial slur shipped to `/marketplace`. `matchedSlurStem()` now withholds such rows (`active = false`), which removes them from every feed at once since explore/marketplace/agents/search all filter `active = true`. Deliberately narrow — **whole-word** hate slurs only, never general profanity, and hex-address aware: leet folding turns `0xdb6b887289c380…` into letter soup, so long alphanumeric runs are excluded from the spaced-out-evasion pass. A false positive silently delists a legitimate agent, so precision outranks recall. Backfill for already-indexed rows: [scripts/deactivate-slur-agents.mjs](scripts/deactivate-slur-agents.mjs) (`--dry-run`). Tests: [tests/display-name-safety.test.js](tests/display-name-safety.test.js) — pins the real agent names an earlier substring matcher wrongly flagged. || FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |diff --git a/api/_lib/mcp-client-analytics.js b/api/_lib/mcp-client-analytics.jsnew file mode 100644index 000000000..6151c277d--- /dev/null+++ b/api/_lib/mcp-client-analytics.js@@ -0,0 +1,305 @@+// Which AI clients use the hosted MCP servers, and for what.+//+// Every MCP `initialize` carries clientInfo { name, version }. On initialize a+// server issues an Mcp-Session-Id and records one session row (who, which+// surface, how it authenticated); a conforming client echoes the id on every+// later request, so each tools/call is counted against the client that opened+// the session. Only names, versions, counts and tool names are kept, never a+// request body or a tool argument. Schema: migration+// 20261008200000_mcp_client_analytics.sql. Read by GET /api/ops/mcp-clients.+//+// Writes never touch the request path: events queue in memory and flush in one+// batch shortly after the response is sent, and a failed flush is logged and+// dropped at that boundary. Telemetry that cannot be written is not worth a+// slower or failed tool call.++import { randomUUID } from 'node:crypto';+import { sql } from './db.js';++export const SESSION_HEADER = 'mcp-session-id';++// The ids this platform issues: `mcs_` on every server, `grk_` on the Grok+// surface, whose per-caller rate caps also key on it (api/_mcp-studio/handler.js).+const SESSION_RE = /^(mcs|grk)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+const TOOL_RE = /^[A-Za-z0-9_.:/-]{1,64}$/;+const NAME_MAX = 64;+const VERSION_MAX = 32;+const FLUSH_DELAY_MS = 250;+const QUEUE_MAX = 5000;++export const AUTH_KINDS = ['anonymous', 'install', 'key', 'oauth', 'x402'];++// Known clients by the clientInfo.name they send, first match wins. A name that+// matches none is its own family, so a new client shows up under the name it+// chose rather than disappearing into a bucket.+const FAMILIES = [+ [/probe/, 'probe'],+ [/claude[-_ ]?code/, 'claude-code'],+ [/claude|anthropic/, 'claude'],+ [/openai|chatgpt/, 'chatgpt'],+ [/grok|xai/, 'grok'],+ [/cursor/, 'cursor'],+ [/visual studio code|vs ?code|copilot/, 'vscode'],+ [/windsurf|codeium/, 'windsurf'],+ [/gemini/, 'gemini'],+ [/inspector/, 'mcp-inspector'],+ [/cline/, 'cline'],+ [/zed/, 'zed'],+ [/goose/, 'goose'],+];++/** clientInfo.name as stored: control characters stripped, trimmed, lowercased, capped. */+export function normalizeClientName(raw) {+ if (typeof raw !== 'string') return 'unknown';+ // eslint-disable-next-line no-control-regex+ const s = raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().toLowerCase().slice(0, NAME_MAX).trim();+ return s || 'unknown';+}++export function normalizeClientVersion(raw) {+ if (typeof raw !== 'string') return '';+ // eslint-disable-next-line no-control-regex+ return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, VERSION_MAX).trim();+}++/** The client family a normalized name belongs to (claude, chatgpt, grok, probe, ...). */+export function clientFamily(name) {+ for (const [re, family] of FAMILIES) if (re.test(name)) return family;+ return name;+}++/** How a caller authenticated, from the principal the MCP auth layer resolved. */+export function authKindOf(auth) {+ switch (auth?.source) {+ case 'oauth':+ return 'oauth';+ case 'apikey':+ return 'key';+ case 'x402':+ return 'x402';+ default:+ return 'anonymous';+ }+}++/**+ * The credential a request presents, for servers that resolve auth per tool+ * rather than per request. Labels what was presented, not whether it verified.+ */+export function authKindFromHeaders(req) {+ const h = req?.headers || {};+ const authz = typeof h.authorization === 'string' ? h.authorization : '';+ if (/^bearer\s+sk_(live|test)_/i.test(authz)) return 'key';+ if (/^bearer\s+\S/i.test(authz)) return 'oauth';+ if (h['x-payment'] || h['payment-signature']) return 'x402';+ return 'anonymous';+}++/** True for a session id this platform issued. */+export function isIssuedSessionId(id) {+ return typeof id === 'string' && SESSION_RE.test(id);+}++function messagesOf(body) {+ return (Array.isArray(body) ? body : [body]).filter((m) => m && typeof m === 'object');+}++function surfaceFrom(req) {+ try {+ const path = new URL(req?.url || '/', 'http://localhost').pathname;+ const m = path.match(/^\/api\/([a-z0-9-]+)/);+ return m ? m[1] : 'unknown';+ } catch {+ return 'unknown';+ }+}++function exposeSessionHeader(res) {+ const exposed = res.getHeader?.('access-control-expose-headers');+ if (typeof exposed === 'string' && exposed.toLowerCase().includes(SESSION_HEADER)) return;+ // A browser MCP client cannot echo a header it is not allowed to read.+ res.setHeader('access-control-expose-headers', exposed ? `${exposed}, ${SESSION_HEADER}` : SESSION_HEADER);+}++const queue = { inits: [], calls: [] };+let timer = null;+let flushing = null;++function scheduleFlush() {+ // Tests drive flushMcpClientEvents() themselves, so a stray timer never+ // writes into a neighbouring test's mocked database.+ if (timer || process.env.VITEST) return;+ timer = setTimeout(() => {+ timer = null;+ flushMcpClientEvents().catch(() => {});+ }, FLUSH_DELAY_MS);+ timer.unref?.();+}++function enqueue(list, event) {+ if (queue.inits.length + queue.calls.length >= QUEUE_MAX) return;+ list.push(event);+ scheduleFlush();+}++/**+ * Record one MCP POST. Call it once the request is authorized and before the+ * response headers are written: an `initialize` gets a fresh Mcp-Session-Id+ * header and a session event, and every tools/call is counted against the+ * session id the client echoed (or against "unknown" when it sent none).+ *+ * @param {object} o+ * @param {unknown} o.body the parsed JSON-RPC body (single or batch)+ * @param {object} o.req+ * @param {object} o.res+ * @param {string} [o.surface] defaults to the /api/<surface> path segment+ * @param {string} [o.authKind] one of AUTH_KINDS; defaults to authKindOf(o.auth)+ * @param {object} [o.auth] the resolved MCP principal+ * @param {string} [o.sessionPrefix] 'mcs' (default) or 'grk'+ * @returns {string|null} the session id issued on this response, if any+ */+export function trackMcpRequest({ body, req, res, surface, authKind, auth, sessionPrefix = 'mcs' }) {+ try {+ const msgs = messagesOf(body);+ const kind = AUTH_KINDS.includes(authKind) ? authKind : authKindOf(auth);+ const where = surface || surfaceFrom(req);+ let issued = null;+ for (const m of msgs) {+ if (m.method === 'initialize') {+ if (!issued) {+ issued = `${sessionPrefix === 'grk' ? 'grk' : 'mcs'}_${randomUUID()}`;+ res.setHeader(SESSION_HEADER, issued);+ exposeSessionHeader(res);+ }+ const info = m.params?.clientInfo || {};+ const name = normalizeClientName(info.name);+ enqueue(queue.inits, {+ sessionId: issued,+ surface: where,+ client: clientFamily(name),+ name,+ version: normalizeClientVersion(info.version),+ authKind: kind,+ });+ } else if (m.method === 'tools/call') {+ const tool = m.params?.name;+ // A batch may open a session and call a tool in the same request.+ const sent = req?.headers?.[SESSION_HEADER];+ enqueue(queue.calls, {+ sessionId: issued || (isIssuedSessionId(sent) ? sent : null),+ surface: where,+ tool: typeof tool === 'string' && TOOL_RE.test(tool) ? tool : '(invalid)',+ authKind: kind,+ });+ }+ }+ return issued;+ } catch (err) {+ console.warn('[mcp-clients] track failed', err?.message);+ return null;+ }+}++async function writeInits(inits) {+ if (!inits.length) return;+ await sql`+ with s as (+ insert into mcp_client_sessions (session_id, surface, client, client_name, client_version, auth_kind)+ select * from unnest(+ ${inits.map((e) => e.sessionId)}::text[],+ ${inits.map((e) => e.surface)}::text[],+ ${inits.map((e) => e.client)}::text[],+ ${inits.map((e) => e.name)}::text[],+ ${inits.map((e) => e.version)}::text[],+ ${inits.map((e) => e.authKind)}::text[]+ )+ on conflict (session_id) do nothing+ returning surface, client, client_name, client_version, auth_kind+ )+ insert into mcp_client_daily (day, surface, client, client_name, client_version, auth_kind, sessions)+ select current_date, surface, client, client_name, client_version, auth_kind, count(*)::int+ from s+ group by surface, client, client_name, client_version, auth_kind+ on conflict (day, surface, client_name, client_version, auth_kind)+ do update set sessions = mcp_client_daily.sessions + excluded.sessions, updated_at = now()+ `;+}++// One statement per (session, tool) group: bump the session's own counters and+// fold the calls into that client's daily row. A call with no known session+// (the client never initialized here, or did not echo the id) lands on the+// "unknown" client for its surface and auth kind, so totals stay complete.+async function writeCallGroup({ sessionId, surface, tool, authKind, n }) {+ await sql`+ with sess as (+ update mcp_client_sessions+ set calls = calls + ${n}::int,+ tool_calls = mcp_tool_count_add(tool_calls, ${tool}::text, ${n}::int),+ last_seen_at = now()+ where session_id = ${sessionId}::text+ returning surface, client, client_name, client_version, auth_kind+ ), who as (+ select surface, client, client_name, client_version, auth_kind from sess+ union all+ select ${surface}::text, 'unknown', 'unknown', '', ${authKind}::text+ where not exists (select 1 from sess)+ )+ insert into mcp_client_daily (day, surface, client, client_name, client_version, auth_kind, calls, tools)+ select current_date, surface, client, client_name, client_version, auth_kind, ${n}::int,+ mcp_tool_count_add('{}'::jsonb, ${tool}::text, ${n}::int)+ from who+ on conflict (day, surface, client_name, client_version, auth_kind)+ do update set calls = mcp_client_daily.calls + excluded.calls,+ tools = mcp_tool_count_add(mcp_client_daily.tools, ${tool}::text, ${n}::int),+ updated_at = now()+ `;+}++function groupCalls(calls) {+ const groups = new Map();+ for (const c of calls) {+ const key = `${c.sessionId}|${c.surface}|${c.tool}|${c.authKind}`;+ const g = groups.get(key);+ if (g) g.n += 1;+ else groups.set(key, { ...c, n: 1 });+ }+ return [...groups.values()];+}++/**+ * Write every queued event. Sessions go first so calls in the same batch find+ * the session they belong to. Errors are logged and swallowed: this is the+ * boundary where telemetry gives up rather than hurting a request.+ * @returns {Promise<{ sessions: number, callGroups: number, failed: number }>}+ */+export async function flushMcpClientEvents() {+ if (flushing) {+ await flushing;+ return flushMcpClientEvents();+ }+ const inits = queue.inits.splice(0);+ const calls = queue.calls.splice(0);+ if (!inits.length && !calls.length) return { sessions: 0, callGroups: 0, failed: 0 };+ flushing = (async () => {+ let failed = 0;+ try {+ await writeInits(inits);+ } catch (err) {+ failed += 1;+ console.warn('[mcp-clients] session write failed', err?.message);+ }+ const groups = groupCalls(calls);+ const results = await Promise.allSettled(groups.map(writeCallGroup));+ const rejected = results.filter((r) => r.status === 'rejected');+ if (rejected.length) {+ failed += rejected.length;+ console.warn(`[mcp-clients] ${rejected.length}/${groups.length} call writes failed`, rejected[0].reason?.message);+ }+ return { sessions: inits.length, callGroups: groups.length, failed };+ })();+ try {+ return await flushing;+ } finally {+ flushing = null;+ }+}diff --git a/api/_lib/mcp-client-report.js b/api/_lib/mcp-client-report.jsnew file mode 100644index 000000000..e7b978854--- /dev/null+++ b/api/_lib/mcp-client-report.js@@ -0,0 +1,149 @@+// The MCP clients report: which AI clients open sessions on the hosted MCP+// servers, how many tools they call, and which tools. Reads the daily aggregate+// that api/_lib/mcp-client-analytics.js writes. Served by GET+// /api/ops/mcp-clients and drawn by the /mcp-clients board.++import { sql } from './db.js';++export const REPORT_DEFAULT_DAYS = 30;+const REPORT_MIN_DAYS = 1;+const REPORT_MAX_DAYS = 365;+const TOP_TOOLS = 5;+const TOP_NAMES = 5;+const ROW_CAP = 50_000;++export function clampReportDays(value) {+ // Number(null) and Number('') are both 0, which would clamp an absent+ // parameter to a one-day window instead of the default.+ if (value == null || value === '') return REPORT_DEFAULT_DAYS;+ const n = Math.floor(Number(value));+ if (!Number.isFinite(n)) return REPORT_DEFAULT_DAYS;+ return Math.min(REPORT_MAX_DAYS, Math.max(REPORT_MIN_DAYS, n));+}++function bump(map, key, by) {+ map.set(key, (map.get(key) || 0) + by);+}++function topOf(map, n, keyName, valueName) {+ return [...map.entries()]+ .sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])))+ .slice(0, n)+ .map(([k, v]) => ({ [keyName]: k, [valueName]: v }));+}++function isoDay(d) {+ return d.toISOString().slice(0, 10);+}++/** Every calendar day of the window, oldest first, ending at `today` (UTC). */+export function windowDays(days, today = new Date()) {+ const end = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());+ return Array.from({ length: days }, (_, i) => isoDay(new Date(end - (days - 1 - i) * 86_400_000)));+}++/**+ * Fold daily aggregate rows into the report. Pure, so the board's numbers are+ * testable without a database.+ * @param {Array<{day: string, surface: string, client: string, client_name: string, client_version: string, auth_kind: string, sessions: number, calls: number, tools: Record<string, number>}>} rows+ */+export function summarizeMcpClients(rows, { days = REPORT_DEFAULT_DAYS, today = new Date() } = {}) {+ const byClient = new Map();+ const surfaces = new Map();+ const allTools = new Map();+ const dayList = windowDays(days, today);+ const daily = new Map(dayList.map((d) => [d, new Map()]));+ let sessions = 0;+ let calls = 0;++ for (const r of rows) {+ const s = Number(r.sessions) || 0;+ const c = Number(r.calls) || 0;+ sessions += s;+ calls += c;+ let entry = byClient.get(r.client);+ if (!entry) {+ entry = { sessions: 0, calls: 0, names: new Map(), versions: new Map(), auth: new Map(), surfaces: new Map(), tools: new Map() };+ byClient.set(r.client, entry);+ }+ entry.sessions += s;+ entry.calls += c;+ bump(entry.names, r.client_name, s + c);+ if (r.client_version) bump(entry.versions, r.client_version, s);+ bump(entry.auth, r.auth_kind, s + c);+ bump(entry.surfaces, r.surface, s + c);++ const sf = surfaces.get(r.surface) || { sessions: 0, calls: 0 };+ sf.sessions += s;+ sf.calls += c;+ surfaces.set(r.surface, sf);++ for (const [tool, n] of Object.entries(r.tools || {})) {+ const v = Number(n) || 0;+ bump(entry.tools, tool, v);+ bump(allTools, tool, v);+ }++ const day = daily.get(String(r.day).slice(0, 10));+ if (day) {+ const d = day.get(r.client) || { sessions: 0, calls: 0 };+ d.sessions += s;+ d.calls += c;+ day.set(r.client, d);+ }+ }++ const clients = [...byClient.entries()]+ .map(([client, e]) => ({+ client,+ sessions: e.sessions,+ calls: e.calls,+ calls_per_session: e.sessions > 0 ? Math.round((e.calls / e.sessions) * 10) / 10 : null,+ names: topOf(e.names, TOP_NAMES, 'name', 'events'),+ versions: topOf(e.versions, TOP_NAMES, 'version', 'sessions'),+ auth: Object.fromEntries(e.auth),+ surfaces: Object.fromEntries(e.surfaces),+ top_tools: topOf(e.tools, TOP_TOOLS, 'tool', 'calls'),+ }))+ .sort((a, b) => b.sessions - a.sessions || b.calls - a.calls || a.client.localeCompare(b.client));++ return {+ window_days: days,+ since: dayList[0],+ totals: {+ sessions,+ calls,+ clients: clients.filter((c) => c.client !== 'unknown').length,+ unattributed_calls: byClient.get('unknown')?.calls || 0,+ },+ clients,+ surfaces: [...surfaces.entries()]+ .map(([surface, v]) => ({ surface, ...v }))+ .sort((a, b) => b.sessions + b.calls - (a.sessions + a.calls)),+ tools: topOf(allTools, 10, 'tool', 'calls'),+ daily: dayList.map((day) => ({ day, clients: Object.fromEntries(daily.get(day)) })),+ };+}++/** Read the window and build the report. A failed read names itself in `degraded`. */+export async function gatherMcpClients({ days = REPORT_DEFAULT_DAYS } = {}) {+ const windowLen = clampReportDays(days);+ const generated_at = new Date().toISOString();+ try {+ const rows = await sql`+ select day::text as day, surface, client, client_name, client_version, auth_kind, sessions, calls, tools+ from mcp_client_daily+ where day >= current_date - ${windowLen - 1}::int+ order by day+ limit ${ROW_CAP}+ `;+ return { ok: true, generated_at, degraded: [], ...summarizeMcpClients(rows, { days: windowLen }) };+ } catch (err) {+ return {+ ok: false,+ generated_at,+ degraded: [{ panel: 'mcp_client_daily', error: String(err?.message || err).slice(0, 200) }],+ ...summarizeMcpClients([], { days: windowLen }),+ };+ }+}diff --git a/api/_lib/migrations/20261008200000_mcp_client_analytics.sql b/api/_lib/migrations/20261008200000_mcp_client_analytics.sqlnew file mode 100644index 000000000..162975471--- /dev/null+++ b/api/_lib/migrations/20261008200000_mcp_client_analytics.sql@@ -0,0 +1,67 @@+-- Migration: know which AI clients use the hosted MCP servers.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261008200000_mcp_client_analytics.sql+-- Idempotent.+--+-- Every MCP `initialize` carries clientInfo { name, version }. The servers issue+-- an Mcp-Session-Id on initialize and record one row per session here, so a+-- later tools/call that echoes the id can be attributed to the client that+-- opened it. Nothing here stores a request body or a tool argument: only the+-- normalized client name and version, the surface, how the caller+-- authenticated, and per-tool call counts.+--+-- mcp_client_sessions is the raw, short-lived join table. db-retention deletes+-- rows idle for 30 days (api/cron/db-retention.js, windowKind `mcpSessions`).+-- mcp_client_daily is the aggregate the ops board reads, kept indefinitely: one+-- row per day, surface, client name, version and auth kind.+--+-- client is the family a name belongs to (claude, chatgpt, cursor, grok,+-- probe, ...), derived in api/_lib/mcp-client-analytics.js; client_name is the+-- name the client actually sent, trimmed, lowercased and capped at 64 chars.++create table if not exists mcp_client_sessions (+ session_id text primary key,+ surface text not null,+ client text not null,+ client_name text not null,+ client_version text not null default '',+ auth_kind text not null check (auth_kind in ('anonymous', 'install', 'key', 'oauth', 'x402')),+ calls integer not null default 0,+ tool_calls jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ last_seen_at timestamptz not null default now()+);++create index if not exists mcp_client_sessions_last_seen_idx on mcp_client_sessions (last_seen_at);++create table if not exists mcp_client_daily (+ day date not null,+ surface text not null,+ client text not null,+ client_name text not null,+ client_version text not null default '',+ auth_kind text not null check (auth_kind in ('anonymous', 'install', 'key', 'oauth', 'x402')),+ sessions integer not null default 0,+ calls integer not null default 0,+ tools jsonb not null default '{}'::jsonb,+ updated_at timestamptz not null default now(),+ primary key (day, surface, client_name, client_version, auth_kind)+);++create index if not exists mcp_client_daily_day_idx on mcp_client_daily (day);++-- Add n to one tool's count in a { tool: count } object. A tool name comes from+-- the caller, so a client inventing names cannot grow the object without bound:+-- past 200 distinct keys every new name folds into "(other)".+create or replace function mcp_tool_count_add(counts jsonb, tool text, n integer)+returns jsonb+language sql+immutable+as $$+ select counts || jsonb_build_object(k, coalesce((counts ->> k)::integer, 0) + n)+ from (+ select case+ when counts ? tool or (select count(*) from jsonb_object_keys(counts)) < 200 then tool+ else '(other)'+ end as k+ ) pick+$$;diff --git a/api/_mcp-studio/dispatch.js b/api/_mcp-studio/dispatch.jsindex 29fa8d069..6a9487000 100644--- a/api/_mcp-studio/dispatch.js+++ b/api/_mcp-studio/dispatch.js@@ -201,6 +201,11 @@ function surfaceOf(name) {return Object.hasOwn(SURFACES, name) ? SURFACES[name] : SURFACES.full;}+/** The endpoint name a surface is served at (mcp-studio, mcp-chatgpt, mcp-grok). */+export function surfaceServer(name) {+ return surfaceOf(name).server;+}+/** The tool descriptors a surface advertises on tools/list. */export function toolCatalogFor(name = 'full') {return surfaceOf(name).catalog;diff --git a/api/_mcp-studio/handler.js b/api/_mcp-studio/handler.jsindex a750f2589..8cb59b040 100644--- a/api/_mcp-studio/handler.js+++ b/api/_mcp-studio/handler.js@@ -31,16 +31,16 @@// generation caps fail OPEN on a Redis outage, so a Redis blip never dead-ends a// free feature; real paid spend stays fail-closed one layer down in /api/forge.-import { randomUUID } from 'node:crypto';import { cors, wrap, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';import { limits, clientIp, STUDIO_LIMITS } from '../_lib/rate-limit.js';-import { dispatch, PROTOCOL_VERSION, surfaceServesAccounts } from './dispatch.js';+import { dispatch, PROTOCOL_VERSION, surfaceServer, surfaceServesAccounts } from './dispatch.js';import { authenticateBearer, extractBearer } from '../_lib/auth.js';import { acceptedAudiences, mcpResourceFor } from '../_lib/mcp-resources.js';import { send401 } from '../_mcp/auth.js';import { TOOL_NAMES } from './tools.js';import { isIdempotentRepeat, progressReporter } from './jobs.js';import { installTokenFrom, studioOrigin, INSTALL_PARAM } from './install-token.js';+import { trackMcpRequest, authKindOf } from '../_lib/mcp-client-analytics.js';// check_job collects a job that is already running rather than starting one: it// must never burn the caller's generation quota, or collecting a pending job@@ -146,11 +146,6 @@ export function grokSession(req) {return typeof sid === 'string' && SESSION_RE.test(sid) ? sid : null;}-function initializes(body) {- const batch = Array.isArray(body) ? body : [body];- return batch.some((m) => m && m.method === 'initialize');-}-/** The per-user identity a shared-egress surface carries, or null for per-IP keying. */export function callerSubject(surface, body, req) {if (surface === 'chatgpt') {@@ -415,6 +410,18 @@ export function studioHandler({ surface = 'full' } = {}) {// Anonymous principal, no auth, no scope. rateKey carries the IP for usage logs.const auth = { userId: null, rateKey: ip, scope: '' };+ // Issues the Mcp-Session-Id on initialize (grk_ on the grok surface, where+ // the per-caller caps key on it) and records which client opened the+ // session and what it calls (../_lib/mcp-client-analytics.js).+ trackMcpRequest({+ body,+ req,+ res,+ surface: surfaceServer(surface),+ authKind: install ? 'install' : account ? authKindOf(account) : 'anonymous',+ sessionPrefix: surface === 'grok' ? 'grk' : 'mcs',+ });+const token = progressTokenOf(body);if (token !== null && acceptsEventStream(req)) {return streamToolCall(res, body, auth, req, { surface, caller: caller.key, token, account });@@ -429,12 +436,6 @@ export function studioHandler({ surface = 'full' } = {}) {res.statusCode = 200;res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- if (surface === 'grok' && initializes(body)) {- res.setHeader('mcp-session-id', `grk_${randomUUID()}`);- // A browser MCP client cannot echo a header it is not allowed to read.- const exposed = res.getHeader('access-control-expose-headers');- res.setHeader('access-control-expose-headers', exposed ? `${exposed}, mcp-session-id` : 'mcp-session-id');- }res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));});}diff --git a/api/_mcp/auth.js b/api/_mcp/auth.jsindex 432823f54..368771ebc 100644--- a/api/_mcp/auth.js+++ b/api/_mcp/auth.js@@ -10,6 +10,7 @@ import {import { sendX402Error } from './payments.js';import { streamSubscriptions, dropSubscriptions } from './resources.js';import { acceptedAudiences, mcpResourceFor, protectedResourceMetadataUrl } from '../_lib/mcp-resources.js';+import { isIssuedSessionId } from '../_lib/mcp-client-analytics.js';function quoteString(s) {return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;@@ -287,15 +288,15 @@ export async function handleTerminate(req, res, { resourceServer = null } = {}));}}- // This server is stateless per request and never issues an Mcp-Session-Id, so- // any session id a caller presents names a session that does not exist here.- // The Streamable HTTP transport says a server MUST answer 404 for a session- // id it no longer holds, which is the client's signal to start a fresh- // session; answering 204 would tell the client we tore down a session we- // never had. A DELETE with no session id is the ordinary polite teardown:- // nothing to release, 204.+ // This server serves every request statelessly. The only session ids it+ // issues are the analytics ids handed out on initialize+ // (api/_lib/mcp-client-analytics.js), which hold no server state, so ending+ // one is the ordinary polite teardown: 204. Any other id names a session+ // that does not exist here, and the Streamable HTTP transport says a server+ // MUST answer 404 for a session id it does not hold, which is the client's+ // signal to start a fresh session. A DELETE with no session id: 204.const sessionId = req.headers?.['mcp-session-id'];- if (sessionId) {+ if (sessionId && !isIssuedSessionId(sessionId)) {res.statusCode = 404;res.setHeader('content-type', 'application/json');res.end(JSON.stringify({ error: 'unknown_session', message: 'no such MCP session; start a new one' }));diff --git a/api/cron/db-retention.js b/api/cron/db-retention.jsindex 2490d4754..9d217cd81 100644--- a/api/cron/db-retention.js+++ b/api/cron/db-retention.js@@ -160,6 +160,11 @@ const TIME_SERIES_TABLES = [// One row per coin the Sentiment Scout ever put on its board. Trade receipts// cite the first sighting, so it keeps the audit window, not the firehose one.{ table: 'sentiment_scout_reads', tsColumn: 'first_scouted_at', windowKind: 'audit' },+ // The raw MCP session join table (api/_lib/mcp-client-analytics.js). Only+ // the daily aggregate in mcp_client_daily is kept, so a session idle for+ // 30 days goes. Fixed, like `spent`: the window is a privacy promise in+ // docs/ops/mcp-clients.md, not a storage valve.+ { table: 'mcp_client_sessions', tsColumn: 'last_seen_at', windowKind: 'mcpSessions' },];// ── Autopilot run logs ────────────────────────────────────────────────────────@@ -179,6 +184,9 @@ const RUN_LOG_TABLES = [{ table: 'pump_distribute_runs', tsColumn: 'created_at' },];+// Raw MCP client sessions live 30 days; the daily aggregate stays.+const MCP_SESSION_RETENTION_DAYS = 30;+function clampInt(raw, min, max, dflt) {const n = Number.parseInt(String(raw ?? ''), 10);if (!Number.isFinite(n)) return dflt;@@ -584,6 +592,7 @@ export default wrapCron(async (req, res) => {firehose: cutoffDays,audit: auditCutoffDays,spent: spentDays,+ mcpSessions: MCP_SESSION_RETENTION_DAYS,});const runLogs = await pruneRunLogs(cutoffDays);const audit = await pruneAuditLog(auditCutoffDays);diff --git a/api/ibm-mcp.js b/api/ibm-mcp.jsindex f9bdf2751..8790889e8 100644--- a/api/ibm-mcp.js+++ b/api/ibm-mcp.js@@ -28,6 +28,7 @@ import {isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+import { trackMcpRequest } from './_lib/mcp-client-analytics.js';const RESOURCE_PATH = '/api/ibm-mcp';@@ -103,6 +104,9 @@ export default wrap(async (req, res) => {releaseProof = guard.release;}+ // Which client opened this session and what it calls (api/_lib/mcp-client-analytics.js).+ trackMcpRequest({ body, req, res, surface: 'ibm-mcp', auth });+try {const responses = [];for (const msg of batch) {diff --git a/api/mcp-3d.js b/api/mcp-3d.jsindex cba313aa2..b515345fa 100644--- a/api/mcp-3d.js+++ b/api/mcp-3d.js@@ -21,6 +21,7 @@ import {isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+import { trackMcpRequest } from './_lib/mcp-client-analytics.js';const RESOURCE_PATH = '/api/mcp-3d';@@ -88,6 +89,9 @@ export default wrap(async (req, res) => {releaseProof = guard.release;}+ // Which client opened this session and what it calls (api/_lib/mcp-client-analytics.js).+ trackMcpRequest({ body, req, res, surface: 'mcp-3d', auth });+try {const responses = [];for (const msg of batch) {diff --git a/api/mcp-agent.js b/api/mcp-agent.jsindex 27fbe61cc..7b7946ff9 100644--- a/api/mcp-agent.js+++ b/api/mcp-agent.js@@ -19,6 +19,7 @@ import {isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+import { trackMcpRequest } from './_lib/mcp-client-analytics.js';// Every 402/401 challenge this server issues is scoped to its OWN resource.// Passing neither resourcePath nor challenge left the Agent wallet advertising@@ -87,6 +88,9 @@ export default wrap(async (req, res) => {releaseProof = guard.release;}+ // Which client opened this session and what it calls (api/_lib/mcp-client-analytics.js).+ trackMcpRequest({ body, req, res, surface: 'mcp-agent', auth });+try {const responses = [];for (const msg of batch) {diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.jsindex 5d6a10172..bfabb2264 100644--- a/api/mcp-bazaar.js+++ b/api/mcp-bazaar.js@@ -21,6 +21,7 @@ import {isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+import { trackMcpRequest } from './_lib/mcp-client-analytics.js';// Every 402/401 challenge this server issues is scoped to its OWN resource.// Passing neither resourcePath nor challenge left the Bazaar advertising@@ -88,6 +89,9 @@ export default wrap(async (req, res) => {releaseProof = guard.release;}+ // Which client opened this session and what it calls (api/_lib/mcp-client-analytics.js).+ trackMcpRequest({ body, req, res, surface: 'mcp-bazaar', auth });+try {const responses = [];for (const msg of batch) {diff --git a/api/mcp.js b/api/mcp.jsindex 080fd58bb..a4022526c 100644--- a/api/mcp.js+++ b/api/mcp.js@@ -19,6 +19,7 @@ import {isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+import { trackMcpRequest } from './_lib/mcp-client-analytics.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;@@ -90,6 +91,9 @@ export default wrap(async (req, res) => {releaseProof = guard.release;}+ // Which client opened this session and what it calls (api/_lib/mcp-client-analytics.js).+ trackMcpRequest({ body, req, res, surface: 'mcp', auth });+try {const responses = [];for (const msg of batch) {diff --git a/api/openapi-json.js b/api/openapi-json.jsindex a4d255f1d..469b5d133 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -360,11 +360,10 @@ export default wrap(async (req, res) => {},// Session teardown, part of the MCP Streamable HTTP transport and// advertised in this route's own `allow` header. The server is- // stateless per request, so there is nothing to tear down and the- // call answers 204; a client that ends sessions politely should- // still be able to find it in the spec. A caller that presents an- // Mcp-Session-Id names a session this server never issued, so that- // gets the transport's 404 "start a new session" instead.+ // stateless per request; the Mcp-Session-Id it issues on initialize+ // only attributes calls to a client, so ending one answers 204. Any+ // other id names a session this server never issued and gets the+ // transport's 404 "start a new session" instead.delete: {operationId: 'mcp_terminate_session',security: [],@@ -378,7 +377,7 @@ export default wrap(async (req, res) => {required: false,schema: { type: 'string' },description:- 'Session to end. This server never issues one, so any value names a session it does not hold.',+ 'Session to end: the Mcp-Session-Id this server returned on initialize. Any other value names a session it does not hold.',},],responses: {diff --git a/api/ops/mcp-clients.js b/api/ops/mcp-clients.jsnew file mode 100644index 000000000..0f04fedc3--- /dev/null+++ b/api/ops/mcp-clients.js@@ -0,0 +1,39 @@+// GET /api/ops/mcp-clients?days=30: which AI clients use the hosted MCP servers.+//+// Per client family (claude, chatgpt, cursor, grok, ...): sessions opened,+// tools called, calls per session, the names and versions it sent, how it+// authenticated, which surface it used and its top tools, plus a per-day series+// for the chart. Built from the daily aggregate in mcp_client_daily+// (api/_lib/mcp-client-report.js); no request body is ever stored.+//+// days Rolling window in whole days, 1 to 365. Default 30.+//+// A failed read names itself in `degraded` and the response is 207, matching+// the other ops boards. Auth: requireAdmin (signed-in platform admin): 401+// without a session, 403 for anyone else. Read-only.++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { requireAdmin } from '../_lib/admin.js';+import { gatherMcpClients, clampReportDays } from '../_lib/mcp-client-report.js';++export const maxDuration = 30;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ // Same polled-read bucket as the other ops boards, so watching a board never+ // drains the login budget of the IP that watches it.+ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const admin = await requireAdmin(req, res);+ if (!admin) return;++ const url = new URL(req.url, 'http://localhost');+ const days = clampReportDays(url.searchParams.get('days') ?? undefined);++ const report = await gatherMcpClients({ days });+ return json(res, report.ok ? 200 : 207, report, { 'cache-control': 'private, no-store' });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 92671473f..d180a4a00 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -29217,6 +29217,14 @@"feature"],"link": "/leaderboard"+ },+ {+ "date": "2026-10-08",+ "title": "Every MCP server now knows which AI client is calling",+ "summary": "The three.ws MCP servers now remember which AI app opened each connection, such as Claude, ChatGPT, Cursor or Grok Bot, using the name and version the app announces when it connects, and count which tools each one uses. Only those names and counts are kept, never what anyone asked for. Each connection gets a session id that MCP apps send back automatically, so nothing changes for anyone connecting. It tells us which apps people actually use three.ws from, so we know where to make the experience better next.",+ "tags": [+ "infra"+ ]}]}diff --git a/docs/mcp.md b/docs/mcp.mdindex 903821ea1..b1d46b160 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -297,7 +297,7 @@ This uses the standalone npm package, which handles OAuth locally. The `--url` f### Any MCP-compatible client-Send `POST /api/mcp` with valid JSON-RPC 2.0 messages and a bearer token. The server is stateless — no session setup needed beyond the `initialize` handshake.+Send `POST /api/mcp` with valid JSON-RPC 2.0 messages and a bearer token. The server is stateless, so no session setup is needed beyond the `initialize` handshake. `initialize` returns an `Mcp-Session-Id` header; echo it on later requests, as the MCP SDKs do, so your calls are attributed to your client in the platform's [client analytics](./ops/mcp-clients.md). It holds no state, and a request without it is served the same way.### Client compatibilitydiff --git a/docs/ops/README.md b/docs/ops/README.mdindex 7b5468f0d..69ba64044 100644--- a/docs/ops/README.md+++ b/docs/ops/README.md@@ -16,6 +16,7 @@ Start with [gcp-production.md](gcp-production.md); it is the complete operationa| [production-log-triage.md](production-log-triage.md) | Known error/warning signature map: what each recurring log signature means and the fix. || [forge-error-triage.md](forge-error-triage.md) | `npm run forge:errors`: which 3D generation failures actually recur, ranked by class and lane over a real window. || [forge-funnel.md](forge-funnel.md) | The Forge funnel board (`GET /api/ops/forge-funnel`, `npm run forge:funnel`): useful-output rate, first and second asset rates, retention, what each model was for, attempts per kept model by engine, and x402 revenue per kept model. |+| [mcp-clients.md](mcp-clients.md) | The MCP clients board (`GET /api/ops/mcp-clients`, `/mcp-clients`): sessions, tool calls and top tools per AI client (Claude, ChatGPT, Cursor, Grok Bot, ...), from the `clientInfo` each sends on `initialize`. || [cron-auth.md](cron-auth.md) | The two locks on `/api/cron/*`: the handler gate, the edge gate, and the header trap that makes attaching Cloud Scheduler OIDC take the whole fleet down if done naively. || [materialize-fulfillment.md](materialize-fulfillment.md) | Running physical print fulfillment: the operator console, its authorization doors, the adapter contract for wiring a partner, webhook idempotency, and the stall sweep. || [payment-outcomes.md](payment-outcomes.md) | The payment-outcome board (`GET /api/ops/payment-outcomes`): verify-reject, settle-fail, replay, and sponsor-runway signals and how to read them in an incident. |diff --git a/docs/ops/db-retention.md b/docs/ops/db-retention.mdindex 9b905821b..7ad518d06 100644--- a/docs/ops/db-retention.md+++ b/docs/ops/db-retention.md@@ -66,6 +66,10 @@ Bounded + idempotent. Each tick:`/api/x402-ring` aggregates it with no time filter for its `lifetime` totals;pruning it is a product decision about published revenue figures, not aretention one.+- **MCP client sessions.** `mcp_client_sessions`, the raw join table behind the+ [MCP clients board](mcp-clients.md), loses every session idle for 30 days. The+ window is fixed and the valve never touches it; `mcp_client_daily`, the+ aggregate the board reads, is kept.- **Avatar job hygiene** — deletes terminal jobs past 30 days and strips base64source images from terminal jobs past a day.- **VACUUM** (plain) of the pruned tables so freed pages become reusable bydiff --git a/docs/ops/mcp-clients.md b/docs/ops/mcp-clients.mdnew file mode 100644index 000000000..cf2dd4fc0--- /dev/null+++ b/docs/ops/mcp-clients.md@@ -0,0 +1,100 @@+# MCP clients board++Which AI clients use the hosted MCP servers, and what they do there: how many+sessions Claude, ChatGPT, Cursor, Grok Bot and everyone else open, how many+tools each calls, which tools, and how each one signed in. It answers whether+the Grok Bot work is landing and which client to optimize next.++- **[/mcp-clients](../../pages/mcp-clients.html)**, the internal board.+- `GET /api/ops/mcp-clients?days=30`, the JSON behind it.++Both need a signed-in platform admin (`requireAdmin`): no session answers+`401`, a signed-in account that is not an admin answers `403`. The page is+`noindex` and not in `data/pages.json`.++## How a session is counted++Every MCP client sends `clientInfo: { name, version }` on `initialize`. Each+hosted server (core `/api/mcp`, `/api/mcp-3d`, the free studio+`/api/mcp-studio`, `/api/mcp-chatgpt`, `/api/mcp-grok`, `/api/mcp-agent`,+`/api/mcp-bazaar`, `/api/ibm-mcp`) now answers `initialize` with an+`Mcp-Session-Id` header (`mcs_<uuid>`, or `grk_<uuid>` on the Grok surface,+whose per-caller rate caps key on it) and records one session row. A+conforming client echoes the id on every later request, so each `tools/call`+is counted against the client that opened the session.++The id holds no server state. Requests are still served statelessly, and a+`DELETE` carrying one of these ids answers `204` (any other id still answers+the transport's `404`, "start a new session").++What is stored, and nothing else:++| Field | Value |+|---|---|+| `client_name` | `clientInfo.name`, control characters stripped, trimmed, lowercased, capped at 64 characters |+| `client` | the family that name belongs to: `claude`, `claude-code`, `chatgpt`, `grok`, `cursor`, `vscode`, `windsurf`, `gemini`, `mcp-inspector`, `cline`, `zed`, `goose`, `probe`. A name matching none is its own family. Mapping: `FAMILIES` in [`api/_lib/mcp-client-analytics.js`](../../api/_lib/mcp-client-analytics.js) |+| `client_version` | `clientInfo.version`, capped at 32 characters |+| `surface` | the server it connected to (`mcp`, `mcp-3d`, `mcp-studio`, `mcp-chatgpt`, `mcp-grok`, ...) |+| `auth_kind` | `anonymous`, `install` (free studio install token), `key` (API key), `oauth`, `x402` |+| tool counts | `{ tool_name: calls }`. A caller cannot grow it without bound: past 200 distinct names every new one folds into `(other)` |++No request body, prompt or tool argument is ever stored.++A `tools/call` that carries no id this platform issued (a client that skipped+`initialize`, a plain x402 agent, curl) still counts, under client `unknown`+for its surface and auth kind, and the board shows it as "unattributed".++## Write path++[`trackMcpRequest`](../../api/_lib/mcp-client-analytics.js) runs once per POST,+after auth and rate limits pass and before the response is written. It only+sets the header and queues events in memory. A timer flushes the queue in one+batch about 250 ms later, after the response has gone: sessions first (one+multi-row insert), then one statement per session and tool. A failed flush is+logged as `[mcp-clients]` and dropped; telemetry never slows or fails a tool+call.++## Tables and retention++Migration `api/_lib/migrations/20261008200000_mcp_client_analytics.sql`:++- `mcp_client_sessions`: one row per issued session id, with its call count+ and per-tool counts. Raw join data, deleted by+ [db-retention](db-retention.md) once idle for 30 days.+- `mcp_client_daily`: one row per day, surface, client name, version and auth+ kind, with sessions, calls and per-tool counts. The board reads only this,+ and it is kept.++Days are UTC (`current_date` on the database).++## Reading it++```bash+curl -s -H "Cookie: __Host-sid=<admin session>" "https://three.ws/api/ops/mcp-clients?days=30" \+ | jq '.clients[] | {client, sessions, calls, top_tools}'+```++`days` is 1 to 365, default 30. The response carries `totals`, `clients`+(sessions, calls, calls per session, the raw names and versions sent, auth+mix, surfaces, top 5 tools), `surfaces`, the top 10 `tools`, and a zero-filled+`daily` series per client for the chart. A failed read answers `207` with the+failing table named in `degraded`; before the migration is applied that is+`relation "mcp_client_daily" does not exist`, and the board says so.++## Checking it locally++Run the API from your tree beside the dev server (see+[Client compatibility in docs/mcp.md](../mcp.md#client-compatibility)), point+it at a throwaway database ([`scripts/use-local-neon.mjs`](../../scripts/use-local-neon.mjs)),+then run the connector probe. It identifies itself as+`three-ws-connector-probe`, so every session it opens shows up as client+`probe`:++```bash+npm run probe:mcp-clients -- --base http://localhost:3107+```++Tests: [`tests/mcp-client-analytics.test.js`](../../tests/mcp-client-analytics.test.js)+(the real migration in PGlite) and+[`tests/api/ops-mcp-clients.test.js`](../../tests/api/ops-mcp-clients.test.js)+(the admin gate).diff --git a/pages/mcp-clients.html b/pages/mcp-clients.htmlnew file mode 100644index 000000000..ae9cc0824--- /dev/null+++ b/pages/mcp-clients.html@@ -0,0 +1,460 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>MCP Clients · three.ws</title>+ <meta name="robots" content="noindex, nofollow" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ /* The ops boards render on one dark surface whatever the site theme, so the+ series take the palette's dark steps (validated against a dark surface). */+ .mc-root {+ --series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500;+ --series-5: #d55181; --series-6: #008300; --series-7: #9085e9; --series-8: #e66767;+ --series-other: #5c5c58;+ }+ body { background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }+ /* style.css makes body a flex container: width + min-width:0 pin this wrapper+ to the viewport so a wide table scrolls inside .mc-table-wrap instead. */+ .mc-wrap { width: 100%; min-width: 0; box-sizing: border-box; max-width: 1200px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3rem) 1.25rem 5rem; }+ .mc-title { font-size: clamp(1.4rem, 3vw, 1.85rem); font-weight: 800; letter-spacing: -0.025em; margin: 0 0 0.5rem; }+ .mc-sub { color: rgba(255,255,255,0.45); font-size: 13.5px; margin: 0 0 1.75rem; max-width: 74ch; line-height: 1.65; }++ .mc-controls { display: flex; gap: 0.75rem; margin-bottom: 1.75rem; flex-wrap: wrap; align-items: center; }+ .mc-controls label { font-size: 12px; color: rgba(255,255,255,0.45); }+ .mc-controls select, .mc-controls button, .mc-seg button { font: inherit; font-size: 13px; padding: 8px 12px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #e2e8f0; cursor: pointer; transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard); }+ .mc-controls select:hover, .mc-controls button:hover, .mc-seg button:hover { border-color: rgba(255,255,255,0.24); background: rgba(255,255,255,0.09); }+ .mc-controls button:active, .mc-seg button:active { transform: translateY(1px); }+ .mc-controls select:focus-visible, .mc-controls button:focus-visible, .mc-seg button:focus-visible, .mc-defs summary:focus-visible, .mc-col:focus-visible { outline: 2px solid rgba(124,92,255,0.75); outline-offset: 2px; }+ .mc-controls button[disabled] { opacity: 0.5; cursor: progress; }+ .mc-stamp { font-size: 11.5px; color: rgba(255,255,255,0.3); margin-left: auto; font-variant-numeric: tabular-nums; }++ .mc-note { padding: 2.5rem 1.5rem; text-align: center; border-radius: 14px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); color: rgba(255,255,255,0.55); line-height: 1.75; }+ .mc-note code { background: rgba(255,255,255,0.08); padding: 2px 6px; border-radius: 4px; font-size: 12.5px; }+ .mc-note.bad { background: rgba(248,113,113,0.05); border-color: rgba(248,113,113,0.18); }+ .mc-note h2 { font-size: 15px; margin: 0 0 0.6rem; color: #e2e8f0; font-weight: 700; }+ .mc-note a { color: var(--accent-violet-strong); }+ .mc-banner { padding: 0.85rem 1.1rem; border-radius: 11px; margin-bottom: 1.5rem; font-size: 12.5px; line-height: 1.6; background: rgba(240,169,59,0.07); border: 1px solid rgba(240,169,59,0.24); color: #f0a93b; }+ .mc-banner code { background: rgba(255,255,255,0.08); padding: 1px 5px; border-radius: 4px; }++ .mc-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.35); margin: 0 0 0.85rem; display: flex; gap: 0.6rem; align-items: baseline; flex-wrap: wrap; }+ .mc-section-title span { text-transform: none; letter-spacing: 0; font-weight: 500; color: rgba(255,255,255,0.25); }+ .mc-section { margin-bottom: 2.5rem; }++ .mc-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 0.75rem; }+ .mc-cell { padding: 1rem 1.15rem; border-radius: 12px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard); }+ .mc-cell:hover { border-color: rgba(255,255,255,0.14); background: rgba(255,255,255,0.045); }+ .mc-cell.lead { border-color: rgba(124,92,255,0.35); background: rgba(124,92,255,0.06); }+ .mc-cell-label { font-size: 12px; color: rgba(255,255,255,0.5); margin-bottom: 0.4rem; }+ .mc-cell-value { font-size: 1.55rem; font-weight: 800; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; line-height: 1.15; }+ .mc-cell-note { font-size: 11.5px; color: rgba(255,255,255,0.35); margin-top: 0.4rem; line-height: 1.5; }++ .mc-chart-head { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 0.85rem; }+ .mc-chart-head .mc-section-title { margin: 0; }+ .mc-seg { display: inline-flex; gap: 0; margin-left: auto; }+ .mc-seg button { border-radius: 0; padding: 6px 12px; font-size: 12px; }+ .mc-seg button:first-child { border-radius: 8px 0 0 8px; }+ .mc-seg button:last-child { border-radius: 0 8px 8px 0; border-left: 0; }+ .mc-seg button[aria-pressed="true"] { background: rgba(124,92,255,0.18); border-color: rgba(124,92,255,0.45); }++ .mc-chart { position: relative; border-radius: 12px; border: 1px solid rgba(255,255,255,0.07); background: rgba(255,255,255,0.02); padding: 1rem 1rem 0.75rem; }+ .mc-plot { display: grid; grid-template-columns: auto 1fr; gap: 0.6rem; }+ .mc-yaxis { display: flex; flex-direction: column; justify-content: space-between; height: 180px; font-size: 10.5px; color: rgba(255,255,255,0.35); text-align: right; font-variant-numeric: tabular-nums; }+ .mc-cols { position: relative; display: flex; align-items: flex-end; gap: 2px; height: 180px; border-bottom: 1px solid rgba(255,255,255,0.12); }+ .mc-cols::before { content: ''; position: absolute; inset: 0; background: linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px) 0 0 / 100% 50%; pointer-events: none; }+ .mc-col { position: relative; flex: 1 1 0; min-width: 1px; height: 100%; display: flex; flex-direction: column-reverse; gap: 2px; cursor: default; border-radius: 4px 4px 0 0; }+ .mc-col.dense { gap: 0; }+ .mc-col:hover, .mc-col:focus-visible { background: rgba(255,255,255,0.05); }+ .mc-seg-fill { width: 100%; flex: none; }+ .mc-col .mc-seg-fill:last-child { border-radius: 4px 4px 0 0; }+ .mc-xaxis { display: flex; justify-content: space-between; font-size: 10.5px; color: rgba(255,255,255,0.35); margin: 0.4rem 0 0 calc(var(--mc-yw, 2.2rem) + 0.6rem); font-variant-numeric: tabular-nums; }+ .mc-tip { position: absolute; z-index: 5; pointer-events: none; min-width: 160px; padding: 0.6rem 0.75rem; border-radius: 9px; background: #16161d; border: 1px solid rgba(255,255,255,0.14); box-shadow: 0 8px 24px rgba(0,0,0,0.45); font-size: 12px; line-height: 1.55; opacity: 0; transform: translateY(4px); transition: opacity var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard); }+ .mc-tip.on { opacity: 1; transform: none; }+ .mc-tip b { display: block; margin-bottom: 0.25rem; color: #fff; }+ .mc-tip-row { display: flex; gap: 0.5rem; align-items: center; color: rgba(255,255,255,0.7); }+ .mc-tip-row span:last-child { margin-left: auto; font-variant-numeric: tabular-nums; color: #e2e8f0; }++ .mc-legend { display: flex; gap: 0.5rem 1.1rem; font-size: 11.5px; color: rgba(255,255,255,0.55); margin-top: 0.85rem; flex-wrap: wrap; }+ .mc-sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 0.4rem; vertical-align: -1px; flex: none; }++ .mc-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }+ .mc-table th, .mc-table td { text-align: left; padding: 0.55rem 1rem 0.55rem 0.8rem; border-bottom: 1px solid rgba(255,255,255,0.06); white-space: nowrap; vertical-align: top; }+ .mc-table th { color: rgba(255,255,255,0.4); font-weight: 600; text-transform: uppercase; font-size: 10.5px; letter-spacing: 0.06em; }+ .mc-table tbody tr { transition: background var(--duration-fast) var(--ease-standard); }+ .mc-table tbody tr:hover { background: rgba(255,255,255,0.035); }+ .mc-table td.num, .mc-table th.num { font-variant-numeric: tabular-nums; text-align: right; }+ .mc-table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid rgba(255,255,255,0.07); }+ .mc-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }+ .mc-small { font-size: 11.5px; color: rgba(255,255,255,0.45); white-space: normal; max-width: 34ch; line-height: 1.5; }+ .muted { color: rgba(255,255,255,0.35); }+ .mc-client { display: inline-flex; align-items: center; font-weight: 600; }++ .mc-bars { display: flex; flex-direction: column; gap: 0.5rem; }+ .mc-bar-row { display: grid; grid-template-columns: minmax(110px, 190px) 1fr minmax(64px, 90px); gap: 0.85rem; align-items: center; font-size: 12.5px; }+ .mc-bar-label { color: rgba(255,255,255,0.7); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .mc-bar-track { position: relative; height: 18px; border-radius: 0 4px 4px 0; background: rgba(255,255,255,0.04); overflow: hidden; }+ .mc-bar-fill { position: absolute; inset: 0 auto 0 0; border-radius: 0 4px 4px 0; background: var(--series-1); transition: width var(--duration-slow) cubic-bezier(.4,0,.2,1); }+ .mc-bar-count { text-align: right; font-variant-numeric: tabular-nums; color: rgba(255,255,255,0.7); }+ .mc-two { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 2rem; }++ .mc-defs { border-radius: 12px; border: 1px solid rgba(255,255,255,0.07); background: rgba(255,255,255,0.02); padding: 0.25rem 1.15rem; }+ .mc-defs summary { cursor: pointer; font-size: 13px; color: rgba(255,255,255,0.7); padding: 0.75rem 0; border-radius: 6px; transition: color var(--duration-fast) var(--ease-standard); }+ .mc-defs summary:hover { color: #fff; }+ .mc-defs dl { margin: 0 0 1rem; display: grid; grid-template-columns: minmax(120px, 180px) 1fr; gap: 0.6rem 1.25rem; font-size: 12.5px; line-height: 1.65; }+ .mc-defs dt { color: rgba(255,255,255,0.8); font-weight: 600; }+ .mc-defs dd { margin: 0; color: rgba(255,255,255,0.5); }+ .mc-defs code { background: rgba(255,255,255,0.08); padding: 1px 5px; border-radius: 4px; }++ .mc-skeleton { border-radius: 12px; background: linear-gradient(90deg, rgba(255,255,255,0.035) 25%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.035) 75%); background-size: 200% 100%; animation: mc-shimmer 1.4s ease-in-out infinite; }+ .mc-skeleton.cell { height: 96px; }+ .mc-skeleton.chart { height: 220px; }+ @keyframes mc-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (max-width: 560px) {+ .mc-bar-row { grid-template-columns: 1fr; gap: 0.3rem; }+ .mc-bar-count { text-align: left; }+ .mc-defs dl { grid-template-columns: 1fr; gap: 0.15rem 0; }+ .mc-defs dd { margin-bottom: 0.6rem; }+ .mc-seg { margin-left: 0; }+ }+ @media (prefers-reduced-motion: reduce) {+ .mc-skeleton { animation: none; }+ .mc-bar-fill, .mc-tip { transition: none; }+ }+ </style>+</head>+<body>+ <div class="mc-wrap mc-root">+ <h1 class="mc-title">MCP Clients</h1>+ <p class="mc-sub">+ Which AI clients connect to the hosted MCP servers, and what they do there. Every session+ is counted by the <code>clientInfo</code> name it sent on <code>initialize</code>, and every+ tool call by the session it echoed. Only names, versions and counts are kept, never a+ request body. Internal tooling, not a public surface.+ </p>++ <div class="mc-controls">+ <label for="mc-window">Window</label>+ <select id="mc-window">+ <option value="7">Last 7 days</option>+ <option value="30" selected>Last 30 days</option>+ <option value="90">Last 90 days</option>+ <option value="365">Last 365 days</option>+ </select>+ <button id="mc-refresh" type="button">Refresh</button>+ <span class="mc-stamp" id="mc-stamp"></span>+ </div>++ <div id="mc-content" aria-live="polite" aria-busy="true"></div>+ </div>++ <script src="/nav.js"></script>+ <script type="module">+ const el = document.getElementById('mc-content');+ const windowSelect = document.getElementById('mc-window');+ const refreshBtn = document.getElementById('mc-refresh');+ const stamp = document.getElementById('mc-stamp');++ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+ const num = (n, d = 0) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d }) : 'n/a');++ // Color follows the client, never its rank: each known family owns one+ // palette slot for good, so a window change never repaints a survivor.+ // Every other name folds into Other.+ const FAMILY_SLOT = { claude: 1, chatgpt: 2, grok: 3, cursor: 4, 'claude-code': 5, vscode: 6, probe: 7, windsurf: 8 };+ const colorOf = (client) => (FAMILY_SLOT[client] ? `var(--series-${FAMILY_SLOT[client]})` : 'var(--series-other)');+ const seriesOf = (client) => (FAMILY_SLOT[client] ? client : 'other');+ const AUTH_LABEL = { anonymous: 'anonymous', install: 'install token', key: 'API key', oauth: 'OAuth', x402: 'x402' };++ let metric = 'sessions';+ let lastReport = null;++ function cell(label, value, note, { lead = false } = {}) {+ return `<div class="mc-cell${lead ? ' lead' : ''}">+ <div class="mc-cell-label">${esc(label)}</div>+ <div class="mc-cell-value">${esc(value)}</div>+ <div class="mc-cell-note">${esc(note || '')}</div>+ </div>`;+ }++ function headline(d) {+ const t = d.totals;+ const grok = d.clients.find((c) => c.client === 'grok');+ const share = t.sessions > 0 && grok ? `${((grok.sessions / t.sessions) * 100).toFixed(1)}%` : '0%';+ return `<section class="mc-section">+ <div class="mc-section-title">Last ${num(d.window_days)} days <span>since ${esc(d.since)} (UTC)</span></div>+ <div class="mc-grid">+ ${cell('Sessions', num(t.sessions), 'initialize handshakes that were served', { lead: true })}+ ${cell('Tool calls', num(t.calls), 'tools/call requests, every client')}+ ${cell('Clients', num(t.clients), 'distinct client families that opened a session')}+ ${cell('Calls per session', t.sessions > 0 ? num(t.calls / t.sessions, 1) : 'n/a', 'unattributed calls included')}+ ${cell('Grok share', share, 'of sessions, the client this work exists to grow')}+ ${cell('Unattributed calls', num(t.unattributed_calls), 'a call with no session id this server issued')}+ </div>+ </section>`;+ }++ // The series drawn: the families present in the window in fixed slot order,+ // then Other. A family with nothing in the window takes no legend entry.+ function seriesFor(d) {+ const present = new Set(d.clients.map((c) => seriesOf(c.client)));+ const ordered = Object.keys(FAMILY_SLOT).filter((f) => present.has(f));+ if (present.has('other')) ordered.push('other');+ return ordered;+ }++ function dayTotals(day, series) {+ const out = Object.fromEntries(series.map((s) => [s, 0]));+ for (const [client, v] of Object.entries(day.clients)) out[seriesOf(client)] += v[metric] || 0;+ return out;+ }++ function niceMax(n) {+ if (n <= 4) return 4;+ const p = 10 ** Math.floor(Math.log10(n));+ for (const m of [1, 2, 2.5, 5, 10]) if (m * p >= n) return m * p;+ return 10 * p;+ }++ function chart(d) {+ const series = seriesFor(d);+ const days = d.daily.map((day) => ({ day: day.day, values: dayTotals(day, series) }));+ const peak = Math.max(0, ...days.map((x) => Object.values(x.values).reduce((a, b) => a + b, 0)));+ const top = niceMax(peak);+ const dense = days.length > 60;+ const cols = days.map((x, i) => {+ const total = Object.values(x.values).reduce((a, b) => a + b, 0);+ const segs = series+ .filter((s) => x.values[s] > 0)+ .map((s) => `<div class="mc-seg-fill" style="height:${((x.values[s] / top) * 100).toFixed(2)}%;background:${s === 'other' ? 'var(--series-other)' : colorOf(s)}"></div>`)+ .join('');+ return `<div class="mc-col${dense ? ' dense' : ''}" tabindex="${dense ? -1 : 0}" data-i="${i}" role="img" aria-label="${esc(x.day)}: ${num(total)} ${metric}">${segs}</div>`;+ }).join('');+ const legend = series.map((s) => `<span><i class="mc-sw" style="background:${s === 'other' ? 'var(--series-other)' : colorOf(s)}"></i>${esc(s === 'other' ? 'Other' : s)}</span>`).join('');+ return `<section class="mc-section">+ <div class="mc-chart-head">+ <div class="mc-section-title">${metric === 'sessions' ? 'Sessions' : 'Tool calls'} per day <span>by client, UTC days</span></div>+ <div class="mc-seg" role="group" aria-label="Chart measure">+ <button type="button" data-metric="sessions" aria-pressed="${metric === 'sessions'}">Sessions</button>+ <button type="button" data-metric="calls" aria-pressed="${metric === 'calls'}">Tool calls</button>+ </div>+ </div>+ <div class="mc-chart" id="mc-chart">+ <div class="mc-plot">+ <div class="mc-yaxis" aria-hidden="true"><span>${num(top)}</span><span>${num(top / 2)}</span><span>0</span></div>+ <div class="mc-cols">${cols}</div>+ </div>+ <div class="mc-xaxis" aria-hidden="true"><span>${esc(days[0]?.day)}</span><span>${esc(days[days.length - 1]?.day)}</span></div>+ <div class="mc-tip" id="mc-tip" role="tooltip"></div>+ </div>+ <div class="mc-legend">${legend}</div>+ </section>`;+ }++ function wireChart(d) {+ const box = document.getElementById('mc-chart');+ const tip = document.getElementById('mc-tip');+ if (!box || !tip) return;+ const series = seriesFor(d);+ const show = (col) => {+ const day = d.daily[Number(col.dataset.i)];+ const values = dayTotals(day, series);+ const total = Object.values(values).reduce((a, b) => a + b, 0);+ const rows = series.filter((s) => values[s] > 0).map((s) => `<div class="mc-tip-row"><i class="mc-sw" style="background:${s === 'other' ? 'var(--series-other)' : colorOf(s)}"></i><span>${esc(s === 'other' ? 'Other' : s)}</span><span>${num(values[s])}</span></div>`).join('');+ tip.innerHTML = `<b>${esc(day.day)} · ${num(total)} ${metric === 'sessions' ? 'sessions' : 'calls'}</b>${rows || '<div class="mc-tip-row"><span>nothing this day</span></div>'}`;+ const b = box.getBoundingClientRect();+ const c = col.getBoundingClientRect();+ const w = tip.offsetWidth || 180;+ const left = Math.min(Math.max(c.left - b.left + c.width / 2 - w / 2, 4), b.width - w - 4);+ tip.style.left = `${left}px`;+ tip.style.top = '8px';+ tip.classList.add('on');+ };+ const hide = () => tip.classList.remove('on');+ box.querySelectorAll('.mc-col').forEach((col) => {+ col.addEventListener('mouseenter', () => show(col));+ col.addEventListener('focus', () => show(col));+ col.addEventListener('mouseleave', hide);+ col.addEventListener('blur', hide);+ });+ el.querySelectorAll('.mc-seg button').forEach((btn) => {+ btn.addEventListener('click', () => {+ if (metric === btn.dataset.metric) return;+ metric = btn.dataset.metric;+ render(lastReport);+ });+ });+ }++ function authMix(auth) {+ const total = Object.values(auth).reduce((a, b) => a + b, 0) || 1;+ return Object.entries(auth)+ .sort((a, b) => b[1] - a[1])+ .map(([k, v]) => `${esc(AUTH_LABEL[k] || k)} ${Math.round((v / total) * 100)}%`)+ .join(', ');+ }++ function clientTable(d) {+ const body = d.clients.map((c) => `<tr>+ <td><span class="mc-client"><i class="mc-sw" style="background:${colorOf(c.client)}"></i>${esc(c.client)}</span></td>+ <td class="num">${num(c.sessions)}</td>+ <td class="num">${num(c.calls)}</td>+ <td class="num">${c.calls_per_session == null ? 'n/a' : num(c.calls_per_session, 1)}</td>+ <td class="mc-small">${c.top_tools.length ? c.top_tools.map((t) => `<span class="mc-mono">${esc(t.tool)}</span> ${num(t.calls)}`).join('<br />') : '<span class="muted">no tool calls</span>'}</td>+ <td class="mc-small">${authMix(c.auth)}</td>+ <td class="mc-small">${c.names.map((n) => `<span class="mc-mono">${esc(n.name)}</span>`).join(', ')}${c.versions.length ? `<br />v ${c.versions.map((v) => esc(v.version)).join(', ')}` : ''}</td>+ <td class="mc-small">${Object.keys(c.surfaces).map((s) => `<span class="mc-mono">${esc(s)}</span>`).join(', ')}</td>+ </tr>`).join('');+ return `<section class="mc-section">+ <div class="mc-section-title">Per client <span>the same numbers as the chart, as a table</span></div>+ <div class="mc-table-wrap"><table class="mc-table">+ <thead><tr>+ <th scope="col">Client</th><th scope="col" class="num">Sessions</th><th scope="col" class="num">Calls</th>+ <th scope="col" class="num">Per session</th><th scope="col">Top tools</th><th scope="col">Auth</th>+ <th scope="col">Sent as</th><th scope="col">Surfaces</th>+ </tr></thead>+ <tbody>${body}</tbody>+ </table></div>+ </section>`;+ }++ function bars(rows, label, value) {+ const max = Math.max(1, ...rows.map(value));+ return `<div class="mc-bars">${rows.map((r) => `<div class="mc-bar-row">+ <div class="mc-bar-label mc-mono" title="${esc(label(r))}">${esc(label(r))}</div>+ <div class="mc-bar-track" role="img" aria-label="${esc(label(r))}: ${num(value(r))}"><div class="mc-bar-fill" style="width:${((value(r) / max) * 100).toFixed(1)}%"></div></div>+ <div class="mc-bar-count">${num(value(r))}</div>+ </div>`).join('')}</div>`;+ }++ function toolsAndSurfaces(d) {+ const tools = d.tools.length+ ? bars(d.tools, (t) => t.tool, (t) => t.calls)+ : '<div class="mc-note" style="padding:1.25rem;text-align:left;font-size:13px">No tool calls in this window yet. Sessions opened, but nothing was called.</div>';+ return `<section class="mc-section mc-two">+ <div><div class="mc-section-title">Top tools <span>calls, every client</span></div>${tools}</div>+ <div><div class="mc-section-title">Surfaces <span>sessions plus calls per server</span></div>${bars(d.surfaces, (s) => s.surface, (s) => s.sessions + s.calls)}</div>+ </section>`;+ }++ function definitions(d) {+ return `<details class="mc-defs">+ <summary>How these numbers are defined</summary>+ <dl>+ <dt>Session</dt><dd>One <code>initialize</code> a server answered. It returns an <code>Mcp-Session-Id</code>; the client echoes it on later requests.</dd>+ <dt>Client</dt><dd>The family of the <code>clientInfo.name</code> sent on initialize (claude, chatgpt, grok, cursor, probe, ...). A name that matches no known family is its own client. "Sent as" lists the raw names.</dd>+ <dt>Tool call</dt><dd>One <code>tools/call</code> the server accepted, counted against the session id it carried, on the day it was made.</dd>+ <dt>Unattributed</dt><dd>A call that carried no session id this platform issued: a client that skipped initialize, or did not echo the id. It still counts in totals, under <code>unknown</code>.</dd>+ <dt>Retention</dt><dd>Daily aggregates are kept. The raw session rows behind them expire after 30 days idle.</dd>+ <dt>Same numbers, no browser</dt><dd><code>GET /api/ops/mcp-clients?days=${num(d.window_days)}</code> with an admin session.</dd>+ </dl>+ </details>`;+ }++ function render(d) {+ lastReport = d;+ const missing = d.degraded?.find((g) => /does not exist/i.test(g.error));+ if (d.degraded?.length) {+ el.innerHTML = `<div class="mc-note bad">+ <h2>${missing ? 'The analytics tables are not there yet' : 'Could not read the client aggregates'}</h2>+ <code>${esc(d.degraded[0].error)}</code><br /><br />+ ${missing+ ? 'Migration <code>20261008200000_mcp_client_analytics.sql</code> has not been applied to this database. Preview it with <code>npm run db:status</code>, then apply with <code>npm run db:migrate</code>.'+ : 'The read failed on the database side. Check <code>/api/healthz</code> and press Refresh.'}+ </div>`;+ } else if (d.totals.sessions === 0 && d.totals.calls === 0) {+ el.innerHTML = `<div class="mc-note">+ <h2>No MCP traffic in the last ${num(d.window_days)} days</h2>+ Nothing has opened a session on a hosted MCP server in this window. Connect a client+ (<a href="/connect">/connect</a> has every connector URL), or run+ <code>npm run probe:mcp-clients</code>, which shows up here as client <code>probe</code>.+ Then press Refresh, or pick a longer window above.+ </div>`;+ } else {+ el.innerHTML = headline(d) + chart(d) + clientTable(d) + toolsAndSurfaces(d) + definitions(d);+ wireChart(d);+ }+ stamp.textContent = d.generated_at ? `read ${new Date(d.generated_at).toLocaleTimeString()}` : '';+ }++ function skeleton() {+ const cells = Array.from({ length: 6 }, () => '<div class="mc-skeleton cell"></div>').join('');+ el.innerHTML = `+ <section class="mc-section">+ <div class="mc-section-title">Reading <span>the daily client aggregates</span></div>+ <div class="mc-grid">${cells}</div>+ </section>+ <section class="mc-section">+ <div class="mc-section-title">Per day <span>by client</span></div>+ <div class="mc-skeleton chart"></div>+ </section>`;+ }++ function denied(status) {+ el.innerHTML = status === 401+ ? `<div class="mc-note">+ <h2>Sign in to read this board</h2>+ It names the AI clients that use the platform and how much, so it is admin only.+ <a href="/login?next=/mcp-clients">Sign in</a> as a platform admin and it loads.+ </div>`+ : `<div class="mc-note">+ <h2>This board is for platform admins</h2>+ You are signed in, but this account is not an admin. Switch to an admin account+ (<a href="/login?next=/mcp-clients">sign in again</a>) to read it.+ </div>`;+ stamp.textContent = '';+ }++ function failed(message) {+ el.innerHTML = `<div class="mc-note bad">+ <h2>Could not load the board</h2>+ <code>${esc(message)}</code><br /><br />+ The endpoint answers 207 with whatever it managed to read, so a total failure here is the+ request itself. Check the service is up (<code>/api/healthz</code>) and press Refresh.+ </div>`;+ stamp.textContent = '';+ }++ let inFlight = null;++ async function load() {+ if (inFlight) return;+ refreshBtn.disabled = true;+ refreshBtn.textContent = 'Reading…';+ el.setAttribute('aria-busy', 'true');+ skeleton();+ inFlight = (async () => {+ try {+ const res = await fetch(`/api/ops/mcp-clients?days=${encodeURIComponent(windowSelect.value)}`, {+ credentials: 'include',+ headers: { accept: 'application/json' },+ });+ if (res.status === 401 || res.status === 403) return denied(res.status);+ if (res.status === 429) {+ return failed(`rate limited, retry in ${res.headers.get('retry-after') || 'a moment'}s`);+ }+ // 207 is the designed partial: the body is valid and names what failed.+ if (!res.ok && res.status !== 207) throw new Error(`status ${res.status}`);+ render(await res.json());+ } catch (err) {+ failed(err?.message || String(err));+ } finally {+ refreshBtn.disabled = false;+ refreshBtn.textContent = 'Refresh';+ el.setAttribute('aria-busy', 'false');+ inFlight = null;+ }+ })();+ await inFlight;+ }++ windowSelect.addEventListener('change', load);+ refreshBtn.addEventListener('click', load);+ load();+ </script>+</body>+</html>diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.jsindex 67736d6e9..539ff7d06 100644--- a/tests/api/mcp.test.js+++ b/tests/api/mcp.test.js@@ -360,13 +360,16 @@ describe('Protocol layer', () => {authState.extracted = 'valid-token';authState.bearer = FULL_AUTH;- const { status, body } = await invoke(rpc('initialize', { protocolVersion: '2025-06-18' }));+ const { status, body, res } = await invoke(rpc('initialize', { protocolVersion: '2025-06-18' }));expect(status).toBe(200);expect(body.jsonrpc).toBe('2.0');expect(body.result.protocolVersion).toBe('2025-06-18');expect(body.result.serverInfo.name).toBe('3d-agent-mcp');expect(body.result.capabilities.tools).toBeDefined();+ // The session id later calls echo, so they count against this client.+ expect(res.headers['mcp-session-id']).toMatch(/^mcs_[0-9a-f-]{36}$/);+ expect(res.headers['access-control-expose-headers']).toContain('mcp-session-id');});it('tools/list returns the full tool catalog', async () => {@@ -441,10 +444,22 @@ describe('Protocol layer', () => {expect(status).toBe(204);});- it('DELETE with an Mcp-Session-Id returns 404 (no such session here)', async () => {- // This server never issues a session id, so any id a client presents came- // from somewhere else. The Streamable HTTP transport reads 404 as "start a- // new session"; 204 would claim we tore down a session we never held.+ it('DELETE with the Mcp-Session-Id initialize issued returns 204', async () => {+ // The only ids this server issues attribute calls to a client+ // (api/_lib/mcp-client-analytics.js) and hold no state, so ending one is+ // the polite teardown, not an unknown session.+ const { status } = await invoke({+ method: 'DELETE',+ headers: { 'mcp-session-id': 'mcs_0b9f6a52-4c1e-4e8e-9a39-2f4f1d6c7e10' },+ });++ expect(status).toBe(204);+ });++ it('DELETE with a foreign Mcp-Session-Id returns 404 (no such session here)', async () => {+ // An id this server did not issue came from somewhere else. The Streamable+ // HTTP transport reads 404 as "start a new session"; 204 would claim we+ // tore down a session we never held.const { status, body } = await invoke({method: 'DELETE',headers: { 'mcp-session-id': 'sess-from-another-server' },diff --git a/tests/api/ops-mcp-clients.test.js b/tests/api/ops-mcp-clients.test.jsnew file mode 100644index 000000000..656e46d34--- /dev/null+++ b/tests/api/ops-mcp-clients.test.js@@ -0,0 +1,84 @@+// GET /api/ops/mcp-clients is admin only: 401 with no session, 403 for a+// signed-in user who is not an admin, and the report for an admin. The admin+// decision is the real requireAdmin; only the session lookup and the+// database are stubbed.++import { describe, it, expect, vi, beforeEach } from 'vitest';++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { authedReadIp: vi.fn(async () => ({ success: true, limit: 300, remaining: 299, reset: Date.now() + 1000 })) },+ clientIp: () => '127.0.0.1',+}));++const sqlCalls = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ const text = strings.join('?');+ sqlCalls.push(text);+ if (text.includes('from user_wallets')) return [];+ if (text.includes('from mcp_client_daily')) {+ return [{ day: new Date().toISOString().slice(0, 10), surface: 'mcp-studio', client: 'probe', client_name: 'three-ws-connector-probe', client_version: '1.0.0', auth_kind: 'anonymous', sessions: 2, calls: 4, tools: { search_catalog: 4 } }];+ }+ return [];+ }),+}));++const { default: handler } = await import('../../api/ops/mcp-clients.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this.writableEnded = true; this._body = body; },+ };+}++async function get(url = '/api/ops/mcp-clients?days=30') {+ const res = makeRes();+ await handler({ method: 'GET', url, headers: { host: 'localhost' } }, res);+ return { status: res.statusCode, body: res._body ? JSON.parse(res._body) : null };+}++beforeEach(() => {+ sessionUser = null;+ sqlCalls.length = 0;+});++describe('GET /api/ops/mcp-clients', () => {+ it('answers 401 without a session and reads nothing', async () => {+ const r = await get();+ expect(r.status).toBe(401);+ expect(sqlCalls.some((q) => q.includes('mcp_client_daily'))).toBe(false);+ });++ it('answers 403 to a signed-in user who is not an admin', async () => {+ sessionUser = { id: 'u1', wallet_address: 'NotAnAdminWa11et1111111111111111111111111111', is_admin: false };+ const r = await get();+ expect(r.status).toBe(403);+ expect(r.body.error).toBe('forbidden');+ expect(sqlCalls.some((q) => q.includes('mcp_client_daily'))).toBe(false);+ });++ it('serves the report to an admin', async () => {+ sessionUser = { id: 'u2', wallet_address: null, is_admin: true };+ const r = await get('/api/ops/mcp-clients?days=7');+ expect(r.status).toBe(200);+ expect(r.body.window_days).toBe(7);+ expect(r.body.clients[0]).toMatchObject({ client: 'probe', sessions: 2, calls: 4 });+ });++ it('refuses anything but GET', async () => {+ sessionUser = { id: 'u2', is_admin: true };+ const res = makeRes();+ await handler({ method: 'POST', url: '/api/ops/mcp-clients', headers: {} }, res);+ expect(res.statusCode).toBe(405);+ });+});diff --git a/tests/mcp-client-analytics.test.js b/tests/mcp-client-analytics.test.jsnew file mode 100644index 000000000..f4e173487--- /dev/null+++ b/tests/mcp-client-analytics.test.js@@ -0,0 +1,211 @@+// MCP client analytics against the REAL migration, in an in-process Postgres+// (PGlite): an initialize issues a session id and records the client, a+// tools/call that echoes the id is counted against that client, a call with+// no issued id lands on "unknown", and the report folds the daily rows the+// way the /mcp-clients board reads them.++import { readFileSync } from 'node:fs';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { PGlite } from '@electric-sql/pglite';++const dbState = { pg: null };++vi.mock('../api/_lib/db.js', () => {+ const sql = async (strings, ...values) => {+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');+ const out = await dbState.pg.query(text, values);+ return out.rows;+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++const analytics = await import('../api/_lib/mcp-client-analytics.js');+const { summarizeMcpClients, gatherMcpClients, windowDays, clampReportDays } = await import('../api/_lib/mcp-client-report.js');++const MIGRATION = readFileSync(+ new URL('../api/_lib/migrations/20261008200000_mcp_client_analytics.sql', import.meta.url),+ 'utf8',+);++function makeRes() {+ const h = {};+ return {+ setHeader(k, v) { h[k.toLowerCase()] = v; },+ getHeader(k) { return h[k.toLowerCase()]; },+ headers: h,+ };+}++const init = (name, version = '1.0.0') => ({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name, version } },+});+const call = (tool, id = 2) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: tool, arguments: { q: 'secret prompt text' } } });++beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(MIGRATION);+ // Drain what an earlier test queued without flushing, then start clean.+ await analytics.flushMcpClientEvents();+ await dbState.pg.exec('truncate mcp_client_sessions, mcp_client_daily');+});++describe('client name normalization', () => {+ it('trims, lowercases, strips control characters and caps the length', () => {+ expect(analytics.normalizeClientName(' Claude-AI \n')).toBe('claude-ai');+ expect(analytics.normalizeClientName('x'.repeat(200))).toHaveLength(64);+ expect(analytics.normalizeClientName('')).toBe('unknown');+ expect(analytics.normalizeClientName(42)).toBe('unknown');+ expect(analytics.normalizeClientVersion(' 1.2.3\u0007 ')).toBe('1.2.3');+ });++ it('maps known clientInfo names to one family per client', () => {+ const fam = (n) => analytics.clientFamily(analytics.normalizeClientName(n));+ expect(fam('three-ws-connector-probe')).toBe('probe');+ expect(fam('claude-ai')).toBe('claude');+ expect(fam('claude-code')).toBe('claude-code');+ expect(fam('openai-mcp')).toBe('chatgpt');+ expect(fam('cursor-vscode')).toBe('cursor');+ expect(fam('Visual Studio Code')).toBe('vscode');+ expect(fam('Grok Bot')).toBe('grok');+ expect(fam('my-own-agent')).toBe('my-own-agent');+ });++ it('names the auth kind from the resolved principal and from headers', () => {+ expect(analytics.authKindOf({ source: 'oauth' })).toBe('oauth');+ expect(analytics.authKindOf({ source: 'apikey' })).toBe('key');+ expect(analytics.authKindOf({ source: 'x402' })).toBe('x402');+ expect(analytics.authKindOf({ source: 'free' })).toBe('anonymous');+ expect(analytics.authKindFromHeaders({ headers: { authorization: 'Bearer sk_live_abc' } })).toBe('key');+ expect(analytics.authKindFromHeaders({ headers: { authorization: 'Bearer eyJhbGciOi' } })).toBe('oauth');+ expect(analytics.authKindFromHeaders({ headers: { 'x-payment': 'e30=' } })).toBe('x402');+ expect(analytics.authKindFromHeaders({ headers: {} })).toBe('anonymous');+ });+});++describe('trackMcpRequest', () => {+ it('issues an exposed Mcp-Session-Id on initialize and nothing on other methods', () => {+ const res = makeRes();+ const sid = analytics.trackMcpRequest({ body: init('probe'), req: { headers: {} }, res, surface: 'mcp-studio' });+ expect(sid).toMatch(/^mcs_[0-9a-f-]{36}$/);+ expect(res.headers['mcp-session-id']).toBe(sid);+ expect(res.headers['access-control-expose-headers']).toContain('mcp-session-id');+ expect(analytics.isIssuedSessionId(sid)).toBe(true);++ const res2 = makeRes();+ expect(analytics.trackMcpRequest({ body: call('search_catalog'), req: { headers: {} }, res: res2, surface: 'mcp' })).toBeNull();+ expect(res2.headers['mcp-session-id']).toBeUndefined();+ });++ it('keeps the grk_ prefix the grok rate caps key on', () => {+ const res = makeRes();+ const sid = analytics.trackMcpRequest({ body: init('grok'), req: { headers: {} }, res, surface: 'mcp-grok', sessionPrefix: 'grk' });+ expect(sid).toMatch(/^grk_[0-9a-f-]{36}$/);+ });++ it('records the session, then counts echoed calls against its client', async () => {+ const res = makeRes();+ const sid = analytics.trackMcpRequest({+ body: init(' Three-WS-Connector-Probe ', '1.0.0'),+ req: { headers: {} },+ res,+ surface: 'mcp-studio',+ authKind: 'install',+ });+ await analytics.flushMcpClientEvents();+ for (const tool of ['search_catalog', 'search_catalog', 'getting_started']) {+ analytics.trackMcpRequest({ body: call(tool), req: { headers: { 'mcp-session-id': sid } }, res: makeRes(), surface: 'mcp-studio', authKind: 'install' });+ }+ const out = await analytics.flushMcpClientEvents();+ expect(out.failed).toBe(0);++ const { rows: [session] } = await dbState.pg.query('select * from mcp_client_sessions where session_id = $1', [sid]);+ expect(session).toMatchObject({+ surface: 'mcp-studio',+ client: 'probe',+ client_name: 'three-ws-connector-probe',+ client_version: '1.0.0',+ auth_kind: 'install',+ calls: 3,+ tool_calls: { search_catalog: 2, getting_started: 1 },+ });++ const { rows: daily } = await dbState.pg.query('select * from mcp_client_daily');+ expect(daily).toHaveLength(1);+ expect(daily[0]).toMatchObject({ client: 'probe', sessions: 1, calls: 3, tools: { search_catalog: 2, getting_started: 1 } });+ });++ it('never stores a request body or a tool argument', async () => {+ const res = makeRes();+ const sid = analytics.trackMcpRequest({ body: [init('claude-ai'), call('text_to_3d', 3)], req: { headers: {} }, res, surface: 'mcp-3d', auth: { source: 'oauth' } });+ await analytics.flushMcpClientEvents();+ const { rows } = await dbState.pg.query('select row_to_json(s)::text as j from mcp_client_sessions s');+ expect(rows[0].j).not.toContain('secret prompt text');+ const { rows: [s] } = await dbState.pg.query('select calls, auth_kind from mcp_client_sessions where session_id = $1', [sid]);+ // The batch opened the session and called a tool in one request.+ expect(s).toEqual({ calls: 1, auth_kind: 'oauth' });+ });++ it('counts a call with no issued session id under "unknown"', async () => {+ analytics.trackMcpRequest({ body: call('getting_started'), req: { headers: { 'mcp-session-id': 'forged-id' } }, res: makeRes(), surface: 'mcp', auth: { source: 'x402' } });+ await analytics.flushMcpClientEvents();+ const { rows } = await dbState.pg.query('select client, client_name, auth_kind, calls, sessions, tools from mcp_client_daily');+ expect(rows).toEqual([{ client: 'unknown', client_name: 'unknown', auth_kind: 'x402', calls: 1, sessions: 0, tools: { getting_started: 1 } }]);+ });++ it('folds invented tool names past 200 into "(other)"', async () => {+ const many = Object.fromEntries(Array.from({ length: 200 }, (_, i) => [`t${i}`, 1]));+ const { rows: [r] } = await dbState.pg.query('select mcp_tool_count_add($1::jsonb, $2, 1) as j', [JSON.stringify(many), 'brand_new']);+ expect(r.j['(other)']).toBe(1);+ expect(r.j.brand_new).toBeUndefined();+ const { rows: [r2] } = await dbState.pg.query('select mcp_tool_count_add($1::jsonb, $2, 4) as j', [JSON.stringify(many), 't7']);+ expect(r2.j.t7).toBe(5);+ });+});++describe('the report', () => {+ it('clamps the window', () => {+ expect(clampReportDays(undefined)).toBe(30);+ expect(clampReportDays('')).toBe(30);+ expect(clampReportDays('0')).toBe(1);+ expect(clampReportDays('9999')).toBe(365);+ expect(windowDays(3, new Date('2026-10-08T12:00:00Z'))).toEqual(['2026-10-06', '2026-10-07', '2026-10-08']);+ });++ it('groups per client with top tools, auth mix and a zero-filled daily series', () => {+ const today = new Date('2026-10-08T12:00:00Z');+ const rows = [+ { day: '2026-10-08', surface: 'mcp-grok', client: 'grok', client_name: 'grok bot', client_version: '0.9', auth_kind: 'anonymous', sessions: 3, calls: 7, tools: { text_to_3d: 5, get_job: 2 } },+ { day: '2026-10-07', surface: 'mcp', client: 'claude', client_name: 'claude-ai', client_version: '0.1.0', auth_kind: 'oauth', sessions: 1, calls: 1, tools: { list_my_avatars: 1 } },+ { day: '2026-10-08', surface: 'mcp', client: 'unknown', client_name: 'unknown', client_version: '', auth_kind: 'x402', sessions: 0, calls: 2, tools: { getting_started: 2 } },+ ];+ const r = summarizeMcpClients(rows, { days: 3, today });+ expect(r.totals).toEqual({ sessions: 4, calls: 10, clients: 2, unattributed_calls: 2 });+ expect(r.clients[0]).toMatchObject({ client: 'grok', sessions: 3, calls: 7, calls_per_session: 2.3, top_tools: [{ tool: 'text_to_3d', calls: 5 }, { tool: 'get_job', calls: 2 }] });+ expect(r.daily.map((d) => d.day)).toEqual(['2026-10-06', '2026-10-07', '2026-10-08']);+ expect(r.daily[0].clients).toEqual({});+ expect(r.daily[2].clients.grok).toEqual({ sessions: 3, calls: 7 });+ expect(r.tools[0]).toEqual({ tool: 'text_to_3d', calls: 5 });+ });++ it('reads the real table end to end', async () => {+ const res = makeRes();+ const sid = analytics.trackMcpRequest({ body: init('three-ws-connector-probe'), req: { headers: {} }, res, surface: 'mcp-studio' });+ await analytics.flushMcpClientEvents();+ analytics.trackMcpRequest({ body: call('search_catalog'), req: { headers: { 'mcp-session-id': sid } }, res: makeRes(), surface: 'mcp-studio' });+ await analytics.flushMcpClientEvents();+ const r = await gatherMcpClients({ days: 30 });+ expect(r.ok).toBe(true);+ expect(r.clients.map((c) => c.client)).toEqual(['probe']);+ expect(r.clients[0]).toMatchObject({ sessions: 1, calls: 1, auth: { anonymous: 2 } });+ });++ it('names the failed read instead of reporting an empty window', async () => {+ await dbState.pg.exec('drop table mcp_client_daily');+ const r = await gatherMcpClients({ days: 7 });+ expect(r.ok).toBe(false);+ expect(r.degraded[0].error).toMatch(/does not exist/);+ });+});diff --git a/vercel.json b/vercel.jsonindex 74f680d28..32eabd2b6 100644--- a/vercel.json+++ b/vercel.json@@ -2023,6 +2023,10 @@"src": "/forge-funnel/?","dest": "/forge-funnel.html"},+ {+ "src": "/mcp-clients/?",+ "dest": "/mcp-clients.html"+ },{"src": "/examples/?","dest": "/examples.html"diff --git a/vite.config.js b/vite.config.jsindex 6e0893998..f9c837543 100644--- a/vite.config.js+++ b/vite.config.js@@ -906,6 +906,7 @@ const appConfig = {'likeness-bench': resolve(__dirname, 'pages/likeness-bench.html'),'payment-outcomes': resolve(__dirname, 'pages/payment-outcomes.html'),'forge-funnel': resolve(__dirname, 'pages/forge-funnel.html'),+ 'mcp-clients': resolve(__dirname, 'pages/mcp-clients.html'),search: resolve(__dirname, 'pages/search.html'),rankings: resolve(__dirname, 'pages/rankings.html'),'daily-match': resolve(__dirname, 'pages/daily-match.html'),@@ -2066,6 +2067,8 @@ const appConfig = {'/payment-outcomes/': resolve(root, 'pages/payment-outcomes.html'),'/forge-funnel': resolve(root, 'pages/forge-funnel.html'),'/forge-funnel/': resolve(root, 'pages/forge-funnel.html'),+ '/mcp-clients': resolve(root, 'pages/mcp-clients.html'),+ '/mcp-clients/': resolve(root, 'pages/mcp-clients.html'),'/materialize': resolve(root, 'pages/materialize.html'),'/materialize/': resolve(root, 'pages/materialize.html'),'/inspect': resolve(root, 'pages/inspect.html'),