@armature-tech/mcp-analytics 0.6.8 → 0.6.9

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.
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.__getMaxClientInfoCacheEntries = exports.__getClientInfoCacheSize = exports.__isInitializePatchInstalled = exports.__clearClientInfoCache = exports.__setClientInfoForSessionId = exports.getClientInfoForSessionId = exports.installClientInfoCapture = void 0;
4
4
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
5
5
  const utils_js_1 = require("./utils.js");
6
+ const stdio_session_js_1 = require("./stdio-session.js");
6
7
  // In-process map keyed by session id (transport sessionId and/or the
7
8
  // `Mcp-Session-Id` request header). Populated by the patched
8
9
  // `Server.prototype._onrequest` on `initialize` and read by the recorder at
@@ -67,8 +68,13 @@ const captureClientInfoFromInitialize = (server, request, extra) => {
67
68
  sessionIds.add(headerSessionId);
68
69
  if (params._meta?.sessionId)
69
70
  sessionIds.add(params._meta.sessionId);
70
- if (sessionIds.size === 0)
71
- return;
71
+ if (sessionIds.size === 0) {
72
+ // No session key anywhere — a stdio/in-process handshake. The recorder
73
+ // resolves the same process-scoped fallback id for every event on this
74
+ // connection (see stdio-session.ts), so cache the identity under it to
75
+ // keep the dashboard's Client column populated for CLI sessions.
76
+ sessionIds.add((0, stdio_session_js_1.processScopedSessionId)());
77
+ }
72
78
  const clientInfo = {
73
79
  name,
74
80
  version: typeof info?.version === "string" ? info.version : undefined,
@@ -6,6 +6,7 @@ const events_js_1 = require("./events.js");
6
6
  const emit_js_1 = require("./emit.js");
7
7
  const schema_js_1 = require("./schema.js");
8
8
  const utils_js_1 = require("./utils.js");
9
+ const stdio_session_js_1 = require("./stdio-session.js");
9
10
  const client_info_cache_js_1 = require("./client-info-cache.js");
10
11
  const stateless_http_js_1 = require("./stateless-http.js");
11
12
  const nudgeTelemetryDescriptions = (schema) => {
@@ -74,8 +75,29 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
74
75
  return event.workflowRunId
75
76
  ?? (0, utils_js_1.workflowRunIdFromHeaders)(event.headers ?? event.extra?.requestInfo?.headers);
76
77
  };
78
+ // Session id, in falling priority: explicit event/extra value, transport
79
+ // `Mcp-Session-Id` header, then — only for requests with no HTTP headers at
80
+ // all (stdio, in-process) — the process-scoped fallback. Stdio transports
81
+ // never carry a session id, and events shipped with `session_id_hint: null`
82
+ // get bucketed per-actor-per-day at ingest, merging distinct CLI
83
+ // conversations into one activity (see stdio-session.ts). Requests that DO
84
+ // carry headers are excluded from the fallback: many sessions share a
85
+ // long-lived HTTP server process, so the absence of a session id there must
86
+ // stay visible to ingest instead of being glued to one process id.
87
+ const resolveSessionId = (event) => {
88
+ const normalized = (0, events_js_1.normalizeSessionId)(event.sessionId, event.extra);
89
+ if (normalized)
90
+ return normalized;
91
+ const headers = event.headers ?? event.extra?.requestInfo?.headers;
92
+ // Loose == null: an explicit `headers: null` from an untyped JS caller
93
+ // means the same as absent — there is no HTTP request.
94
+ if (headers == null)
95
+ return (0, stdio_session_js_1.processScopedSessionId)();
96
+ const fromHeaders = (0, utils_js_1.headerValue)(headers, "mcp-session-id")?.trim();
97
+ return fromHeaders ? fromHeaders : undefined;
98
+ };
77
99
  const recordSessionInit = async (event) => {
78
- const sessionId = (0, events_js_1.normalizeSessionId)(event.sessionId, event.extra);
100
+ const sessionId = resolveSessionId(event);
79
101
  if (!sessionId)
80
102
  return;
81
103
  const context = await analyticsContextFor({
@@ -121,7 +143,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
121
143
  finishedAtMs,
122
144
  });
123
145
  const requestId = (0, events_js_1.normalizeRequestId)(event.requestId);
124
- const sessionId = (0, events_js_1.normalizeSessionId)(event.sessionId, event.extra);
146
+ const sessionId = resolveSessionId(event);
125
147
  const errorMessage = event.error === undefined
126
148
  ? undefined
127
149
  : event.error instanceof Error
@@ -0,0 +1,2 @@
1
+ export declare const processScopedSessionId: () => string;
2
+ export declare const __resetProcessScopedSessionIdForTests: () => void;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.__resetProcessScopedSessionIdForTests = exports.processScopedSessionId = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ // Session identity for transports that have none: stdio (and in-process)
6
+ // servers never see an `Mcp-Session-Id` — `StdioServerTransport.sessionId`
7
+ // stays undefined and there is no HTTP request — so every event used to ship
8
+ // `session_id_hint: null`. Armature's ingest groups null-hint events into a
9
+ // coarse per-actor daily bucket, which merged *distinct* CLI conversations
10
+ // (e.g. two `claude -p` runs on the same day) into a single activity.
11
+ //
12
+ // A stdio MCP server process is spawned by its client and serves exactly one
13
+ // connection for its whole lifetime, so process identity IS session identity:
14
+ // mint one id per process, lazily, and reuse it for every event that has no
15
+ // other session signal. The recorder only falls back to this id for requests
16
+ // that carry no HTTP headers at all — on an HTTP server many sessions share
17
+ // one long-lived process, and pinning them all to a single id would be worse
18
+ // than the server-side fallback bucketing.
19
+ //
20
+ // The `stdio-` prefix deliberately does NOT match the stateless-HTTP
21
+ // `mcp_<name>_v_<version>_<uuid>` shape, so `parseStatelessSessionClientInfo`
22
+ // can never mistake it for an identity-bearing id and report a bogus client.
23
+ let processSessionId;
24
+ const processScopedSessionId = () => {
25
+ processSessionId ??= `stdio-${(0, node_crypto_1.randomUUID)()}`;
26
+ return processSessionId;
27
+ };
28
+ exports.processScopedSessionId = processScopedSessionId;
29
+ // INTERNAL. Test-only reset so one test process can simulate several stdio
30
+ // server processes. Not reachable through the package name: `exports` only
31
+ // publishes `.` and `./mastra`.
32
+ const __resetProcessScopedSessionIdForTests = () => {
33
+ processSessionId = undefined;
34
+ };
35
+ exports.__resetProcessScopedSessionIdForTests = __resetProcessScopedSessionIdForTests;
@@ -1,5 +1,6 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { headerValue, isRecord } from "./utils.js";
3
+ import { processScopedSessionId } from "./stdio-session.js";
3
4
  // In-process map keyed by session id (transport sessionId and/or the
4
5
  // `Mcp-Session-Id` request header). Populated by the patched
5
6
  // `Server.prototype._onrequest` on `initialize` and read by the recorder at
@@ -64,8 +65,13 @@ const captureClientInfoFromInitialize = (server, request, extra) => {
64
65
  sessionIds.add(headerSessionId);
65
66
  if (params._meta?.sessionId)
66
67
  sessionIds.add(params._meta.sessionId);
67
- if (sessionIds.size === 0)
68
- return;
68
+ if (sessionIds.size === 0) {
69
+ // No session key anywhere — a stdio/in-process handshake. The recorder
70
+ // resolves the same process-scoped fallback id for every event on this
71
+ // connection (see stdio-session.ts), so cache the identity under it to
72
+ // keep the dashboard's Client column populated for CLI sessions.
73
+ sessionIds.add(processScopedSessionId());
74
+ }
69
75
  const clientInfo = {
70
76
  name,
71
77
  version: typeof info?.version === "string" ? info.version : undefined,
@@ -2,7 +2,8 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
3
3
  import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
4
4
  import { appendTelemetryHint, decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
5
- import { createBoundedKeySet, deriveToolResultError, isJsonObjectSchema, isRecord, workflowRunIdFromHeaders } from "./utils.js";
5
+ import { createBoundedKeySet, deriveToolResultError, headerValue, isJsonObjectSchema, isRecord, workflowRunIdFromHeaders } from "./utils.js";
6
+ import { processScopedSessionId } from "./stdio-session.js";
6
7
  import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
7
8
  import { parseStatelessSessionClientInfo } from "./stateless-http.js";
8
9
  const nudgeTelemetryDescriptions = (schema) => {
@@ -71,8 +72,29 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
71
72
  return event.workflowRunId
72
73
  ?? workflowRunIdFromHeaders(event.headers ?? event.extra?.requestInfo?.headers);
73
74
  };
75
+ // Session id, in falling priority: explicit event/extra value, transport
76
+ // `Mcp-Session-Id` header, then — only for requests with no HTTP headers at
77
+ // all (stdio, in-process) — the process-scoped fallback. Stdio transports
78
+ // never carry a session id, and events shipped with `session_id_hint: null`
79
+ // get bucketed per-actor-per-day at ingest, merging distinct CLI
80
+ // conversations into one activity (see stdio-session.ts). Requests that DO
81
+ // carry headers are excluded from the fallback: many sessions share a
82
+ // long-lived HTTP server process, so the absence of a session id there must
83
+ // stay visible to ingest instead of being glued to one process id.
84
+ const resolveSessionId = (event) => {
85
+ const normalized = normalizeSessionId(event.sessionId, event.extra);
86
+ if (normalized)
87
+ return normalized;
88
+ const headers = event.headers ?? event.extra?.requestInfo?.headers;
89
+ // Loose == null: an explicit `headers: null` from an untyped JS caller
90
+ // means the same as absent — there is no HTTP request.
91
+ if (headers == null)
92
+ return processScopedSessionId();
93
+ const fromHeaders = headerValue(headers, "mcp-session-id")?.trim();
94
+ return fromHeaders ? fromHeaders : undefined;
95
+ };
74
96
  const recordSessionInit = async (event) => {
75
- const sessionId = normalizeSessionId(event.sessionId, event.extra);
97
+ const sessionId = resolveSessionId(event);
76
98
  if (!sessionId)
77
99
  return;
78
100
  const context = await analyticsContextFor({
@@ -118,7 +140,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
118
140
  finishedAtMs,
119
141
  });
120
142
  const requestId = normalizeRequestId(event.requestId);
121
- const sessionId = normalizeSessionId(event.sessionId, event.extra);
143
+ const sessionId = resolveSessionId(event);
122
144
  const errorMessage = event.error === undefined
123
145
  ? undefined
124
146
  : event.error instanceof Error
@@ -0,0 +1,2 @@
1
+ export declare const processScopedSessionId: () => string;
2
+ export declare const __resetProcessScopedSessionIdForTests: () => void;
@@ -0,0 +1,30 @@
1
+ import { randomUUID } from "node:crypto";
2
+ // Session identity for transports that have none: stdio (and in-process)
3
+ // servers never see an `Mcp-Session-Id` — `StdioServerTransport.sessionId`
4
+ // stays undefined and there is no HTTP request — so every event used to ship
5
+ // `session_id_hint: null`. Armature's ingest groups null-hint events into a
6
+ // coarse per-actor daily bucket, which merged *distinct* CLI conversations
7
+ // (e.g. two `claude -p` runs on the same day) into a single activity.
8
+ //
9
+ // A stdio MCP server process is spawned by its client and serves exactly one
10
+ // connection for its whole lifetime, so process identity IS session identity:
11
+ // mint one id per process, lazily, and reuse it for every event that has no
12
+ // other session signal. The recorder only falls back to this id for requests
13
+ // that carry no HTTP headers at all — on an HTTP server many sessions share
14
+ // one long-lived process, and pinning them all to a single id would be worse
15
+ // than the server-side fallback bucketing.
16
+ //
17
+ // The `stdio-` prefix deliberately does NOT match the stateless-HTTP
18
+ // `mcp_<name>_v_<version>_<uuid>` shape, so `parseStatelessSessionClientInfo`
19
+ // can never mistake it for an identity-bearing id and report a bogus client.
20
+ let processSessionId;
21
+ export const processScopedSessionId = () => {
22
+ processSessionId ??= `stdio-${randomUUID()}`;
23
+ return processSessionId;
24
+ };
25
+ // INTERNAL. Test-only reset so one test process can simulate several stdio
26
+ // server processes. Not reachable through the package name: `exports` only
27
+ // publishes `.` and `./mastra`.
28
+ export const __resetProcessScopedSessionIdForTests = () => {
29
+ processSessionId = undefined;
30
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.8",
3
+ "version": "0.6.9",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",