@punchline-analytics/next 0.3.0 → 0.4.1
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 +19 -0
- package/dist/index.js +71 -14
- package/package.json +2 -2
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,10 @@ interface EdgeEvent {
|
|
|
28
37
|
hints: boolean;
|
|
29
38
|
lang: boolean;
|
|
30
39
|
};
|
|
40
|
+
mcp?: {
|
|
41
|
+
calls: McpCall[];
|
|
42
|
+
};
|
|
43
|
+
mcpSession?: string;
|
|
31
44
|
visitorId?: string;
|
|
32
45
|
consent?: true;
|
|
33
46
|
ip: string;
|
|
@@ -87,6 +100,12 @@ interface PunchlineOptions {
|
|
|
87
100
|
serverTiming?: boolean;
|
|
88
101
|
/** Called on configuration or network errors. Default: ignore. */
|
|
89
102
|
onError?: (err: unknown) => void;
|
|
103
|
+
/**
|
|
104
|
+
* Your MCP server's paths, if it has one (Streamable HTTP). Agents' calls to
|
|
105
|
+
* it are recorded: method, tool name and client name only, never arguments
|
|
106
|
+
* or results. Default: any path ending in /mcp.
|
|
107
|
+
*/
|
|
108
|
+
mcpPaths?: string[];
|
|
90
109
|
}
|
|
91
110
|
declare const INTERNAL_HEADER = "x-punchline-internal";
|
|
92
111
|
/** 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}$/;
|
|
@@ -494,9 +519,11 @@ Share link to this page: ${link}
|
|
|
494
519
|
const headers = new Headers(md.headers);
|
|
495
520
|
headers.set("cache-control", "private, no-store");
|
|
496
521
|
headers.delete("content-length");
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
522
|
+
return { response: new Response(body, { status: md.status, headers }), tokenHash: await sha256Hex(token) };
|
|
523
|
+
}
|
|
524
|
+
async function sha256Hex(text) {
|
|
525
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
526
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
500
527
|
}
|
|
501
528
|
function randomBase62(n) {
|
|
502
529
|
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
@@ -562,28 +589,40 @@ function createTracker(options) {
|
|
|
562
589
|
}
|
|
563
590
|
return dsn;
|
|
564
591
|
};
|
|
592
|
+
const send = (config, e) => fetch(config.collectorUrl, {
|
|
593
|
+
method: "POST",
|
|
594
|
+
headers: { authorization: `Bearer ${config.secret}`, "content-type": "application/json" },
|
|
595
|
+
body: JSON.stringify(e),
|
|
596
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
597
|
+
}).then((res) => {
|
|
598
|
+
if (!res.ok) onError(new Error(`Punchline collector responded ${res.status}`));
|
|
599
|
+
return res.body?.cancel();
|
|
600
|
+
});
|
|
565
601
|
return {
|
|
566
602
|
track(request, waitUntil, response) {
|
|
567
603
|
const start = performance.now();
|
|
568
604
|
try {
|
|
569
605
|
const config = resolveDsn();
|
|
606
|
+
if (config && isMcpRequest(request, options.mcpPaths)) {
|
|
607
|
+
const event2 = buildEvent(request, config.siteId, options.readFacts(request), Date.now());
|
|
608
|
+
const sessionId = request.headers.get("mcp-session-id")?.trim();
|
|
609
|
+
const sent2 = readMcpCalls(request).then(async (calls) => {
|
|
610
|
+
if (!calls) return;
|
|
611
|
+
const r = response ? await response.catch(() => null) : null;
|
|
612
|
+
const mcpSession = sessionId && sessionId.length <= 256 ? await sha256Hex(sessionId) : void 0;
|
|
613
|
+
await send(config, { ...event2, mcp: { calls }, ...mcpSession ? { mcpSession } : {}, ...r ? { status: r.status } : {} });
|
|
614
|
+
});
|
|
615
|
+
waitUntil(sent2.catch(onError));
|
|
616
|
+
return { overheadMs: performance.now() - start };
|
|
617
|
+
}
|
|
570
618
|
if (!config || !shouldTrack(request)) return { overheadMs: null };
|
|
571
619
|
const facts = options.readFacts(request);
|
|
572
620
|
const event = buildEvent(request, config.siteId, facts, Date.now(), siteConfig.allowed(config, waitUntil), siteConfig.clickIds(config, waitUntil));
|
|
573
621
|
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
622
|
const sent = response ? response.then(
|
|
584
623
|
(r) => r ? { ...event, status: r.status, ...r.bytes !== null ? { bytes: r.bytes } : {}, ...r.format ? { format: r.format } : {}, ...r.mintedHandoff ? { mintedHandoff: r.mintedHandoff } : {} } : event,
|
|
585
624
|
() => event
|
|
586
|
-
).then(send) : send(event);
|
|
625
|
+
).then((e) => send(config, e)) : send(config, event);
|
|
587
626
|
waitUntil(sent.catch(onError));
|
|
588
627
|
return { overheadMs: performance.now() - start, ...setCookie ? { setCookie } : {} };
|
|
589
628
|
} catch (err) {
|
|
@@ -637,6 +676,7 @@ var TRACKED_EXTENSIONS = /* @__PURE__ */ new Set(["html", "htm", "txt", "md", "x
|
|
|
637
676
|
function shouldTrack(request) {
|
|
638
677
|
if (request.method !== "GET" && request.method !== "HEAD") return false;
|
|
639
678
|
const h = request.headers;
|
|
679
|
+
if (/text\/event-stream/i.test(h.get("accept") ?? "")) return false;
|
|
640
680
|
const dest = h.get("sec-fetch-dest");
|
|
641
681
|
if (dest && dest !== "document") return false;
|
|
642
682
|
if (/prefetch|prerender/i.test(h.get("sec-purpose") ?? "") || /prefetch/i.test(h.get("purpose") ?? "")) return false;
|
|
@@ -645,6 +685,22 @@ function shouldTrack(request) {
|
|
|
645
685
|
const dot = last.lastIndexOf(".");
|
|
646
686
|
return dot <= 0 || TRACKED_EXTENSIONS.has(last.slice(dot + 1).toLowerCase());
|
|
647
687
|
}
|
|
688
|
+
var MCP_MAX_BODY_BYTES = 256 * 1024;
|
|
689
|
+
function isMcpRequest(request, paths) {
|
|
690
|
+
if (request.method !== "POST" || !/application\/json/i.test(request.headers.get("content-type") ?? "")) return false;
|
|
691
|
+
const path = new URL(request.url).pathname.replace(/\/+$/, "") || "/";
|
|
692
|
+
return paths?.length ? paths.some((p) => p.replace(/\/+$/, "") === path) : /(^|\/)mcp$/i.test(path);
|
|
693
|
+
}
|
|
694
|
+
async function readMcpCalls(request) {
|
|
695
|
+
if (Number(request.headers.get("content-length") ?? "0") > MCP_MAX_BODY_BYTES) return null;
|
|
696
|
+
const text = await request.clone().text();
|
|
697
|
+
if (text.length > MCP_MAX_BODY_BYTES) return null;
|
|
698
|
+
try {
|
|
699
|
+
return mcpCallsFromBody(JSON.parse(text));
|
|
700
|
+
} catch {
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
648
704
|
function buildEvent(request, siteId, facts, now = Date.now(), allowed = [], clickTypes = []) {
|
|
649
705
|
const h = request.headers;
|
|
650
706
|
const { host, path, utm, params, handoff, clicks } = sanitizeUrl(request.url, allowed, clickTypes);
|
|
@@ -713,7 +769,8 @@ function createTracker2(options = {}) {
|
|
|
713
769
|
dsn: () => options.dsn ?? (process.env.PUNCHLINE_DSN || process.env.AGENTLENS_DSN || ""),
|
|
714
770
|
readFacts: readVercelFacts,
|
|
715
771
|
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
716
|
-
...options.onError ? { onError: options.onError } : {}
|
|
772
|
+
...options.onError ? { onError: options.onError } : {},
|
|
773
|
+
...options.mcpPaths ? { mcpPaths: options.mcpPaths } : {}
|
|
717
774
|
});
|
|
718
775
|
const dsnSecret = () => {
|
|
719
776
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punchline-analytics/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
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",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@punchline/privacy": "0.0.0",
|
|
32
32
|
"@punchline/schema": "0.0.0",
|
|
33
|
-
"next": "16.4.
|
|
33
|
+
"next": "16.4.6",
|
|
34
34
|
"tsup": "8.5.1",
|
|
35
35
|
"typescript": "5.9.3",
|
|
36
36
|
"@punchline/edge": "0.0.0"
|