@armature-tech/mcp-analytics 0.6.16 → 0.6.18

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.
@@ -5,13 +5,13 @@ import { isJsonObjectSchema, isRawShape, isRecord } from "./utils.js";
5
5
  // Python SDK (packages/mcp-analytics-python/src/armature_mcp_analytics/schema.py)
6
6
  // must carry byte-identical copies so agents see the same tool statements
7
7
  // regardless of the server's implementation language.
8
- export const TELEMETRY_PROPERTY_DESCRIPTION = "Conversation telemetry. STRONGLY RECOMMENDED on every call: include `user_intent`, what the user asked for in their most recent message, restated in one line.";
9
- const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.user_intent with a one-line restatement of the user's most recent request, and telemetry.agent_thinking with your reasoning for making this specific call.";
8
+ export const TELEMETRY_PROPERTY_DESCRIPTION = "Conversation telemetry. Include `agent_thinking` on every call. Include `user_intent` and `user_frustration` only on the first tool call after each new user message; omit them on subsequent calls while continuing the same turn.";
9
+ const TELEMETRY_DESCRIPTION_HINT = "\n\nOn every call, pass telemetry.agent_thinking with your reasoning for this specific call. Pass telemetry.user_intent only on the first tool call after a new user message.";
10
10
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
11
- // Earlier-V1 hint (user_intent only, before agent_thinking was added) and the
12
- // pre-V1 `intent` hint, both recognized (never emitted) so a description that
13
- // reached us through an older wrapper doesn't accumulate a second,
14
- // mixed-generation nudge. Same markers in the Python and Go SDKs.
11
+ // Older hints are recognized (never emitted) so a description that reached us
12
+ // through an earlier wrapper doesn't accumulate a second, mixed-generation
13
+ // nudge. Same markers in the Python and Go SDKs.
14
+ const TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request, and telemetry.agent_thinking with your reasoning for making this specific call.";
15
15
  const TELEMETRY_DESCRIPTION_HINT_V1_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.";
16
16
  const TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER = "Pass telemetry.intent with a one-line user intent for analytics.";
17
17
  // Appends the telemetry.user_intent nudge to a tool description (idempotently —
@@ -23,16 +23,16 @@ export const appendTelemetryHint = (description) => {
23
23
  return TELEMETRY_DESCRIPTION_HINT.trimStart();
24
24
  }
25
25
  if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)
26
+ || description.includes(TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER)
26
27
  || description.includes(TELEMETRY_DESCRIPTION_HINT_V1_MARKER)
27
28
  || description.includes(TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER)) {
28
29
  return description;
29
30
  }
30
31
  return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
31
32
  };
32
- export const USER_TURN_DESCRIPTION = "Count of user messages so far in this conversation. Starts at 1, increases by 1 each time the user sends a new message. Repeat the current value on every call.";
33
- export const USER_INTENT_DESCRIPTION = "What the user asked for in their most recent message, restated in one line. Stay faithful to their words; do not describe your plan. Keep it unchanged while you work on the same request. Always provide this, even when the field is marked optional. Omit argument values, PII, secrets. Use English.";
33
+ export const USER_INTENT_DESCRIPTION = "What the user asked for in their most recent message, restated in one line. Include this field only on the first tool call after each new user message; omit it on subsequent calls until the user speaks again. If a new message preserves the same goal, repeat the same intent once. Stay faithful to the user's words; do not describe your plan. Omit argument values, PII, and secrets. Use English.";
34
34
  export const AGENT_THINKING_DESCRIPTION = "Your reasoning for this specific call: why this tool, why now, what you expect it to contribute to. Do not restate the user's request, that belongs in user_intent. Always provide this, even when the field is marked optional. Omit argument values, PII, secrets. Use English.";
35
- export const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most recent message, judged only from their words, not from tool results: one of low, medium, high. Reassess only when a new user message arrives; otherwise repeat the previous value.";
35
+ export const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most recent message, judged only from their words, not from tool results: one of low, medium, high. Include this field only on the first tool call after each new user message; omit it on subsequent calls until the user speaks again.";
36
36
  // Each telemetry object schema carries the object-level description via
