@punchline-analytics/next 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,14 @@
1
1
  import { NextRequest, NextFetchEvent, NextResponse } from 'next/server.js';
2
2
 
3
+ interface McpCall {
4
+ /** JSON-RPC method: "initialize", "tools/call", "tools/list", "notifications/initialized", … */
5
+ method: string;
6
+ /** tools/call and prompts/get: the tool or prompt name. */
7
+ tool?: string;
8
+ /** initialize: the client's name and version, as it reports them ("claude-ai 0.1.0"). */
9
+ client?: string;
10
+ }
11
+
3
12
  /**
4
13
  * The event sent to the collector. Declared here so the published packages'
5
14
  * types are self-contained; the check below fails the build if it ever stops
@@ -23,6 +32,14 @@ interface EdgeEvent {
23
32
  clicks?: Record<string, string>;
24
33
  accept: string | null;
25
34
  query?: string;
35
+ browserHeaders?: {
36
+ fetch: boolean;
37
+ hints: boolean;
38
+ lang: boolean;
39
+ };
40
+ mcp?: {
41
+ calls: McpCall[];
42
+ };
26
43
  visitorId?: string;
27
44
  consent?: true;
28
45
  ip: string;
@@ -82,6 +99,12 @@ interface PunchlineOptions {
82
99
  serverTiming?: boolean;
83
100
  /** Called on configuration or network errors. Default: ignore. */
84
101
  onError?: (err: unknown) => void;
102
+ /**
103
+ * Your MCP server's paths, if it has one (Streamable HTTP). Agents' calls to
104
+ * it are recorded: method, tool name and client name only, never arguments
105
+ * or results. Default: any path ending in /mcp.
106
+ */
107
+ mcpPaths?: string[];
85
108
  }
86
109
  declare const INTERNAL_HEADER = "x-punchline-internal";
87
110
  /** A ready-made proxy function. */
package/dist/index.js CHANGED
@@ -7,6 +7,31 @@ new TextEncoder();
7
7
  var UTM_KEYS = ["source", "medium", "campaign", "term", "content"];
8
8
  var ACCEPT_MAX_LENGTH = 200;
9
9
 
10
+ // ../schema/src/mcp.ts
11
+ var MAX_MCP_CALLS = 20;
12
+ var MCP_METHOD = /^[a-z][a-z/_]{0,39}$/i;
13
+ var MCP_TOOL = /^[A-Za-z0-9_.:-]{1,64}$/;
14
+ var cleanClient = (s) => s.replace(/[^\x20-\x7e]/g, "").trim().slice(0, 60);
15
+ function callOf(m) {
16
+ if (!m || typeof m !== "object" || Array.isArray(m)) return null;
17
+ const r = m;
18
+ if (r.jsonrpc !== "2.0" || typeof r.method !== "string" || !MCP_METHOD.test(r.method)) return null;
19
+ const call = { method: r.method };
20
+ const params = r.params && typeof r.params === "object" ? r.params : {};
21
+ if ((r.method === "tools/call" || r.method === "prompts/get") && typeof params.name === "string" && MCP_TOOL.test(params.name)) call.tool = params.name;
22
+ if (r.method === "initialize") {
23
+ const info = params.clientInfo && typeof params.clientInfo === "object" ? params.clientInfo : {};
24
+ const client = cleanClient([info.name, info.version].filter((v) => typeof v === "string").join(" "));
25
+ if (client) call.client = client;
26
+ }
27
+ return call;
28
+ }
29
+ function mcpCallsFromBody(body) {
30
+ const messages = Array.isArray(body) ? body : [body];
31
+ const calls = messages.map(callOf).filter((c) => c !== null).slice(0, MAX_MCP_CALLS);
32
+ return calls.length ? calls : null;
33
+ }
34
+
10
35
  // ../schema/src/tokens.ts
11
36
  var CLICK_ID_PARAMS = ["gclid", "gbraid", "wbraid", "fbclid"];
12
37
  var CLICK_ID = /^[A-Za-z0-9_.-]{8,500}$/;
@@ -562,28 +587,38 @@ function createTracker(options) {
562
587
  }
563
588
  return dsn;
564
589
  };
