agentrail-node 0.2.0 → 0.3.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/options.d.ts CHANGED
@@ -1,15 +1,45 @@
1
- import type { PrincipalKind, Surface } from 'agentrail-core';
1
+ import type { PrincipalKind, Surface, IpLocation } from 'agentrail-core';
2
2
  export interface VerifiedIdentity {
3
3
  readonly kind: PrincipalKind;
4
4
  /** An ID the application has already authenticated. Never supplied from a request claim alone. */
5
5
  readonly id: string;
6
6
  readonly actingUserId?: string;
7
7
  }
8
+ export interface AuthorizedOperation {
9
+ readonly namespaceId: string;
10
+ /** A business attempt ID the application has already authorized. Hashed locally; never exported. */
11
+ readonly instanceRef: string;
12
+ readonly role: 'start' | 'progress' | 'terminal';
13
+ }
14
+ export interface PluginInvocation {
15
+ readonly bindingId: string;
16
+ /** An opaque invocation ID, never tool arguments or a user identifier. */
17
+ readonly invocationId: string;
18
+ }
19
+ export type PerformanceContext = {
20
+ readonly environment: 'production' | 'test';
21
+ } & ({
22
+ readonly operation: AuthorizedOperation;
23
+ readonly eventName: string;
24
+ readonly plugin?: PluginInvocation;
25
+ } | {
26
+ readonly operation: AuthorizedOperation;
27
+ readonly eventName?: string;
28
+ readonly plugin: PluginInvocation;
29
+ } | {
30
+ readonly operation?: never;
31
+ readonly eventName?: never;
32
+ readonly plugin: PluginInvocation;
33
+ });
8
34
  export interface MilestoneContext {
35
+ /** Explicit evidence supplied after application authorization; never inferred from tool inputs or results. */
36
+ readonly performance?: PerformanceContext;
9
37
  readonly surface: Surface;
10
38
  readonly kind: string;
11
39
  readonly mcp?: {
12
40
  readonly method: string;
41
+ /** The tool, resource or prompt's registered name, never a value from its arguments. */
42
+ readonly name?: string;
13
43
  readonly client?: string;
14
44
  readonly clientVersion?: string;
15
45
  readonly protocol?: string;
@@ -36,6 +66,8 @@ export interface NodeOptions {
36
66
  /** Exact http(s) origins permitted to receive signed trace context. Defaults to none. */
37
67
  readonly outboundOrigins?: readonly string[];
38
68
  readonly ignoreIncomingRequest?: (request: import('node:http').IncomingMessage) => boolean;
69
+ /** Use trusted platform metadata or a preloaded local database; never the exporter connection's IP. */
70
+ readonly incomingLocation?: (request: import('node:http').IncomingMessage) => Omit<IpLocation, 'observedAt'> | null;
39
71
  readonly logs?: {
40
72
  readonly includeFields?: readonly string[];
41
73
  readonly uncorrelated?: boolean;
@@ -43,7 +75,11 @@ export interface NodeOptions {
43
75
  readonly queue?: Partial<QueueOptions>;
44
76
  readonly onError?: (error: CaptureError) => void;
45
77
  }
46
- export type CaptureCode = 'queue_full' | 'export_failed' | 'deadline' | 'closed' | 'handoff_refused' | 'entry_not_recording' | 'identity_outside_request';
78
+ export type CaptureCode = 'queue_full' | 'export_failed' | 'deadline' | 'closed' | 'handoff_refused' | 'entry_not_recording' | 'location_failed' | 'identity_outside_request' | 'invalid_performance'
79
+ /** MCP payloads past the queue's payload memory budget: the span went without them. */
80
+ | 'payload_budget'
81
+ /** The application's MCP payload redact hook threw: the span went without payloads. */
82
+ | 'payload_redact_failed';
47
83
  export declare class CaptureError extends Error {
48
84
  readonly code: CaptureCode;
49
85
  readonly signal: 'traces' | 'logs' | 'context';
@@ -0,0 +1,4 @@
1
+ import type { Attributes } from '@opentelemetry/api';
2
+ import { type PerformanceContext } from './options.js';
3
+ /** Only normalized, allowlisted evidence enters the span context. */
4
+ export declare function performanceAttributes(input: PerformanceContext, hashKey: string): Attributes;
@@ -0,0 +1,37 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { ConfigurationError } from './options.js';
3
+ // Matches the collector's UUID contract, including version and variant.
4
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
5
+ /** Only normalized, allowlisted evidence enters the span context. */
6
+ export function performanceAttributes(input, hashKey) {
7
+ const attributes = { 'agentrail.environment': input.environment };
8
+ if (input.plugin !== undefined) {
9
+ if (!uuid.test(input.plugin.bindingId) ||
10
+ input.plugin.invocationId.length === 0 ||
11
+ input.plugin.invocationId.length > 256 ||
12
+ !input.plugin.invocationId.isWellFormed() ||
13
+ input.plugin.invocationId.includes('\u0000'))
14
+ throw new ConfigurationError('Use a canonical binding ID and an opaque invocation ID of 1–256 characters.');
15
+ attributes['agentrail.plugin.binding_id'] = input.plugin.bindingId;
16
+ attributes['agentrail.plugin.invocation_id'] = input.plugin.invocationId;
17
+ }
18
+ if (input.operation !== undefined) {
19
+ const { namespaceId, instanceRef, role } = input.operation;
20
+ if (!uuid.test(namespaceId) ||
21
+ instanceRef.length === 0 ||
22
+ !instanceRef.isWellFormed())
23
+ throw new ConfigurationError('Use a canonical namespace ID and a nonempty, well-formed authorized operation reference.');
24
+ attributes['agentrail.operation.namespace_id'] = namespaceId;
25
+ attributes['agentrail.operation.hash'] = createHmac('sha256', hashKey)
26
+ .update(JSON.stringify(['agentrail.operation', namespaceId, instanceRef]))
27
+ .digest('hex');
28
+ attributes['agentrail.workflow.role'] = role;
29
+ if (input.eventName !== undefined) {
30
+ if (input.eventName.length > 120 ||
31
+ !/^[a-zA-Z][a-zA-Z0-9_.:-]*$/u.test(input.eventName))
32
+ throw new ConfigurationError('Use a business event name of 1–120 letters, digits, dots, underscores, colons or hyphens, starting with a letter.');
33
+ attributes['agentrail.workflow.event_name'] = input.eventName;
34
+ }
35
+ }
36
+ return attributes;
37
+ }
package/dist/privacy.d.ts CHANGED
@@ -15,5 +15,14 @@ export declare function spanContextOnly(input: SpanContext): SpanContext;
15
15
  export declare function boundedText(input: string, limit: number): string;
16
16
  export declare function boundedText(input: unknown, limit: number): string | undefined;
17
17
  export declare function copySpan(span: ReadableSpan, runtime: Runtime): ReadableSpan | undefined;
18
+ /** The UTF-8 size of the MCP payload text an exported span holds. */
19
+ export declare function payloadBytes(span: ReadableSpan): number;
20
+ /** The exported span without its MCP payloads. */
21
+ export declare function withoutPayloads(span: ReadableSpan): ReadableSpan;
22
+ /**
23
+ * An upper estimate of an exported span's OTLP protobuf size: its text as
24
+ * UTF-8, and a generous allowance for each field's tag, length and value.
25
+ */
26
+ export declare function estimatedBytes(span: ReadableSpan): number;
18
27
  export declare function copyLog(record: ReadableLogRecord, runtime: Runtime): ReadableLogRecord | undefined;
19
28
  export declare function makeLog(input: StructuredLog, ctx: Context, runtime: Runtime): ReadableLogRecord | undefined;
package/dist/privacy.js CHANGED
@@ -67,21 +67,40 @@ export function copySpan(span, runtime) {
67
67
  const url = sanitizedUrl(original['url.full'] ?? original['http.url'] ?? incomingUrl);
68
68
  if (url !== undefined)
69
69
  attrs['url.full'] = url;
70
- const entry = metadata.mark !== undefined ||
71
- span.kind === SpanKind.SERVER ||
72
- span.kind === SpanKind.CONSUMER;
70
+ // An MCP handler inside its transport span is neither a step nor an entry:
71
+ // the transport span is the call.
72
+ const mark = metadata.mark?.step === false ? undefined : metadata.mark;
73
+ const step = mark !== undefined;
74
+ const entry = step || span.kind === SpanKind.SERVER || span.kind === SpanKind.CONSUMER;
73
75
  if (entry)
74
76
  Object.assign(attrs, metadata.mark?.identity ?? metadata.state.identity);
77
+ if (entry && metadata.state.location) {
78
+ const location = metadata.state.location;
79
+ for (const field of ['country', 'region', 'city', 'source']) {
80
+ const value = location[field];
81
+ if (value !== null)
82
+ attrs[`agentrail.client.location.${field}`] = boundedText(value, 128);
83
+ }
84
+ }
75
85
  if (span.kind === SpanKind.SERVER)
76
86
  attrs['agentrail.ingress.verified'] = metadata.state.verifiedIngress;
77
- if (metadata.mark !== undefined)
87
+ if (mark !== undefined)
78
88
  Object.assign(attrs, {
79
89
  'agentrail.step': true,
80
- 'agentrail.step.surface': metadata.mark.surface,
81
- 'agentrail.step.kind': metadata.mark.kind,
90
+ 'agentrail.step.surface': mark.surface,
91
+ 'agentrail.step.kind': mark.kind,
82
92
  });
93
+ if (metadata.mark?.performance !== undefined)
94
+ Object.assign(attrs, metadata.mark.performance);
83
95
  const mcp = metadata.mark?.mcp;
84
96
  if (mcp !== undefined) {
97
+ // The OpenTelemetry MCP server span's names. A resource is named only
98
+ // by its URI there, which can carry what was asked for, so it gets none.
99
+ attrs['mcp.method.name'] = boundedText(mcp.method, 128);
100
+ if (mcp.name !== undefined && mcp.method === 'tools/call')
101
+ attrs['gen_ai.tool.name'] = boundedText(mcp.name, 256);
102
+ if (mcp.name !== undefined && mcp.method === 'prompts/get')
103
+ attrs['gen_ai.prompt.name'] = boundedText(mcp.name, 256);
85
104
  if (mcp.client !== undefined)
86
105
  attrs['agentrail.mcp.client.name'] = boundedText(mcp.client, 128);
87
106
  if (mcp.clientVersion !== undefined)
@@ -89,6 +108,9 @@ export function copySpan(span, runtime) {
89
108
  if (mcp.protocol !== undefined)
90
109
  attrs['agentrail.mcp.protocol.version'] = boundedText(mcp.protocol, 64);
91
110
  }
111
+ const facts = metadata.mark?.mcpFacts;
112
+ if (facts !== undefined)
113
+ Object.assign(attrs, mcpAttributes(facts));
92
114
  const parent = span.parentSpanContext;
93
115
  return {
94
116
  name: boundedText(metadata.mark?.name ??
@@ -118,6 +140,95 @@ export function copySpan(span, runtime) {
118
140
  droppedLinksCount: 0,
119
141
  };
120
142
  }
143
+ /** A method the collector keeps; any other is named only in the span name. */
144
+ const MCP_METHOD = /^[A-Za-z0-9_./-]{1,128}$/u;
145
+ function mcpAttributes(facts) {
146
+ const attrs = { 'agentrail.mcp.layer': facts.layer };
147
+ const optional = {
148
+ 'agentrail.mcp.method': MCP_METHOD.test(facts.method)
149
+ ? facts.method
150
+ : undefined,
151
+ 'agentrail.mcp.session.id_hash': facts.sessionHash,
152
+ 'agentrail.mcp.request.bytes': facts.requestBytes,
153
+ 'agentrail.mcp.response.bytes': facts.responseBytes,
154
+ 'agentrail.mcp.jsonrpc.error_code': facts.errorCode,
155
+ 'agentrail.mcp.result.is_error': facts.isError,
156
+ // JSON text after the application's redact hook, never bounded by the
157
+ // 4,096-character cap: the capture truncates it only to fit one export.
158
+ 'agentrail.mcp.request.payload': facts.requestPayload,
159
+ 'agentrail.mcp.response.payload': facts.responsePayload,
160
+ 'agentrail.mcp.request.truncated': facts.requestTruncated,
161
+ 'agentrail.mcp.response.truncated': facts.responseTruncated,
162
+ };
163
+ for (const [key, value] of Object.entries(optional))
164
+ if (value !== undefined)
165
+ attrs[key] = value;
166
+ return { ...attrs, ...requestAttributes(facts) };
167
+ }
168
+ /**
169
+ * The request facts of a step whose message came by HTTP, as the contract's
170
+ * `mcpSpans.requestFacts` names them: the HTTP request's method, URL (its
171
+ * query cut to the marker lane, as on an HTTP span), user agent, header
172
+ * names, `Accept` and `Accept-Encoding`, the answer's status, and the
173
+ * message's JSON-RPC id. None over stdio.
174
+ */
175
+ function requestAttributes(facts) {
176
+ const { request } = facts;
177
+ if (request === undefined)
178
+ return {};
179
+ const optional = {
180
+ 'http.request.method': boundedText(request.method, 4096),
181
+ 'url.full': sanitizedUrl(request.url),
182
+ 'http.response.status_code': facts.httpStatus,
183
+ 'user_agent.original': boundedText(request.userAgent, 4096),
184
+ // Names only, never a value; already within their own bound.
185
+ 'agentrail.http.request.header_names': request.headerNames,
186
+ 'agentrail.http.request.accept': boundedText(request.accept, 4096),
187
+ 'agentrail.http.request.accept_encoding': boundedText(request.acceptEncoding, 4096),
188
+ 'agentrail.mcp.jsonrpc.id': boundedText(facts.jsonrpcId, 4096),
189
+ };
190
+ const attrs = {};
191
+ for (const [key, value] of Object.entries(optional))
192
+ if (value !== undefined)
193
+ attrs[key] = value;
194
+ return attrs;
195
+ }
196
+ const PAYLOAD_ATTRIBUTES = [
197
+ 'agentrail.mcp.request.payload',
198
+ 'agentrail.mcp.response.payload',
199
+ 'agentrail.mcp.request.truncated',
200
+ 'agentrail.mcp.response.truncated',
201
+ ];
202
+ /** The UTF-8 size of the MCP payload text an exported span holds. */
203
+ export function payloadBytes(span) {
204
+ let total = 0;
205
+ for (const key of PAYLOAD_ATTRIBUTES) {
206
+ const value = span.attributes[key];
207
+ if (typeof value === 'string')
208
+ total += Buffer.byteLength(value);
209
+ }
210
+ return total;
211
+ }
212
+ /** The exported span without its MCP payloads. */
213
+ export function withoutPayloads(span) {
214
+ const attributes = { ...span.attributes };
215
+ for (const key of PAYLOAD_ATTRIBUTES)
216
+ Reflect.deleteProperty(attributes, key);
217
+ return { ...span, attributes };
218
+ }
219
+ /**
220
+ * An upper estimate of an exported span's OTLP protobuf size: its text as
221
+ * UTF-8, and a generous allowance for each field's tag, length and value.
222
+ */
223
+ export function estimatedBytes(span) {
224
+ let total = 128 + Buffer.byteLength(span.name) + span.links.length * 64;
225
+ for (const [key, value] of Object.entries(span.attributes))
226
+ total +=
227
+ 16 +
228
+ Buffer.byteLength(key) +
229
+ (typeof value === 'string' ? Buffer.byteLength(value) : 16);
230
+ return total;
231
+ }
121
232
  /** Fit an already-sanitized string, including JSON escaping, without splitting a code point. */
122
233
  function fitLogText(value, budget) {
123
234
  const prefix = (length) => {
@@ -4,14 +4,14 @@ import { SamplingDecision } from '@opentelemetry/sdk-trace';
4
4
  import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
5
5
  import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';
6
6
  import { ExportQueue } from './queue.js';
7
- import { copyLog, copySpan } from './privacy.js';
7
+ import { copyLog, copySpan, estimatedBytes, payloadBytes, withoutPayloads, } from './privacy.js';
8
8
  export function processors(runtime) {
9
9
  const options = runtime.options;
10
10
  const config = {
11
11
  headers: { Authorization: `Bearer ${options.input.collector.secret}` },
12
12
  timeoutMillis: options.queue.exportTimeoutMs,
13
13
  };
14
- const spans = new ExportQueue('traces', new OTLPTraceExporter({ ...config, url: `${options.endpoint}/v1/traces` }), options);
14
+ const spans = new ExportQueue('traces', new OTLPTraceExporter({ ...config, url: `${options.endpoint}/v1/traces` }), options, { bytes: estimatedBytes, payloadBytes, withoutPayloads });
15
15
  const logs = new ExportQueue('logs', new OTLPLogExporter({ ...config, url: `${options.endpoint}/v1/logs` }), options);
16
16
  const spanProcessor = {
17
17
  onStart(span, parent) {
package/dist/queue.d.ts CHANGED
@@ -4,18 +4,34 @@ interface Exporter<T> {
4
4
  export(records: T[], callback: (result: ExportResult) => void): void;
5
5
  shutdown(): Promise<void>;
6
6
  }
7
+ /** How a queue weighs its records; a queue without one counts records only. */
8
+ export interface Sizing<T> {
9
+ /** An upper estimate of the record's encoded size. */
10
+ bytes(record: T): number;
11
+ /** The payload text it holds, against the queue's payload budget. */
12
+ payloadBytes(record: T): number;
13
+ withoutPayloads(record: T): T;
14
+ }
7
15
  export interface QueueStats {
8
16
  accepted: number;
9
17
  exported: number;
10
18
  dropped: number;
11
19
  pending: number;
12
20
  }
13
- /** One in-flight batch; its records still consume capacity. The vendor transport owns OTLP retry policy. */
21
+ /**
22
+ * One in-flight batch; its records still consume capacity. A batch closes at
23
+ * `batchSize` records or before its estimated size passes what one export
24
+ * carries. The vendor transport owns OTLP retry policy.
25
+ */
14
26
  export declare class ExportQueue<T> {
15
27
  private readonly signal;
16
28
  private readonly exporter;
17
29
  private readonly options;
30
+ private readonly sizing?;
18
31
  private records;
32
+ private queuedBytes;
33
+ /** Payload text queued or in flight. */
34
+ private payloadHeld;
19
35
  private active;
20
36
  private inFlight;
21
37
  private cancelActive;
@@ -23,11 +39,13 @@ export declare class ExportQueue<T> {
23
39
  private closed;
24
40
  private stop;
25
41
  private readonly stats;
26
- constructor(signal: 'traces' | 'logs', exporter: Exporter<T>, options: ResolvedOptions);
42
+ constructor(signal: 'traces' | 'logs', exporter: Exporter<T>, options: ResolvedOptions, sizing?: Sizing<T> | undefined);
27
43
  diagnostics(): QueueStats;
28
- add(record: T): void;
44
+ add(given: T): void;
29
45
  private drop;
30
46
  private exportBatch;
47
+ /** At least one record, so one estimated over the limit still goes, alone. */
48
+ private nextBatchLength;
31
49
  private drain;
32
50
  private bounded;
33
51
  flush(): Promise<void>;
package/dist/queue.js CHANGED
@@ -1,12 +1,21 @@
1
1
  import { ExportResultCode, suppressTracing } from '@opentelemetry/core';
2
2
  import { context } from '@opentelemetry/api';
3
3
  import { CaptureError } from './options.js';
4
- /** One in-flight batch; its records still consume capacity. The vendor transport owns OTLP retry policy. */
4
+ import { EXPORT_BATCH_BYTES, QUEUE_PAYLOAD_BYTES } from './limits.js';
5
+ /**
6
+ * One in-flight batch; its records still consume capacity. A batch closes at
7
+ * `batchSize` records or before its estimated size passes what one export
8
+ * carries. The vendor transport owns OTLP retry policy.
9
+ */
5
10
  export class ExportQueue {
6
11
  signal;
7
12
  exporter;
8
13
  options;
14
+ sizing;
9
15
  records = [];
16
+ queuedBytes = 0;
17
+ /** Payload text queued or in flight. */
18
+ payloadHeld = 0;
10
19
  active;
11
20
  inFlight = 0;
12
21
  cancelActive;
@@ -14,23 +23,41 @@ export class ExportQueue {
14
23
  closed = false;
15
24
  stop;
16
25
  stats = { accepted: 0, exported: 0, dropped: 0 };
17
- constructor(signal, exporter, options) {
26
+ constructor(signal, exporter, options, sizing) {
18
27
  this.signal = signal;
19
28
  this.exporter = exporter;
20
29
  this.options = options;
30
+ this.sizing = sizing;
21
31
  }
22
32
  diagnostics() {
23
33
  return { ...this.stats, pending: this.records.length + this.inFlight };
24
34
  }
25
- add(record) {
35
+ add(given) {
26
36
  if (this.closed ||
27
37
  this.records.length + this.inFlight >= this.options.queue.maxRecords) {
28
38
  this.drop(this.closed ? 'closed' : 'queue_full', 1);
29
39
  return;
30
40
  }
31
- this.records.push(record);
41
+ let record = given;
42
+ let payload = 0;
43
+ let bytes = 0;
44
+ const sizing = this.sizing;
45
+ if (sizing !== undefined) {
46
+ payload = sizing.payloadBytes(record);
47
+ if (payload > 0 && this.payloadHeld + payload > QUEUE_PAYLOAD_BYTES) {
48
+ // The span still goes; only its payloads are dropped.
49
+ record = sizing.withoutPayloads(record);
50
+ payload = 0;
51
+ this.options.report(new CaptureError('payload_budget', this.signal, 1));
52
+ }
53
+ bytes = sizing.bytes(record);
54
+ }
55
+ this.records.push({ record, bytes, payload });
56
+ this.queuedBytes += bytes;
57
+ this.payloadHeld += payload;
32
58
  this.stats.accepted++;
33
- if (this.records.length >= this.options.queue.batchSize)
59
+ if (this.records.length >= this.options.queue.batchSize ||
60
+ this.queuedBytes >= EXPORT_BATCH_BYTES)
34
61
  void this.drain();
35
62
  else if (this.timer === undefined) {
36
63
  this.timer = setTimeout(() => {
@@ -80,6 +107,19 @@ export class ExportQueue {
80
107
  });
81
108
  });
82
109
  }
110
+ /** At least one record, so one estimated over the limit still goes, alone. */
111
+ nextBatchLength() {
112
+ let count = 0;
113
+ let bytes = 0;
114
+ for (const entry of this.records) {
115
+ if (count === this.options.queue.batchSize ||
116
+ (count > 0 && bytes + entry.bytes > EXPORT_BATCH_BYTES))
117
+ break;
118
+ bytes += entry.bytes;
119
+ count++;
120
+ }
121
+ return count;
122
+ }
83
123
  drain() {
84
124
  if (this.active !== undefined)
85
125
  return this.active;
@@ -87,10 +127,14 @@ export class ExportQueue {
87
127
  this.timer = undefined;
88
128
  this.active = (async () => {
89
129
  while (this.records.length > 0) {
90
- const batch = this.records.splice(0, this.options.queue.batchSize);
130
+ const batch = this.records.splice(0, this.nextBatchLength());
91
131
  this.inFlight = batch.length;
92
- await this.exportBatch(batch);
132
+ for (const entry of batch)
133
+ this.queuedBytes -= entry.bytes;
134
+ await this.exportBatch(batch.map((entry) => entry.record));
93
135
  this.inFlight = 0;
136
+ for (const entry of batch)
137
+ this.payloadHeld -= entry.payload;
94
138
  }
95
139
  })().finally(() => {
96
140
  this.active = undefined;
@@ -108,7 +152,10 @@ export class ExportQueue {
108
152
  new Promise((resolve) => {
109
153
  timer = setTimeout(() => {
110
154
  const count = this.records.length;
155
+ for (const entry of this.records)
156
+ this.payloadHeld -= entry.payload;
111
157
  this.records = [];
158
+ this.queuedBytes = 0;
112
159
  if (count > 0)
113
160
  this.drop('deadline', count);
114
161
  this.cancelActive?.();
package/dist/runtime.d.ts CHANGED
@@ -1,16 +1,61 @@
1
1
  import type { Attributes, Context, Span } from '@opentelemetry/api';
2
- import type { MilestoneContext, ResolvedOptions, VerifiedIdentity } from './options.js';
2
+ import { type MilestoneContext, type ResolvedOptions, type VerifiedIdentity } from './options.js';
3
3
  export interface State {
4
+ location?: Omit<import('agentrail-core').IpLocation, 'observedAt'> | null;
4
5
  identity?: Attributes;
5
6
  readonly verifiedIngress: boolean;
6
7
  readonly links: import('@opentelemetry/api').Link[];
7
8
  readonly entry: {
8
9
  span?: Span;
9
10
  };
11
+ /**
12
+ * The names of the incoming request's headers in the order and the case
13
+ * they arrived (Node's `rawHeaders`), never a value; undefined where the
14
+ * HTTP instrumentation did not see the request.
15
+ */
16
+ headerNames?: readonly string[];
10
17
  }
11
- export interface Mark extends MilestoneContext {
18
+ /**
19
+ * What the HTTP request that carried an MCP message says of itself, as the
20
+ * contract's `mcpSpans.requestFacts` lists it. No header's value but these
21
+ * three, and the names of the rest.
22
+ */
23
+ export interface McpRequestFacts {
24
+ readonly method: string;
25
+ readonly url: string;
26
+ readonly userAgent?: string;
27
+ /** Comma-joined, as received; undefined for a request that holds none. */
28
+ readonly headerNames?: string;
29
+ readonly accept?: string;
30
+ readonly acceptEncoding?: string;
31
+ }
32
+ /** What the MCP capture learns of one call, filled until its span ends. */
33
+ export interface McpFacts {
34
+ readonly layer: 'transport' | 'handler';
35
+ readonly method: string;
36
+ /** Set only for a message that came by HTTP. */
37
+ request?: McpRequestFacts;
38
+ /** The message's JSON-RPC id as text; set only with `request`, and never for a notification. */
39
+ jsonrpcId?: string;
40
+ /** The status the HTTP answer carried, where the capture saw it before the call ended. */
41
+ httpStatus?: number;
42
+ sessionHash?: string;
43
+ requestBytes?: number;
44
+ responseBytes?: number;
45
+ errorCode?: number;
46
+ isError?: boolean;
47
+ requestPayload?: string;
48
+ responsePayload?: string;
49
+ requestTruncated?: boolean;
50
+ responseTruncated?: boolean;
51
+ }
52
+ export interface Mark extends Omit<MilestoneContext, 'performance'> {
53
+ readonly performance?: Attributes;
12
54
  readonly name: string;
13
55
  readonly identity?: Attributes;
56
+ /** False for a span that is not a step: an MCP handler inside its transport span. */
57
+ readonly step?: false;
58
+ readonly mcpFacts?: McpFacts;
14
59
  }
15
60
  export declare class Runtime {
16
61
  readonly options: ResolvedOptions;
@@ -26,5 +71,18 @@ export declare class Runtime {
26
71
  state(ctx: Context): State | undefined;
27
72
  mark(ctx: Context): Mark | undefined;
28
73
  newState(verifiedIngress?: boolean, links?: State['links']): State;
74
+ /** The keyed hash every principal and session ID is sent as: 32 lowercase hex. */
75
+ hash(id: string): string;
29
76
  identity(identity: VerifiedIdentity): Attributes;
30
77
  }
78
+ /** What the MCP adapter needs of a client, kept out of its public type. */
79
+ export interface Internal {
80
+ readonly runtime: Runtime;
81
+ /** Starts a marked span under the active context. */
82
+ start(name: string, details: MilestoneContext, extra?: Pick<Mark, 'step' | 'mcpFacts'>): {
83
+ span: Span;
84
+ ctx: Context;
85
+ };
86
+ }
87
+ export declare function registerInternal(client: object, internal: Internal): void;
88
+ export declare function internalOf(client: object): Internal;
package/dist/runtime.js CHANGED
@@ -2,6 +2,7 @@ import { createHash, createHmac, randomUUID } from 'node:crypto';
2
2
  import { createContextKey } from '@opentelemetry/api';
3
3
  import { resourceFromAttributes } from '@opentelemetry/resources';
4
4
  import { VERSION } from 'agentrail-core';
5
+ import { ConfigurationError, } from './options.js';
5
6
  export class Runtime {
6
7
  options;
7
8
  stateKey = createContextKey(`agentrail.state.${randomUUID()}`);
@@ -33,11 +34,15 @@ export class Runtime {
33
34
  newState(verifiedIngress = false, links = []) {
34
35
  return { verifiedIngress, links, entry: {} };
35
36
  }
36
- identity(identity) {
37
- const hash = (id) => createHmac('sha256', this.options.input.hashKey)
37
+ /** The keyed hash every principal and session ID is sent as: 32 lowercase hex. */
38
+ hash(id) {
39
+ return createHmac('sha256', this.options.input.hashKey)
38
40
  .update(id)
39
41
  .digest('hex')
40
42
  .slice(0, 32);
43
+ }
44
+ identity(identity) {
45
+ const hash = (id) => this.hash(id);
41
46
  return {
42
47
  'agentrail.identity.verified': true,
43
48
  'agentrail.principal.kind': identity.kind,
@@ -50,3 +55,13 @@ export class Runtime {
50
55
  };
51
56
  }
52
57
  }
58
+ const internals = new WeakMap();
59
+ export function registerInternal(client, internal) {
60
+ internals.set(client, internal);
61
+ }
62
+ export function internalOf(client) {
63
+ const internal = internals.get(client);
64
+ if (internal === undefined)
65
+ throw new ConfigurationError('Pass the client that init or createProcessors returned.');
66
+ return internal;
67
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentrail-node",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Backend HTTP traces, structured logs and MCP journey context for Agentrail.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -45,7 +45,8 @@
45
45
  "@opentelemetry/instrumentation": "0.221.0",
46
46
  "@opentelemetry/instrumentation-http": "0.221.0",
47
47
  "@opentelemetry/instrumentation-undici": "0.31.0",
48
- "agentrail-core": "0.2.0"
48
+ "eventsource-parser": "3.1.1",
49
+ "agentrail-core": "0.3.0"
49
50
  },
50
51
  "peerDependencies": {
51
52
  "pino": ">=9 <11",