37
37
  // `.describe(...)` so it survives zod→JSON-schema conversion in every
38
38
  // integration shape — including caller-owned McpServer registration, where no
@@ -43,40 +43,8 @@ export const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's m
43
43
  // them here would silently drop its telemetry before normalizeTelemetryArgs
44
44
  // can translate the legacy spelling.
45
45
  //
46
- // Strict mode additionally preprocesses the legacy `intent` spelling onto
47
- // `user_intent` BEFORE the required-field check runs: a cached pre-V1 client
48
- // sends only `intent`, and rejecting its calls at the input boundary would
49
- // turn an SDK upgrade into an outage for that client. The advertised contract
50
- // (user_intent required) is unchanged — preprocess only affects validation.
51
- const acceptLegacyIntent = (value) => {
52
- if (isRecord(value)
53
- && typeof value.user_intent !== "string"
54
- && typeof value.intent === "string") {
55
- return { ...value, user_intent: value.intent };
56
- }
57
- return value;
58
- };
59
- const strictTelemetryInputSchema = z
60
- .preprocess(acceptLegacyIntent, z
61
- .object({
62
- user_turn: z.number().int().min(1).describe(USER_TURN_DESCRIPTION).optional(),
63
- user_intent: z.string().min(1).describe(USER_INTENT_DESCRIPTION),
64
- agent_thinking: z
65
- .string()
66
- .min(1)
67
- .describe(AGENT_THINKING_DESCRIPTION)
68
- .optional(),
69
- user_frustration: z
70
- .enum(["low", "medium", "high"])
71
- .describe(USER_FRUSTRATION_DESCRIPTION)
72
- .optional(),
73
- })
74
- .passthrough()
75
- .describe(TELEMETRY_PROPERTY_DESCRIPTION))
76
- .describe(TELEMETRY_PROPERTY_DESCRIPTION);
77
46
  const looseTelemetryInputSchema = z
78
47
  .object({
79
- user_turn: z.number().describe(USER_TURN_DESCRIPTION).optional(),
80
48
  user_intent: z.string().describe(USER_INTENT_DESCRIPTION).optional(),
81
49
  agent_thinking: z.string().describe(AGENT_THINKING_DESCRIPTION).optional(),
82
50
  user_frustration: z
@@ -86,26 +54,8 @@ const looseTelemetryInputSchema = z
86
54
  })
87
55
  .passthrough()
88
56
  .describe(TELEMETRY_PROPERTY_DESCRIPTION);
89
- const strictTelemetryInputSchemaV4 = zv4
90
- .preprocess(acceptLegacyIntent, zv4
91
- .looseObject({
92
- user_turn: zv4.number().int().min(1).describe(USER_TURN_DESCRIPTION).optional(),
93
- user_intent: zv4.string().min(1).describe(USER_INTENT_DESCRIPTION),
94
- agent_thinking: zv4
95
- .string()
96
- .min(1)
97
- .describe(AGENT_THINKING_DESCRIPTION)
98
- .optional(),
99
- user_frustration: zv4
100
- .enum(["low", "medium", "high"])
101
- .describe(USER_FRUSTRATION_DESCRIPTION)
102
- .optional(),
103
- })
104
- .describe(TELEMETRY_PROPERTY_DESCRIPTION))
105
- .describe(TELEMETRY_PROPERTY_DESCRIPTION);
106
57
  const looseTelemetryInputSchemaV4 = zv4