590
+ const send = (config, e) => fetch(config.collectorUrl, {
591
+ method: "POST",
592
+ headers: { authorization: `Bearer ${config.secret}`, "content-type": "application/json" },
593
+ body: JSON.stringify(e),
594
+ signal: AbortSignal.timeout(timeoutMs)
595
+ }).then((res) => {
596
+ if (!res.ok) onError(new Error(`Punchline collector responded ${res.status}`));
597
+ return res.body?.cancel();
598
+ });
565
599
  return {
566
600
  track(request, waitUntil, response) {
567
601
  const start = performance.now();
568
602
  try {
569
603
  const config = resolveDsn();
604
+ if (config && isMcpRequest(request, options.mcpPaths)) {
605
+ const event2 = buildEvent(request, config.siteId, options.readFacts(request), Date.now());
606
+ const sent2 = readMcpCalls(request).then(async (calls) => {
607
+ if (!calls) return;
608
+ const r = response ? await response.catch(() => null) : null;
609
+ await send(config, { ...event2, mcp: { calls }, ...r ? { status: r.status } : {} });
610
+ });
611
+ waitUntil(sent2.catch(onError));
612
+ return { overheadMs: performance.now() - start };
613
+ }
570
614
  if (!config || !shouldTrack(request)) return { overheadMs: null };
571
615
  const facts = options.readFacts(request);
572
616
  const event = buildEvent(request, config.siteId, facts, Date.now(), siteConfig.allowed(config, waitUntil), siteConfig.clickIds(config, waitUntil));
573
617
  const setCookie = rememberVisitor(request, event, siteConfig.visitors(config, waitUntil));
574
- const send = (e) => fetch(config.collectorUrl, {
575
- method: "POST",
576
- headers: { authorization: `Bearer ${config.secret}`, "content-type": "application/json" },
577
- body: JSON.stringify(e),
578
- signal: AbortSignal.timeout(timeoutMs)
579
- }).then((res) => {
580
- if (!res.ok) onError(new Error(`Punchline collector responded ${res.status}`));
581
- return res.body?.cancel();
582
- });
583
618
  const sent = response ? response.then(
584
619
  (r) => r ? { ...event, status: r.status, ...r.bytes !== null ? { bytes: r.bytes } : {}, ...r.format ? { format: r.format } : {}, ...r.mintedHandoff ? { mintedHandoff: r.mintedHandoff } : {} } : event,
585
620
  () => event
586
- ).then(send) : send(event);
621
+ ).then((e) => send(config, e)) : send(config, event);
587
622
  waitUntil(sent.catch(onError));
588
623
  return { overheadMs: performance.now() - start, ...setCookie ? { setCookie } : {} };
589
624
  } catch (err) {
@@ -637,6 +672,7 @@ var TRACKED_EXTENSIONS = /* @__PURE__ */ new Set(["html", "htm", "txt", "md", "x
637
672
  function shouldTrack(request) {
638
673
  if (request.method !== "GET" && request.method !== "HEAD") return false;
639
674
  const h = request.headers;
675
+ if (/text\/event-stream/i.test(h.get("accept") ?? "")) return false;
640
676
  const dest = h.get("sec-fetch-dest");
641
677
  if (dest && dest !== "document") return false;
642
678
  if (/prefetch|prerender/i.test(h.get("sec-purpose") ?? "") || /prefetch/i.test(h.get("purpose") ?? "")) return false;
@@ -645,6 +681,22 @@ function shouldTrack(request) {
645
681
  const dot = last.lastIndexOf(".");
646
682
  return dot <= 0 || TRACKED_EXTENSIONS.has(last.slice(dot + 1).toLowerCase());
647
683
  }
684
+ var MCP_MAX_BODY_BYTES = 256 * 1024;
685
+ function isMcpRequest(request, paths) {
686
+ if (request.method !== "POST" || !/application\/json/i.test(request.headers.get("content-type") ?? "")) return false;
687
+ const path = new URL(request.url).pathname.replace(/\/+$/, "") || "/";
688
+ return paths?.length ? paths.some((p) => p.replace(/\/+$/, "") === path) : /(^|\/)mcp$/i.test(path);
689
+ }
690
+ async function readMcpCalls(request) {
691
+ if (Number(request.headers.get("content-length") ?? "0") > MCP_MAX_BODY_BYTES) return null;
692
+ const text = await request.clone().text();
693
+ if (text.length > MCP_MAX_BODY_BYTES) return null;
694
+ try {
695
+ return mcpCallsFromBody(JSON.parse(text));
696
+ } catch {
697
+ return null;
698
+ }
699
+ }
648
700
  function buildEvent(request, siteId, facts, now = Date.now(), allowed = [], clickTypes = []) {
649
701
  const h = request.headers;
650
702
  const { host, path, utm, params, handoff, clicks } = sanitizeUrl(request.url, allowed, clickTypes);
@@ -667,6 +719,8 @@ function buildEvent(request, siteId, facts, now = Date.now(), allowed = [], clic
667
719
  ...clicks ? { clicks } : {},
668
720
  accept: truncateAccept(h.get("accept")),
669
721
  ...query ? { query } : {},
722
+ // Presence only, never values: scripts that borrow a browser's name rarely send these (R15).
723
+ browserHeaders: { fetch: h.has("sec-fetch-dest") || h.has("sec-fetch-mode"), hints: h.has("sec-ch-ua"), lang: h.has("accept-language") },
670
724
  ip: (facts.ip || "unknown").slice(0, 45),
671
725
  userAgent: h.get("user-agent") ?? "",
672
726
  gpc: h.get("sec-gpc") === "1",
@@ -711,7 +765,8 @@ function createTracker2(options = {}) {
711
765
  dsn: () => options.dsn ?? (process.env.PUNCHLINE_DSN || process.env.AGENTLENS_DSN || ""),
712
766
  readFacts: readVercelFacts,
713
767
  ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
714
- ...options.onError ? { onError: options.onError } : {}
768
+ ...options.onError ? { onError: options.onError } : {},
769
+ ...options.mcpPaths ? { mcpPaths: options.mcpPaths } : {}
715
770
  });
716
771
  const dsnSecret = () => {
717
772
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punchline-analytics/next",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "See which visitors are AI agents: Next.js middleware/proxy for Punchline Analytics. Forwards a minimal, privacy-reduced event per page request.",
5
5
  "type": "module",
6
6
  "license": "MIT",