agentrail-node 0.0.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/http.js ADDED
@@ -0,0 +1,197 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { ClientRequest } from 'node:http';
3
+ import { ROOT_CONTEXT, trace } from '@opentelemetry/api';
4
+ import { encodeTraceHandoff, readTraceHandoff, TRACE_HANDOFF_HEADER, parseTraceparent, } from 'agentrail-core';
5
+ import { isCaptureSuppressed } from './suppression.js';
6
+ import { CaptureError } from './options.js';
7
+ const ownedHeaders = [
8
+ 'traceparent',
9
+ 'sentry-trace',
10
+ 'tracestate',
11
+ 'baggage',
12
+ TRACE_HANDOFF_HEADER,
13
+ ];
14
+ function single(value) {
15
+ return typeof value === 'string' ? value : null;
16
+ }
17
+ export function httpCapture(runtime) {
18
+ const requests = new WeakMap();
19
+ const ports = new WeakMap();
20
+ const collector = new URL(runtime.options.endpoint);
21
+ const base = runtime.options.input.propagator;
22
+ const propagator = {
23
+ // Undici injects AFTER requestHook. Managed propagation is already signed/filtered there.
24
+ inject(ctx, carrier, setter) {
25
+ if (runtime.state(ctx) !== undefined || isCaptureSuppressed(ctx))
26
+ return;
27
+ base?.inject(ctx, carrier, setter);
28
+ },
29
+ extract(ctx, carrier, getter) {
30
+ const incoming = typeof carrier === 'object' && carrier !== null
31
+ ? requests.get(carrier)
32
+ : undefined;
33
+ return incoming ?? base?.extract(ctx, carrier, getter) ?? ROOT_CONTEXT;
34
+ },
35
+ fields: () => [...new Set([...ownedHeaders, ...(base?.fields() ?? [])])],
36
+ };
37
+ function sign(span, method, target, origin) {
38
+ if (!runtime.spans.has(span) || !runtime.options.origins.has(origin))
39
+ return {};
40
+ const sc = span.spanContext();
41
+ const traceparent = `00-${sc.traceId}-${sc.spanId}-${sc.traceFlags.toString(16).padStart(2, '0')}`;
42
+ const encoded = encodeTraceHandoff({
43
+ traceparent,
44
+ hashKeyId: runtime.keyId,
45
+ issuedAt: Date.now(),
46
+ method,
47
+ target,
48
+ });
49
+ return {
50
+ traceparent,
51
+ [TRACE_HANDOFF_HEADER]: encoded.tokenPrefix +
52
+ createHmac('sha256', runtime.options.input.hashKey)
53
+ .update(encoded.bytes)
54
+ .digest('hex'),
55
+ };
56
+ }
57
+ const httpOptions = {
58
+ requireParentforOutgoingSpans: true,
59
+ ignoreIncomingRequestHook: (request) => (request.socket.localPort ===
60
+ Number(collector.port || (collector.protocol === 'https:' ? 443 : 80)) &&
61
+ (request.url ?? '').startsWith(collector.pathname)) ||
62
+ (runtime.options.input.ignoreIncomingRequest?.(request) ?? false),
63
+ ignoreOutgoingRequestHook: (request) => (request.hostname ?? request.host) === collector.hostname &&
64
+ Number(request.port ?? (request.protocol === 'https:' ? 443 : 80)) ===
65
+ Number(collector.port || (collector.protocol === 'https:' ? 443 : 80)) &&
66
+ (request.path ?? '').startsWith(collector.pathname),
67
+ startIncomingSpanHook(request) {
68
+ const header = single(request.headers.traceparent);
69
+ const candidate = readTraceHandoff(single(request.headers[TRACE_HANDOFF_HEADER]), {
70
+ traceparent: header,
71
+ hashKeyId: runtime.keyId,
72
+ method: request.method ?? '',
73
+ target: request.url ?? '',
74
+ now: Date.now(),
75
+ });
76
+ let state;
77
+ let ctx = ROOT_CONTEXT;
78
+ if (candidate.kind === 'candidate' &&
79
+ timingSafeEqual(createHmac('sha256', runtime.options.input.hashKey)
80
+ .update(candidate.bytes)
81
+ .digest(), candidate.signature)) {
82
+ state = runtime.newState(true);
83
+ ctx = trace.setSpanContext(ctx, {
84
+ ...candidate.context,
85
+ traceFlags: Number.parseInt(candidate.traceparent.slice(-2), 16) & 1,
86
+ isRemote: true,
87
+ });
88
+ }
89
+ else {
90
+ const external = header === null ? null : parseTraceparent(header);
91
+ state = runtime.newState(false, external === null
92
+ ? []
93
+ : [
94
+ {
95
+ context: {
96
+ ...external,
97
+ traceFlags: header === null
98
+ ? 0
99
+ : Number.parseInt(header.slice(-2), 16) & 1,
100
+ isRemote: true,
101
+ },
102
+ },
103
+ ]);
104
+ if (candidate.kind === 'candidate' || candidate.reason !== 'missing')
105
+ runtime.options.report(new CaptureError('handoff_refused', 'context', 1));
106
+ }
107
+ // Names only (rawHeaders is name, value, name, value), kept for an MCP
108
+ // message this request carries: the order and case a client's HTTP
109
+ // library wrote say which library it is.
110
+ state.headerNames = request.rawHeaders.filter((_, index) => index % 2 === 0);
111
+ requests.set(request.headers, ctx.setValue(runtime.stateKey, state));
112
+ try {
113
+ const location = runtime.options.input.incomingLocation?.(request) ?? null;
114
+ state.location =
115
+ location === null
116
+ ? null
117
+ : {
118
+ country: location.country,
119
+ region: location.region,
120
+ city: location.city,
121
+ source: location.source,
122
+ };
123
+ }
124
+ catch (error) {
125
+ // Application-provided enrichment must not replace its HTTP response.
126
+ runtime.options.report(new CaptureError('location_failed', 'context', 1, error instanceof Error ? error : new Error(String(error))));
127
+ }
128
+ return {};
129
+ },
130
+ startOutgoingSpanHook(request) {
131
+ // The SDK span processor gets these before requestHook. Never trust Host for destination allowlisting.
132
+ return {
133
+ 'agentrail.network.port': Number(request.port ?? (request.protocol === 'https:' ? 443 : 80)),
134
+ };
135
+ },
136
+ requestHook(span, request) {
137
+ if (!(request instanceof ClientRequest)) {
138
+ if (!span.isRecording())
139
+ runtime.options.report(new CaptureError('entry_not_recording', 'traces', 1));
140
+ return;
141
+ }
142
+ const metadata = runtime.spans.get(span);
143
+ if (metadata === undefined)
144
+ return;
145
+ for (const header of ownedHeaders)
146
+ request.removeHeader(header);
147
+ const port = ports.get(span);
148
+ // Public ClientRequest.host is the actual connection hostname; its Host header may be overridden.
149
+ const hostname = request.host.includes(':') && !request.host.startsWith('[')
150
+ ? `[${request.host}]`
151
+ : request.host;
152
+ const origin = new URL(`${request.protocol}//${hostname}${port === undefined ? '' : `:${port}`}`).origin;
153
+ for (const [key, value] of Object.entries(sign(span, request.method, request.path, origin)))
154
+ request.setHeader(key, value);
155
+ },
156
+ };
157
+ const undiciOptions = {
158
+ requireParentforSpans: true,
159
+ ignoreRequestHook: (request) => request.origin === collector.origin &&
160
+ request.path.startsWith(collector.pathname),
161
+ requestHook(span, request) {
162
+ if (!runtime.spans.has(span))
163
+ return;
164
+ stripUndiciHeaders(request);
165
+ for (const [key, value] of Object.entries(sign(span, request.method, request.path, new URL(request.origin).origin)))
166
+ request.addHeader(key, value);
167
+ },
168
+ };
169
+ return {
170
+ propagator,
171
+ httpOptions,
172
+ undiciOptions,
173
+ rememberPort(span, value) {
174
+ if (typeof value === 'number')
175
+ ports.set(span, value);
176
+ },
177
+ };
178
+ }
179
+ function stripUndiciHeaders(request) {
180
+ if (typeof request.headers === 'string')
181
+ request.headers = request.headers
182
+ .split('\r\n')
183
+ .filter((line) => !ownedHeaders.includes(line.slice(0, line.indexOf(':')).toLowerCase()))
184
+ .join('\r\n');
185
+ else {
186
+ const headers = [];
187
+ for (let i = 0; i < request.headers.length; i += 2) {
188
+ const name = request.headers[i];
189
+ const value = request.headers[i + 1];
190
+ if (typeof name === 'string' &&
191
+ value !== undefined &&
192
+ !ownedHeaders.includes(name.toLowerCase()))
193
+ headers.push(name, value);
194
+ }
195
+ request.headers = headers;
196
+ }
197
+ }
@@ -0,0 +1,16 @@
1
+ import { type NodeOptions } from './options.js';
2
+ export { CaptureError, ConfigurationError, type NodeOptions, type VerifiedIdentity, type MilestoneContext, type PerformanceContext, type AuthorizedOperation, type PluginInvocation, type QueueOptions, } from './options.js';
3
+ export type { AgentrailNode } from './client.js';
4
+ export type { StructuredLog } from './privacy.js';
5
+ export { init } from './init.js';
6
+ /** Construct before the application's provider. This factory never registers globals. */
7
+ export declare function createProcessors(options: NodeOptions): {
8
+ client: import("./client.js").AgentrailNode;
9
+ spanProcessor: import("@opentelemetry/sdk-trace").SpanProcessor;
10
+ logProcessor: import("@opentelemetry/sdk-logs").LogRecordProcessor;
11
+ sampler: (base: import("@opentelemetry/sdk-trace").Sampler) => import("@opentelemetry/sdk-trace").Sampler;
12
+ propagator: import("@opentelemetry/api").TextMapPropagator<any>;
13
+ httpOptions: import("@opentelemetry/instrumentation-http").HttpInstrumentationConfig;
14
+ undiciOptions: import("@opentelemetry/instrumentation-undici").UndiciInstrumentationConfig<import("@opentelemetry/instrumentation-undici").UndiciRequest, import("@opentelemetry/instrumentation-undici").UndiciResponse>;
15
+ };
16
+ export type AgentrailProcessors = ReturnType<typeof createProcessors>;
package/dist/index.js ADDED
@@ -0,0 +1,27 @@
1
+ import { resolveOptions } from './options.js';
2
+ import { Runtime } from './runtime.js';
3
+ import { processors } from './processors.js';
4
+ import { createClient } from './client.js';
5
+ import { httpCapture } from './http.js';
6
+ export { CaptureError, ConfigurationError, } from './options.js';
7
+ export { init } from './init.js';
8
+ /** Construct before the application's provider. This factory never registers globals. */
9
+ export function createProcessors(options) {
10
+ const runtime = new Runtime(resolveOptions(options));
11
+ const queues = processors(runtime);
12
+ const http = httpCapture(runtime);
13
+ const underlying = queues.spanProcessor.onStart.bind(queues.spanProcessor);
14
+ queues.spanProcessor.onStart = (span, ctx) => {
15
+ underlying(span, ctx);
16
+ http.rememberPort(span, span.attributes['agentrail.network.port']);
17
+ };
18
+ return {
19
+ client: createClient(runtime, queues),
20
+ spanProcessor: queues.spanProcessor,
21
+ logProcessor: queues.logProcessor,
22
+ sampler: queues.sampler,
23
+ propagator: http.propagator,
24
+ httpOptions: http.httpOptions,
25
+ undiciOptions: http.undiciOptions,
26
+ };
27
+ }
package/dist/init.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { type NodeOptions } from './options.js';
2
+ import type { AgentrailNode } from './client.js';
3
+ /** Call before loading application HTTP modules. Use createProcessors when another OTel provider owns startup. */
4
+ export declare function init(options: NodeOptions): Promise<AgentrailNode>;
package/dist/init.js ADDED
@@ -0,0 +1,80 @@
1
+ import { createRequire, syncBuiltinESMExports } from 'node:module';
2
+ import { context, propagation, trace } from '@opentelemetry/api';
3
+ import { logs } from '@opentelemetry/api-logs';
4
+ import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
5
+ import { AlwaysOnSampler, TracerProvider } from '@opentelemetry/sdk-trace';
6
+ import { LoggerProvider } from '@opentelemetry/sdk-logs';
7
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
8
+ import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
9
+ import { createProcessors } from './index.js';
10
+ import { ConfigurationError } from './options.js';
11
+ import { internalOf, registerInternal } from './runtime.js';
12
+ let installed;
13
+ /** Call before loading application HTTP modules. Use createProcessors when another OTel provider owns startup. */
14
+ export function init(options) {
15
+ if (installed !== undefined) {
16
+ if (installed.options !== options)
17
+ throw new ConfigurationError('Agentrail is already initialized. Reuse the original options and client.');
18
+ return Promise.resolve(installed.client);
19
+ }
20
+ const sdk = createProcessors(options);
21
+ const provider = new TracerProvider({
22
+ sampler: sdk.sampler(new AlwaysOnSampler()),
23
+ spanProcessors: [sdk.spanProcessor],
24
+ });
25
+ if (!trace.setGlobalTracerProvider(provider)) {
26
+ void sdk.client.shutdown();
27
+ throw new ConfigurationError('A tracer provider is already installed. Wire createProcessors into its construction instead.');
28
+ }
29
+ const manager = new AsyncLocalStorageContextManager().enable();
30
+ if (!context.setGlobalContextManager(manager)) {
31
+ trace.disable();
32
+ manager.disable();
33
+ void provider.shutdown();
34
+ throw new ConfigurationError('An OTel context manager is already installed. Use createProcessors with the existing setup.');
35
+ }
36
+ if (!propagation.setGlobalPropagator(sdk.propagator)) {
37
+ trace.disable();
38
+ context.disable();
39
+ manager.disable();
40
+ void provider.shutdown();
41
+ throw new ConfigurationError('An OTel propagator is already installed. Use createProcessors with the existing setup.');
42
+ }
43
+ const logger = new LoggerProvider({ processors: [sdk.logProcessor] });
44
+ const ownLogs = logs.setGlobalLoggerProvider(logger) === logger;
45
+ if (!ownLogs) {
46
+ trace.disable();
47
+ context.disable();
48
+ propagation.disable();
49
+ manager.disable();
50
+ void provider.shutdown();
51
+ void logger.shutdown();
52
+ throw new ConfigurationError('A logger provider is already installed. Use createProcessors with the existing setup.');
53
+ }
54
+ const http = new HttpInstrumentation(sdk.httpOptions);
55
+ const undici = new UndiciInstrumentation(sdk.undiciOptions);
56
+ http.setTracerProvider(provider);
57
+ undici.setTracerProvider(provider);
58
+ // Load core modules through the supported instrumentation loader, then refresh Node's ESM bindings.
59
+ const require = createRequire(import.meta.url);
60
+ require('node:http');
61
+ require('node:https');
62
+ syncBuiltinESMExports();
63
+ let stopping;
64
+ const client = {
65
+ ...sdk.client,
66
+ shutdown() {
67
+ stopping ??= (async () => {
68
+ http.disable();
69
+ undici.disable();
70
+ await Promise.all([provider.shutdown(), logger.shutdown()]);
71
+ manager.disable();
72
+ })();
73
+ return stopping;
74
+ },
75
+ };
76
+ // The MCP adapter finds the runtime through the client it is given.
77
+ registerInternal(client, internalOf(sdk.client));
78
+ installed = { options, client };
79
+ return Promise.resolve(client);
80
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The collector's limits (`otlp.limits` in the contract); the contract
3
+ * package is never published, so they are kept here and
4
+ * `test/limits.test.ts` holds them to it.
5
+ */
6
+ /**
7
+ * A span batch closes before its estimated size passes this
8
+ * (`otlp.limits.exportBatchBytes`): the rest is headroom for the resource,
9
+ * the envelope and the estimate's error, under the 16 MiB a body may hold.
10
+ */
11
+ export declare const EXPORT_BATCH_BYTES: number;
12
+ /**
13
+ * The most MCP payload text one span carries, both payloads together, so the
14
+ * span alone fits one batch (`otlp.limits.mcpPayloadBytes`).
15
+ */
16
+ export declare const MCP_PAYLOAD_BYTES: number;
17
+ /** The most MCP payload text one span queue holds, in flight included. */
18
+ export declare const QUEUE_PAYLOAD_BYTES: number;
package/dist/limits.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The collector's limits (`otlp.limits` in the contract); the contract
3
+ * package is never published, so they are kept here and
4
+ * `test/limits.test.ts` holds them to it.
5
+ */
6
+ /**
7
+ * A span batch closes before its estimated size passes this
8
+ * (`otlp.limits.exportBatchBytes`): the rest is headroom for the resource,
9
+ * the envelope and the estimate's error, under the 16 MiB a body may hold.
10
+ */
11
+ export const EXPORT_BATCH_BYTES = 15 * 1024 * 1024;
12
+ /**
13
+ * The most MCP payload text one span carries, both payloads together, so the
14
+ * span alone fits one batch (`otlp.limits.mcpPayloadBytes`).
15
+ */
16
+ export const MCP_PAYLOAD_BYTES = 14 * 1024 * 1024;
17
+ /** The most MCP payload text one span queue holds, in flight included. */
18
+ export const QUEUE_PAYLOAD_BYTES = 64 * 1024 * 1024;
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { McpHandlerRequestOptions, Transport } from '@modelcontextprotocol/server';
2
+ import type { AgentrailNode } from './client.js';
3
+ /** One MCP call as the redact hook sees it, before anything leaves the process. */
4
+ export interface McpPayload {
5
+ readonly method: string;
6
+ /** The tool or prompt name, or the resource URI; null for other methods. */
7
+ readonly name: string | null;
8
+ /** The request's params, as received. */
9
+ readonly request: unknown;
10
+ /** The result, or the JSON-RPC error object. */
11
+ readonly response: unknown;
12
+ }
13
+ export interface McpPayloadCapture {
14
+ /**
15
+ * Returns what of the call may leave the process, sent as JSON text, or
16
+ * null to send neither. It runs for every call the transport captures.
17
+ */
18
+ redact(payload: McpPayload): {
19
+ readonly request: unknown;
20
+ readonly response: unknown;
21
+ } | null;
22
+ }
23
+ export interface McpCaptureOptions {
24
+ readonly client: AgentrailNode;
25
+ /**
26
+ * Off unless set: request params and results then leave the process as
27
+ * `redact` returns them, on transport spans only.
28
+ */
29
+ readonly capturePayloads?: McpPayloadCapture;
30
+ }
31
+ /**
32
+ * Captures MCP calls through public APIs only; no transport is patched.
33
+ *
34
+ * - `transport(t)` wraps a transport you own before `server.connect`: one
35
+ * step per JSON-RPC message the server receives.
36
+ * - `handler(h)` wraps what `createMcpHandler` returns, the same way.
37
+ * - `tool`, `resource` and `prompt` wrap the callbacks you register: inside a
38
+ * wrapped transport, each is the call's child span; alone, it is the step.
39
+ */
40
+ export declare function mcp(options: McpCaptureOptions): {
41
+ transport: <T extends Transport>(inner: T) => T;
42
+ handler: <H extends {
43
+ readonly fetch: (request: Request, options?: McpHandlerRequestOptions) => Promise<Response>;
44
+ }>(inner: H, handlerOptions?: {
45
+ /** The `maxRequestBodySize` the handler was created with; 4 MiB as createMcpHandler's default. */
46
+ readonly maxRequestBodySize?: number;
47
+ }) => H;
48
+ tool: <Args extends unknown[], Result>(name: string, callback: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
49
+ resource: <Args extends unknown[], Result>(name: string, callback: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
50
+ prompt: <Args extends unknown[], Result>(name: string, callback: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
51
+ };