@punchline-analytics/next 0.3.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 +18 -0
- package/dist/index.js +64 -11
- package/package.json +1 -1
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
|
|
@@ -28,6 +37,9 @@ interface EdgeEvent {
|
|
|
28
37
|
hints: boolean;
|
|
29
38
|
lang: boolean;
|
|
30
39
|
};
|
|
40
|
+
mcp?: {
|
|
41
|
+
calls: McpCall[];
|
|
42
|
+
};
|
|
31
43
|
visitorId?: string;
|
|
32
44
|
consent?: true;
|
|
33
45
|
ip: string;
|
|
@@ -87,6 +99,12 @@ interface PunchlineOptions {
|
|
|
87
99
|
serverTiming?: boolean;
|
|
88
100
|
/** Called on configuration or network errors. Default: ignore. */
|
|
89
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[];
|
|
90
108
|
}
|
|
91
109
|
declare const INTERNAL_HEADER = "x-punchline-internal";
|
|
92
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);
|
|
@@ -713,7 +765,8 @@ function createTracker2(options = {}) {
|
|
|
713
765
|
dsn: () => options.dsn ?? (process.env.PUNCHLINE_DSN || process.env.AGENTLENS_DSN || ""),
|
|
714
766
|
readFacts: readVercelFacts,
|
|
715
767
|
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
716
|
-
...options.onError ? { onError: options.onError } : {}
|
|
768
|
+
...options.onError ? { onError: options.onError } : {},
|
|
769
|
+
...options.mcpPaths ? { mcpPaths: options.mcpPaths } : {}
|
|
717
770
|
});
|
|
718
771
|
const dsnSecret = () => {
|
|
719
772
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punchline-analytics/next",
|
|
3
|
-
"version": "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",
|