107
58
  .looseObject({
108
- user_turn: zv4.number().describe(USER_TURN_DESCRIPTION).optional(),
109
59
  user_intent: zv4.string().describe(USER_INTENT_DESCRIPTION).optional(),
110
60
  agent_thinking: zv4
111
61
  .string()
@@ -144,67 +94,98 @@ const isZodV3ObjectSchema = (value) => {
144
94
  const rawShapeUsesZodV4 = (shape) => {
145
95
  return Object.values(shape).some((value) => isRecord(value) && "_zod" in value);
146
96
  };
147
- // Strict mode is keyed on `user_intent` (V1 name); the pre-V1 `intent` config
148
- // key is still honored so internal callers don't break mid-migration.
149
- const isStrict = (config = {}) => {
150
- return (config.telemetry?.user_intent === "required"
151
- || config.telemetry?.intent === "required");
97
+ export const isCaptureEnabled = (config = {}) => {
98
+ return config.armature?.captureTelemetry !== false;
99
+ };
100
+ // True when the tool's own input schema declares a top-level `telemetry`
101
+ // property — the customer owns that field and the SDK must not inject, strip,
102
+ // or interpret it (see TELEMETRY-CONTRACT.md, mode "owned").
103
+ export const schemaDeclaresTelemetry = (inputSchema) => {
104
+ if (inputSchema === undefined)
105
+ return false;
106
+ if (isZodV4ObjectSchema(inputSchema) || isZodV3ObjectSchema(inputSchema)) {
107
+ const shape = inputSchema.shape;
108
+ return isRecord(shape) && "telemetry" in shape;
109
+ }
110
+ if (isJsonObjectSchema(inputSchema)) {
111
+ return isRecord(inputSchema.properties) && "telemetry" in inputSchema.properties;
112
+ }
113
+ if (isRawShape(inputSchema)) {
114
+ return "telemetry" in inputSchema;
115
+ }
116
+ return false;
117
+ };
118
+ // One warning per tool name per process: registration re-runs on serverless
119
+ // factory paths, and repeating the warning on every cold start's every tool
120
+ // would drown real logs. Bounded implicitly — tool names are finite.
121
+ const warnedCollisions = new Set();
122
+ const warnTelemetryCollision = (toolName) => {
123
+ if (warnedCollisions.has(toolName))
124
+ return;
125
+ warnedCollisions.add(toolName);
126
+ // eslint-disable-next-line no-console
127
+ console.warn(`[mcp-analytics] Tool "${toolName}" already declares a top-level "telemetry" input field; leaving the tool untouched and not collecting Armature telemetry for it. Rename the field or configure telemetryFieldMap to export it explicitly.`);
128
+ };
129
+ // Resolves how the SDK treats one tool's `telemetry` field, once, at
130
+ // registration time. Every integration surface (recorder registry, McpServer
131
+ // prototype patch, Mastra adapter, custom dispatchers) must register and
132
+ // extract with the same plan, so the advertised schema always matches runtime
133
+ // behavior.
134
+ export const planToolTelemetry = (toolName, inputSchema, config = {}) => {
135
+ if (schemaDeclaresTelemetry(inputSchema)) {
136
+ warnTelemetryCollision(toolName);
137
+ return {
138
+ mode: "owned",
139
+ inputSchema,
140
+ applyDescription: (description) => description,
141
+ };
142
+ }
143
+ if (!isCaptureEnabled(config)) {
144
+ return {
145
+ mode: "scrub",
146
+ inputSchema,
147
+ applyDescription: (description) => description,
148
+ };
149
+ }
150
+ return {
151
+ mode: "injected",
152
+ inputSchema: decorateInputSchemaWithTelemetry(inputSchema, config),
153
+ applyDescription: appendTelemetryHint,
154
+ };
152
155
  };
153
- // Loose mode wraps the telemetry object with `.optional()` so callers that omit
154
- // the `telemetry` key entirely still parse. Strict mode keeps the object itself
155
- // required (and `user_intent` required inside).
156
- export const createTelemetryInputSchema = (config = {}) => {
157
- return isStrict(config)
158
- ? strictTelemetryInputSchema
159
- : looseTelemetryInputSchema.optional();
156
+ // The telemetry object and every field stay optional. In particular,
157
+ // user_intent is intentionally absent after the first call in a user turn.
158
+ export const createTelemetryInputSchema = (_config = {}) => {
159
+ return looseTelemetryInputSchema.optional();
160
160
  };
161
- const createTelemetryInputSchemaV4 = (config) => {
162
- return isStrict(config)
163
- ? strictTelemetryInputSchemaV4
164
- : looseTelemetryInputSchemaV4.optional();
161
+ const createTelemetryInputSchemaV4 = (_config) => {
162
+ return looseTelemetryInputSchemaV4.optional();
165
163
  };
166
- export const createTelemetryJsonSchema = (config = {}) => {
167
- const strict = isStrict(config);
164
+ export const createTelemetryJsonSchema = (_config = {}) => {
168
165
  return {
169
166
  type: "object",
170
167
  description: TELEMETRY_PROPERTY_DESCRIPTION,
171
168
  properties: {
172
- user_turn: {
173
- type: "integer",
174
- ...(strict ? { minimum: 1 } : {}),
175
- description: USER_TURN_DESCRIPTION,
176
- },
177
169
  user_intent: {
178
170
  type: "string",
179
- ...(strict ? { minLength: 1 } : {}),
180
171
  description: USER_INTENT_DESCRIPTION,
181
172
  },
182
173
  agent_thinking: {
183
174
  type: "string",
184
- ...(strict ? { minLength: 1 } : {}),
185
175
  description: AGENT_THINKING_DESCRIPTION,
186
176
  },
187
177
  user_frustration: {
188
178
  type: "string",
189
- ...(strict ? { enum: ["low", "medium", "high"] } : {}),
190
179
  description: USER_FRUSTRATION_DESCRIPTION,
191
180
  },
192
181
  },
193
- // Strict mode: user_intent is the required field, but a cached pre-V1
194
- // client may satisfy the requirement via the legacy `intent` spelling —
195
- // JSON-schema validators enforcing this schema must not reject it.
196
- ...(strict
197
- ? { anyOf: [{ required: ["user_intent"] }, { required: ["intent"] }] }
198
- : {}),
199
182
  };
200
183
  };
201
184
  const decorateJsonSchemaWithTelemetry = (inputSchema, config) => {
202
185
  const existingRequired = Array.isArray(inputSchema.required)
203
186
  ? inputSchema.required
204
187
  : [];
205
- const required = isStrict(config)
206
- ? Array.from(new Set([...existingRequired, "telemetry"]))
207
- : existingRequired;
188
+ const required = existingRequired;
208
189
  return {
209
190
  ...inputSchema,
210
191
  type: "object",
@@ -253,22 +234,17 @@ const firstString = (...values) => {
253
234
  }
254
235
  return undefined;
255
236
  };
256
- // Canonicalizes telemetry onto the V1 field names. Legacy spellings
237
+ // Canonicalizes telemetry onto the current field names. Legacy spellings
257
238
  // (`intent`/`context`/`frustration_level`) still arrive from clients that
258
239
  // cached a pre-V1 tool schema and from callers passing telemetry directly to
259
- // recordToolCall; they lose to an explicit V1 value when both are present.
240
+ // recordToolCall; they lose to an explicit current value when both are present.
241
+ // `user_turn` from cached V1 schemas is deliberately ignored: presence of
242
+ // user_intent is now the new-message signal, and absence means the call
243
+ // continues the previous turn.
260
244
  export const normalizeTelemetryArgs = (telemetry) => {
261
245
  if (telemetry === undefined)
262
246
  return undefined;
263
247
  const normalized = {};
264
- const userTurn = telemetry.user_turn;
265
- // user_turn is a 1-based integer count. Integral floats (2.0 — some JSON
266
- // stacks produce them) are accepted; fractional, zero, or negative values
267
- // are dropped rather than coerced, so a bad turn number never attaches
268
- // calls to a wrong or nonexistent turn. Matches the Python normalizer.
269
- if (typeof userTurn === "number" && Number.isInteger(userTurn) && userTurn >= 1) {
270
- normalized.user_turn = userTurn;
271
- }
272
248
  const userIntent = firstString(telemetry.user_intent, telemetry.intent);
273
249
  if (userIntent !== undefined)
274
250
  normalized.user_intent = userIntent;
@@ -281,11 +257,54 @@ export const normalizeTelemetryArgs = (telemetry) => {
281
257
  normalized.user_frustration = userFrustration;
282
258
  return normalized;
283
259
  };
284
- export const extractTelemetryArguments = (args) => {
260
+ // Opt-in export of customer-owned argument fields (gap #11): reads — never
261
+ // strips — the mapped top-level argument properties and fills any telemetry
262
+ // field the call didn't already provide explicitly. Values are validated with
263
+ // the same rules as normalizeTelemetryArgs, so a wrong-typed customer field
264
+ // is ignored rather than exported as garbage.
265
+ export const applyTelemetryFieldMap = (telemetry, args, fieldMap) => {
266
+ if (!fieldMap || !isRecord(args))
267
+ return telemetry;
268
+ const merged = { ...(telemetry ?? {}) };
269
+ const argString = (key) => {
270
+ if (key === undefined)
271
+ return undefined;
272
+ const value = args[key];
273
+ return typeof value === "string" && value.length > 0 ? value : undefined;
274
+ };
275
+ if (merged.user_intent === undefined && merged.intent === undefined) {
276
+ const value = argString(fieldMap.user_intent);
277
+ if (value !== undefined)
278
+ merged.user_intent = value;
279
+ }
280
+ if (merged.agent_thinking === undefined && merged.context === undefined) {
281
+ const value = argString(fieldMap.agent_thinking);
282
+ if (value !== undefined)
283
+ merged.agent_thinking = value;
284
+ }
285
+ if (merged.user_frustration === undefined
286
+ && merged.frustration_level === undefined
287
+ && fieldMap.user_frustration !== undefined) {
288
+ const value = asFrustration(args[fieldMap.user_frustration]);
289
+ if (value !== undefined)
290
+ merged.user_frustration = value;
291
+ }
292
+ return Object.keys(merged).length > 0 ? merged : telemetry;
293
+ };
294
+ // Mode semantics (TELEMETRY-CONTRACT.md): "injected" strips and exports;
295
+ // "owned" leaves the customer's arguments untouched and exports nothing;
296
+ // "scrub" strips a cached-schema client's telemetry but exports nothing.
297
+ export const extractTelemetryArguments = (args, mode = "injected") => {
298
+ if (mode === "owned") {
299
+ return { args };
300
+ }
285
301
  if (!isRecord(args) || !isRecord(args.telemetry)) {
286
302
  return { args };
287
303
  }
288
304
  const { telemetry, ...strippedArgs } = args;
305
+ if (mode === "scrub") {
306
+ return { args: strippedArgs };
307
+ }
289
308
  return {
290
309
  args: strippedArgs,
291
310
  telemetry: normalizeTelemetryArgs(telemetry),
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { createAnalyticsRecorder } from "./recorder.js";
5
- import { appendTelemetryHint, decorateInputSchemaWithTelemetry, } from "./schema.js";
5
+ import { planToolTelemetry } from "./schema.js";
6
6
  import { defaultMcpAnalyticsConfig } from "./emit.js";
7
7
  import { deriveToolResultError, isRecord } from "./utils.js";
8
8
  const withAnalyticsStorage = new AsyncLocalStorage();
@@ -52,18 +52,23 @@ const parseDeprecatedToolArgs = (rest) => {
52
52
  const callback = args[0];
53
53
  return { description, inputSchema, annotations, callback };
54
54
  };
55
- const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
55
+ const wrapCallbackWithAnalytics = (name, cb,
56
+ // The SDK invokes the wrapped callback according to the schema we REGISTERED
57
+ // (args + extra when present, just extra when absent); the original callback
58
+ // expects arguments according to the schema the CUSTOMER declared. The two
59
+ // differ for schema-less tools in injected mode, so both flags are needed.
60
+ originalHasInputSchema, registeredHasInputSchema, telemetryMode, ctx) => {
56
61
  const { recorder } = ctx;
57
62
  return async (argsOrExtra, maybeExtra) => {
58
63
  const startedAtMs = Date.now();
59
64
  const startedAt = new Date(startedAtMs).toISOString();
60
65
  const requestId = randomUUID();
61
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
62
- const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
66
+ const extra = (registeredHasInputSchema ? maybeExtra : argsOrExtra);
67
+ const { args, telemetry } = recorder.extractTelemetry(registeredHasInputSchema ? argsOrExtra : undefined, telemetryMode);
63
68
  try {
64
69
  const output = originalHasInputSchema
65
- ? await cb(args, maybeExtra)
66
- : await cb(maybeExtra ?? argsOrExtra);
70
+ ? await cb(args, extra)
71
+ : await cb(extra);
67
72
  // A returned MCP error result (`isError: true`) is a failed call even
68
73
  // though the callback resolved; record it as an error while returning the
69
74
  // original output to the caller untouched.
@@ -112,12 +117,15 @@ const installPrototypePatchOnce = () => {
112
117
  }
113
118
  const { config } = ctx;
114
119
  const originalHasInputSchema = toolConfig.inputSchema !== undefined;
120
+ const plan = planToolTelemetry(name, toolConfig.inputSchema, config);
121
+ const registeredHasInputSchema = plan.inputSchema !== undefined;
122
+ const description = plan.applyDescription(toolConfig.description);
115
123
  const instrumentedConfig = {
116
124
  ...toolConfig,
117
- description: appendTelemetryHint(toolConfig.description),
118
- inputSchema: decorateInputSchemaWithTelemetry(toolConfig.inputSchema, config),
125
+ ...(description !== undefined ? { description } : {}),
126
+ ...(registeredHasInputSchema ? { inputSchema: plan.inputSchema } : {}),
119
127
  };
120
- const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
128
+ const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, registeredHasInputSchema, plan.mode, ctx);
121
129
  return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
122
130
  };
123
131
  // PRIA and other older codebases still use the deprecated `server.tool(...)`
@@ -1,6 +1,6 @@
1
1
  import type { HeaderBag, McpClientInfo } from "./types.js";
2
2
  /** Mint a session id that carries the client identity from `initialize`. */
3
- export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo) => string;
3
+ export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessionSeed?: string) => string;
4
4
  /** Recover the client identity from an identity-bearing session id. */
5
5
  export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
6
6
  export type StatelessHttpSession = {
@@ -25,6 +25,7 @@ import { headerValue, isRecord } from "./utils.js";
25
25
  // });
26
26
  // await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
27
27
  const SESSION_ID_RE = /^mcp_([A-Za-z0-9.-]+)_v_([A-Za-z0-9.-]*)_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
28
+ const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
28
29
  const ANONYMOUS_NAME = "unknown";
29
30
  const slugPart = (value, fallback) => {
30
31
  const slug = String(value ?? "")
@@ -37,7 +38,11 @@ const slugPart = (value, fallback) => {
37
38
  /** Mint a session id that carries the client identity from `initialize`. */
38
39
  // Version falls back to an empty segment (`_v__`) so a client that never
39
40
  // reported a version stays distinguishable from one reporting literal "0".
40
- export const buildStatelessSessionId = (clientInfo) => `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${randomUUID()}`;
41
+ export const buildStatelessSessionId = (clientInfo, sessionSeed) => {
42
+ const seed = String(sessionSeed ?? "").trim();
43
+ const uuid = SESSION_SEED_RE.test(seed) ? seed.toLowerCase() : randomUUID();
44
+ return `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${uuid}`;
45
+ };
41
46
  /** Recover the client identity from an identity-bearing session id. */
42
47
  export const parseStatelessSessionClientInfo = (sessionId) => {
43
48
  const match = SESSION_ID_RE.exec(String(sessionId ?? ""));
@@ -64,7 +69,8 @@ const clientInfoFromInitialize = (message) => {
64
69
  export const resolveStatelessHttpSession = (input) => {
65
70
  const initialize = findInitializeMessage(input.body);
66
71
  if (initialize) {
67
- const sessionId = buildStatelessSessionId(clientInfoFromInitialize(initialize));
72
+ const clientInfo = clientInfoFromInitialize(initialize);
73
+ const sessionId = buildStatelessSessionId(clientInfo, headerValue(input.headers, "x-armature-session-seed") ?? undefined);
68
74
  return {
69
75
  sessionId,
70
76
  sessionIdGenerator: () => sessionId,
@@ -39,6 +39,14 @@ export type ActorIdResolverInput = {
39
39
  telemetry?: TelemetryArgs;
40
40
  };
41
41
  export type ActorIdResolver = (input: ActorIdResolverInput) => string | Promise<string>;
42
+ export type RedactFunction = (value: unknown) => unknown;
43
+ export type TelemetryFieldMap = {
44
+ /** @deprecated `user_turn` is no longer collected; this mapping is ignored. */
45
+ user_turn?: string;
46
+ user_intent?: string;
47
+ agent_thinking?: string;
48
+ user_frustration?: string;
49
+ };
42
50
  export type McpAnalyticsConfig = {
43
51
  armature?: {
44
52
  endpointUrl?: string;
@@ -49,16 +57,22 @@ export type McpAnalyticsConfig = {
49
57
  emit?: TelemetryEmitter;
50
58
  onError?: (error: unknown, batch: AnalyticsIngestBatch) => void;
51
59
  timeoutMs?: number;
60
+ captureTelemetry?: boolean;
61
+ redact?: RedactFunction;
62
+ telemetryFieldMap?: TelemetryFieldMap;
52
63
  };
53
64
  };
65
+ export type TelemetryMode = "injected" | "owned" | "scrub";
54
66
  export type InternalMcpAnalyticsConfig = McpAnalyticsConfig & {
67
+ /** @deprecated Required-per-call intent conflicts with sparse intent declarations and is ignored. */
55
68
  telemetry?: {
56
69
  user_intent?: "required" | "optional";
57
- /** @deprecated Pre-V1 spelling of `user_intent`; still honored. */
70
+ /** @deprecated Pre-V1 spelling retained for source compatibility; ignored. */
58
71
  intent?: "required" | "optional";
59
72
  };
60
73
  };
61
74
  export type TelemetryArgs = {
75
+ /** @deprecated `user_turn` is accepted from cached clients but ignored. */
62
76
  user_turn?: number;
63
77
  user_intent?: string;
64
78
  agent_thinking?: string;
@@ -125,6 +139,7 @@ export type InstrumentToolCallEvent = {
125
139
  requestId?: string;
126
140
  clientInfo?: McpClientInfo;
127
141
  workflowRunId?: string;
142
+ telemetryMode?: TelemetryMode;
128
143
  };
129
144
  export type ToolCallHandler<T> = (args: unknown) => T | Promise<T>;
130
145
  export type ToolHandlerContext = {
@@ -151,7 +166,7 @@ export type McpServerInfo = {
151
166
  };
152
167
  export type AnalyticsRecorder = {
153
168
  decorateDefinitions: (defs: ToolDefinition[]) => ToolDefinition[];
154
- extractTelemetry: (args: unknown) => ExtractedToolArguments;
169
+ extractTelemetry: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;
155
170
  recordToolCall: (event: RecordToolCallEvent) => Promise<void>;
156
171
  recordSessionInit: (event: RecordSessionInitEvent) => Promise<void>;
157
172
  instrumentToolCall: <T>(event: InstrumentToolCallEvent, handler: ToolCallHandler<T>) => Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.16",
3
+ "version": "0.6.18",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",
@@ -61,6 +61,8 @@
61
61
  "demo": "tsx experimental/mock-env/demo-client.ts",
62
62
  "demo:instrumented": "tsx experimental/mock-env/instrumented-demo-client.ts",
63
63
  "test": "tsx --test tests/*.test.ts",
64
+ "test:artifact-canary": "npm run build && node scripts/run-publish-canary.mjs",
65
+ "test:platform-canary": "node scripts/run-publish-canary.mjs --require-platform",
64
66
  "typecheck": "tsc --noEmit",
65
67
  "typecheck:all": "tsc --noEmit -p tsconfig.test.json",
66
68
  "check": "npm run typecheck:all && npm test",