Skip to content

Commit 670359f

Browse files
aborrusoclaude
andcommitted
feat: add Cloudflare Analytics Engine telemetry (ckan_tool_calls)
- wrangler.toml: ANALYTICS binding → dataset ckan_tool_calls - worker.ts: Env interface, timing per request, writeDataPoint - Schema: tool, server, query, status, country, duration_ms, cache_hit - Binding is optional: worker functions unchanged without it Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 761920b commit 670359f

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

src/worker.ts

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,16 @@ import { createServer, registerAll } from "./server.js";
88
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
99
import { getLastCacheHit } from "./utils/http.js";
1010

11+
interface AnalyticsEngineDataset {
12+
writeDataPoint(event: { blobs?: string[]; doubles?: number[]; indexes?: string[] }): void;
13+
}
14+
15+
interface Env {
16+
ANALYTICS?: AnalyticsEngineDataset;
17+
}
18+
1119
export default {
12-
async fetch(request: Request): Promise<Response> {
20+
async fetch(request: Request, env: Env): Promise<Response> {
1321
const url = new URL(request.url);
1422

1523
// Root endpoint - README
@@ -289,12 +297,41 @@ export default {
289297
}
290298
} catch { /* ignore parse errors (e.g. non-JSON requests) */ }
291299

300+
const t0 = Date.now();
292301
const response = await transport.handleRequest(request);
302+
const durationMs = Date.now() - t0;
293303

294304
if (logEntry) {
295305
const cacheHit = getLastCacheHit();
296306
if (cacheHit !== null) logEntry['cache_hit'] = cacheHit;
307+
logEntry['duration_ms'] = durationMs;
308+
309+
let callStatus = 'ok';
310+
try {
311+
const rj = await response.clone().json() as Record<string, unknown>;
312+
const result = rj?.result as Record<string, unknown> | undefined;
313+
if (result?.isError || rj?.error) callStatus = 'error';
314+
} catch { /* ignore */ }
315+
logEntry['status'] = callStatus;
316+
297317
console.log(JSON.stringify(logEntry));
318+
319+
if (env.ANALYTICS) {
320+
env.ANALYTICS.writeDataPoint({
321+
blobs: [
322+
String(logEntry['tool'] ?? ''),
323+
String(logEntry['server'] ?? ''),
324+
String(logEntry['q'] ?? logEntry['query'] ?? logEntry['id'] ?? ''),
325+
callStatus,
326+
String(logEntry['country'] ?? ''),
327+
],
328+
doubles: [
329+
durationMs,
330+
cacheHit ? 1 : 0,
331+
],
332+
indexes: [String(logEntry['tool'] ?? '')],
333+
});
334+
}
298335
}
299336

300337
// Add CORS headers and service notices

wrangler.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ enabled = true
88

99
[build]
1010
command = "npm run build:worker"
11+
12+
[[analytics_engine_datasets]]
13+
binding = "ANALYTICS"
14+
dataset = "ckan_tool_calls"

0 commit comments

Comments
 (0)