agentrail-node 0.2.0 → 0.3.1

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/README.md CHANGED
@@ -1,155 +1,179 @@
1
1
  # agentrail-node
2
2
 
3
- Node 22+ backend evidence for Agentrail: HTTP and fetch traces, application-verified identity, explicit journey milestones and structured logs. Uses OpenTelemetry's HTTP/protobuf exporters. The receiver must support `/ingest/otlp/v1/traces` and `/ingest/otlp/v1/logs` before installing this package.
3
+ [![npm](https://img.shields.io/npm/v/agentrail-node)](https://www.npmjs.com/package/agentrail-node)
4
+ [![Node](https://img.shields.io/node/v/agentrail-node)](https://www.npmjs.com/package/agentrail-node)
5
+ [![License](https://img.shields.io/github/license/agentrail-co/agentrail-js)](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE)
6
+
7
+ The Agentrail SDK for Node servers. It records what happens on your server
8
+ when an agent or a person reaches it: the requests it answers and the HTTP and
9
+ `fetch` calls it makes, the identity your application verified, the milestones
10
+ you name, your logs and your MCP tool calls. [Agentrail](https://www.agentrail.co)
11
+ links these steps with the ones your edge and pages record, into one journey.
12
+
13
+ What leaves your process is each step's facts: a request's method, route,
14
+ status, user agent and URL (its query dropped, but for Agentrail's own
15
+ markers); an MCP call's method, tool or prompt name, resource URI (without its
16
+ userinfo, query or fragment), the client's self-reported name and version,
17
+ message sizes, JSON-RPC id and error code, and, for a call that came over
18
+ HTTP, the names of the request's headers with its `Accept` and
19
+ `Accept-Encoding`; and identities only as keyed hashes. Request and response
20
+ bodies, the values of other headers and raw identities never leave it.
21
+ MCP tool arguments and results are not exported unless you turn on
22
+ `capturePayloads`, and then only as your `redact` hook returns them. The same
23
+ features are in the
24
+ [Go](https://github.com/agentrail-co/agentrail-go) and
25
+ [Python](https://github.com/agentrail-co/agentrail-python) SDKs.
26
+
27
+ ## Install
28
+
29
+ Node 22 or later.
30
+
31
+ ```sh
32
+ npm install agentrail-node
33
+ ```
34
+
35
+ In Agentrail, open **Journeys → Set up** and choose **Your servers**. Agentrail
36
+ shows the **Secret** and the **Hash key** once: keep them in your server's
37
+ secrets as `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY`, never in a page.
4
38
 
5
- ## Standalone startup
39
+ ## Quick start
40
+
41
+ Start Agentrail before your application's HTTP modules load:
6
42
 
7
43
  ```ts
8
- // instrumentation.ts — load before application HTTP modules
44
+ // instrumentation.ts
9
45
  import { init } from 'agentrail-node';
10
46
 
47
+ const secret = process.env.AGENTRAIL_SECRET;
48
+ const hashKey = process.env.AGENTRAIL_HASH_KEY;
49
+ if (!secret || !hashKey) throw new Error('Agentrail is not configured');
50
+
11
51
  export const agentrail = await init({
12
- collector: {
13
- endpoint: 'https://api.example.com/ingest/otlp',
14
- secret: process.env.AGENTRAIL_SOURCE_SECRET!, // a Node source
15
- },
16
- hashKey: process.env.AGENTRAIL_HASH_KEY!,
52
+ collector: { endpoint: 'https://<collector>/ingest/otlp', secret },
53
+ hashKey,
17
54
  serviceName: 'orders-api',
18
- outboundOrigins: ['https://inventory.internal'],
19
- onError(error) {
20
- console.error(error);
21
- },
55
+ outboundOrigins: ['https://inventory.example.com'], // your own services
22
56
  });
23
57
  ```
24
58
 
25
- The application validates its environment before initialization. Source credentials and the workspace hash key stay on the server. Never put them in a page. Start with `node --import ./instrumentation.js app.js`. `init` installs one tracer provider, logger provider, async context manager and HTTP/fetch instrumentation. Calling it again with the same options object returns the same client. It refuses an existing provider/context/propagator; use construction-time integration below. Shutdown is terminal for this installation.
26
-
27
- A valid edge handoff continues its trace. Direct public calls and refused handoffs start fresh traces; a caller's trace is a directional link only. The HMAC binds method, exact forwarded path/query, parent, workspace key ID and a 60-second issue time. Keep clocks synchronized. Configure edge path/query rewrites with its `prepareOriginRequest` hook before signing. Arbitrary baggage and trace state do not leave managed requests. Only exact `outboundOrigins` receive signed context; the actual network destination determines admission, rather than an overridden Host header. Configure the same workspace key at each participating service. Exporter requests and this collector's incoming ingestion traffic are excluded.
59
+ ```sh
60
+ node --import ./instrumentation.js app.js
61
+ ```
28
62
 
29
- ## Verified context and milestones
63
+ Every request your server answers is now recorded, with the calls it makes.
64
+ In a handler, once your application has authenticated the caller:
30
65
 
31
66
  ```ts
32
- // After authenticating the application request:
33
- agentrail.identify({
34
- kind: 'agent_registration',
35
- id: authenticatedAgent.id,
36
- actingUserId: authenticatedAgent.userId,
37
- });
67
+ agentrail.identify({ kind: 'user', id: user.id });
38
68
 
39
- const result = await agentrail.milestone(
69
+ const order = await agentrail.milestone(
40
70
  'checkout.confirm',
41
71
  { surface: 'custom', kind: 'checkout.confirm' },
42
72
  async () => confirmOrder(),
43
73
  );
44
74
  ```
45
75
 
46
- `identify` uses the active managed request, hashes IDs before export and never promotes generic OTel `user.id` or caller-declared attributes into verified identity. Outside a managed request it reports a capture error. Repeated identical assertions do nothing. A different assertion creates a distinct auth milestone while preserving the first principal. Concurrent requests have independent identity state. `milestone(name, context)` records an instant step; its callback overload scopes child spans, preserves the callback's result and rethrows its original error. Milestone names and kinds are bounded to 256 characters and should be stable operation names, without arguments or identifiers.
47
-
48
- ## Your own servers
49
-
50
- Calls your own services make to this one are not visitors or agents. Leave
51
- them out with `ignoreIncomingRequest`, and check something only your servers
52
- can send, such as a shared secret: a user agent or an address is what any
53
- caller can claim.
76
+ When the process stops, finish your requests, then send what is queued:
54
77
 
55
78
  ```ts
56
- const internalSecret = process.env.INTERNAL_SECRET;
57
- if (!internalSecret) throw new Error('INTERNAL_SECRET is not set');
58
-
59
- init({
60
- // ...
61
- ignoreIncomingRequest: (request) =>
62
- request.headers['x-my-internal'] === internalSecret,
79
+ process.on('SIGTERM', () => {
80
+ server.close(() => void agentrail.shutdown());
63
81
  });
64
82
  ```
65
83
 
66
- Check the secret is set before `init`. Unset, a request with no such header would match it, and every ordinary request would go unrecorded.
84
+ ## MCP servers
67
85
 
68
- ## Structured logs
86
+ `agentrail-node/mcp` records every JSON-RPC message your MCP server receives
87
+ (`initialize`, `tools/list`, `tools/call`, notifications, and requests the SDK
88
+ refuses) as one step, through public APIs only: nothing is patched.
69
89
 
70
90
  ```ts
71
- import pinoLogger from 'pino';
72
- import { pino } from 'agentrail-node/pino';
73
- const logger = pinoLogger({ hooks: pino(agentrail) });
74
- logger.error({ err: new TypeError('private detail') }, 'private detail');
75
-
76
- agentrail.log({
77
- severityNumber: 17,
78
- errorType: 'PaymentDeclined',
79
- eventName: 'checkout.failed',
80
- });
81
- ```
91
+ import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
92
+ import { mcp } from 'agentrail-node/mcp';
82
93
 
83
- The optional Pino 9/10 hook captures synchronously in the caller's async context and composes an existing hook as its second argument. The original logger output is unchanged. The standard OTel log processor is also available. Default exports contain severity, error type, event name, a stable per-record ID and exact span correlation. Arguments, results, headers, arbitrary attributes, exception messages and message bodies are excluded. Generic logs never create journey proof. Set `logs.uncorrelated: false` to exclude logs outside managed requests.
94
+ const capture = mcp({ client: agentrail });
84
95
 
85
- Message text requires an explicit field allowlist, for example `logs: { includeFields: ['msg'] }` for Pino or `['message']` for a standard OTel body. `client.log` selects from `fields`. Only selected top-level scalar fields are serialized, with a 4096-character body limit. Fields are considered in allowlist order. String values are shortened before serialization, including JSON escaping and complete Unicode code points; fields whose keys or scalar values cannot fit are omitted, so the exported object stays valid JSON. Do not select credentials, raw identities or sensitive customer content. Span names for supporting operations are neutralized, exception events and status messages are dropped, URLs retain only valid `h` markers; a sanitized URL over 4096 characters is omitted while the entry and its trace evidence are retained, and resource exports contain service/component/hash-key metadata. Service names/instance IDs, routes, operation names, user agents and explicitly selected fields are customer-controlled context: choose non-sensitive values.
96
+ // A handler from createMcpHandler: serve the wrapped one in its place.
97
+ export const handler = capture.handler(
98
+ createMcpHandler(() => {
99
+ const server = new McpServer({ name: 'orders', version: '1' });
100
+ server.registerTool(
101
+ 'find_order',
102
+ { inputSchema },
103
+ capture.tool('find_order', findOrder),
104
+ );
105
+ return server;
106
+ }),
107
+ );
86
108
 
87
- ## Existing OpenTelemetry provider
109
+ // A transport you own: connect the wrapped one.
110
+ await server.connect(capture.transport(transport));
111
+ ```
88
112
 
89
- Create the processors **before** constructing the customer's provider. A running provider cannot recover spans its sampler already dropped.
113
+ If you create the handler with a larger `maxRequestBodySize` than
114
+ `createMcpHandler`'s 4 MiB default, give the wrapper the same value, or bodies
115
+ past 4 MiB are served without a step:
116
+ `capture.handler(createMcpHandler(factory, { maxRequestBodySize }), { maxRequestBodySize })`.
117
+
118
+ Each call carries its method and name, the client's self-reported name,
119
+ version and protocol, the keyed hash of its `Mcp-Session-Id` (none for a
120
+ stateless server), the size of the request and response as JSON, and its
121
+ JSON-RPC error code or `isError` result.
122
+
123
+ A call that came over HTTP also carries what its HTTP request said of
124
+ itself: the method, the URL (its query dropped, but for Agentrail's own
125
+ markers), the user agent, `Accept` and `Accept-Encoding`, the names of its
126
+ headers (never a value), and the call's JSON-RPC id; through `capture.handler`,
127
+ the HTTP status of the answer too. Every message of a batch carries its
128
+ request's. A client's HTTP library writes its headers in an order and case of
129
+ its own, which say which client it is: where the SDK's HTTP instrumentation
130
+ saw the request (`init`, or `httpOptions` in your own setup), the names are
131
+ sent as Node received them; otherwise they come from the Fetch `Request`,
132
+ which lower-cases and sorts them. Names are sent as received, those a proxy
133
+ added too: Agentrail leaves those out. A call over stdio carries none of this.
134
+
135
+ `capture.tool`, `capture.resource`
136
+ and `capture.prompt` add the handler's own span inside the call, so a call is
137
+ counted once; on their own, without a wrapped transport, each is the step.
138
+ Inside a wrapped transport, a tool whose callback threw is a failed call: the
139
+ MCP server answers the throw with an `isError` result of its own, and the call
140
+ keeps `isError` but carries the thrown error's type, where a result your tool
141
+ returned with `isError` is a failed result (`tool_error`).
142
+
143
+ Payloads are off by default. To send them, redact first; returning `null`
144
+ sends neither:
90
145
 
91
146
  ```ts
92
- import { createProcessors } from 'agentrail-node';
93
- import {
94
- TracerProvider,
95
- ParentBasedSampler,
96
- TraceIdRatioBasedSampler,
97
- } from '@opentelemetry/sdk-trace';
98
- import { LoggerProvider } from '@opentelemetry/sdk-logs';
99
- import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
100
- import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
101
-
102
- const capture = createProcessors({
103
- ...options,
104
- propagator: customerPropagator,
105
- });
106
- const provider = new TracerProvider({
107
- sampler: capture.sampler(
108
- new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.1) }),
109
- ),
110
- spanProcessors: [customerProcessor, capture.spanProcessor],
111
- });
112
- const logProvider = new LoggerProvider({
113
- processors: [customerLogProcessor, capture.logProcessor],
147
+ const capture = mcp({
148
+ client: agentrail,
149
+ capturePayloads: {
150
+ redact: ({ method, name, request, response }) =>
151
+ name === 'find_order'
152
+ ? { request, response: redactOrder(response) }
153
+ : null,
154
+ },
114
155
  });
115
- // In the existing startup, register provider/logProvider, its async context manager,
116
- // capture.propagator and these request-aware hooks once:
117
- const http = new HttpInstrumentation(capture.httpOptions);
118
- const fetch = new UndiciInstrumentation(capture.undiciOptions);
119
- http.setTracerProvider(provider);
120
- fetch.setTracerProvider(provider);
121
156
  ```
122
157
 
123
- Pass the existing `TextMapPropagator` as `options.propagator`, then register the **returned** `capture.propagator` once. It delegates extraction/injection for unmanaged work and prevents a late customer injection from re-adding headers to managed fetches. Keeping the original propagator globally bypasses this boundary: Undici injects after its request hook. For multiple installations, chain the earlier installation's returned propagator as the next one's base. Request-aware hooks still bind the actual destination/method/target before signing.
124
-
125
- Retain other customer instrumentation; install only one HTTP and one Undici instrumentation, passing these options to them. Keep the request-aware propagator and HTTP hooks together: extraction alone cannot verify method and path. The factory registers no globals and never changes another exporter's input. The sampler promotes dropped managed spans to **record-only**, preserving the customer's sampled flag. Standard sampled-only exporters retain their sampling; custom exporters that export record-only spans may see additional records. Without this sampler wrapper, dropped entries report `entry_not_recording`, and their ancestry is unavailable. Ordinary spans outside managed requests are not captured by the Agentrail span processor.
126
-
127
- For Sentry, compose this sampler around `SentrySampler` while constructing the single customer-owned provider, retaining `SentrySpanProcessor` and its context manager, with `new SentryPropagator()` passed as the base and the returned capture propagator registered globally. A 100% Sentry sample rate still drops HEAD/OPTIONS; merely adding a processor cannot retain those spans. Agentrail's packed installation gate exercises this public composition. In framework admission mode, use the supplied request-aware incoming hook/propagator in the admitted scope and disable automatic incoming instrumentation, so there is one backend entry per request. Handler work after admission is captured; earlier authentication/body parsing is outside that scope.
158
+ A payload is sent as JSON text with no length limit of its own, except that a
159
+ call's two payloads together are cut to 14 MiB of UTF-8 (the longer first, on a
160
+ character boundary, and flagged as truncated), so one call always fits an
161
+ export. At most 64 MiB of payload text waits to be sent: past that, calls go
162
+ without their payloads and `onError` is told (`payload_budget`), as it is when
163
+ `redact` throws or returns what JSON cannot hold (`payload_redact_failed`).
128
164
 
129
- Pinned compatible OTel family: API 1.9.1, core/trace/resources/context 2.10.0, logs/exporters/HTTP instrumentation 0.221.0, Undici instrumentation 0.31.0. This release supports those APIs; check dependency compatibility when composing a distribution.
165
+ ## Documentation
130
166
 
131
- ## Delivery and shutdown
167
+ | Topic | Guide |
168
+ | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
169
+ | Install, identity, milestones, logs (Pino), MCP, location | [Install the Node SDK](https://www.agentrail.co/docs/guides/journeys-node) |
170
+ | Every option, an existing OpenTelemetry setup (Sentry too), delivery and errors, the MCP and Pino adapters in full | [Node SDK reference](https://www.agentrail.co/docs/guides/journeys-node-reference) |
171
+ | Keeping your own services' calls out | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) |
172
+ | What is sent, and what never is | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) |
173
+ | Workflow attempts and plugin calls | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) |
132
174
 
133
- Defaults per signal: 2048 records including the in-flight batch, batches of 128, a 1000 ms schedule, 5000 ms export timeout, and 10000 ms flush/shutdown deadlines. Override with `queue`. Positive integer limits are required, batch size cannot exceed capacity and flush/shutdown deadlines cannot be shorter than the export timeout. One batch is in flight per signal. The official exporter retries retryable OTLP responses within its export deadline; permanent rejections and exhausted retries are reported and dropped. This is a bounded memory queue, without disk persistence.
134
-
135
- `await agentrail.flush()` drains capture within the configured bound. `await agentrail.shutdown()` stops instrumentation and drains once; call it during application shutdown. `diagnostics()` reports accepted, exported, dropped and pending records per signal. Overflow, export failure, deadline loss, refused handoff and missing capture context go to `onError` (console by default). SDK error reporting runs outside capture, including when routed through the same Pino or OTel logger, so diagnostics cannot feed their own full queue. If a synchronous `onError` callback throws, its exception and the original capture error are reported to the console outside capture, and queue cleanup continues. These capture outcomes do not replace an application response. Flush completion means attempts ended; inspect diagnostics/errors for delivery loss.
136
-
137
- ## MCP callback adapter
138
-
139
- ```ts
140
- import { McpServer, type ToolCallback } from '@modelcontextprotocol/server';
141
- import { mcp } from 'agentrail-node/mcp';
142
- const server = new McpServer({ name: 'orders', version: '1' });
143
- const capture = mcp({ client: agentrail });
144
- const checkout: ToolCallback = async (ctx) => {
145
- // Authentication happens in the application's HTTP/auth boundary.
146
- return { content: [{ type: 'text', text: 'done' }] };
147
- };
148
- server.registerTool('checkout', {}, capture.tool('checkout', checkout));
149
- // capture.resource(registeredName, handler) and capture.prompt(registeredName, handler)
150
- // wrap their respective public registration callbacks too.
151
- ```
175
+ Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
152
176
 
153
- The optional adapter targets `@modelcontextprotocol/server` 2.3.1 and public registration callbacks, without modifying private handlers or transports. Use a callback typed with the SDK's schema, for example `ToolCallback<typeof inputSchema>`, for typed tool arguments. With HTTP capture installed, each execution becomes a nested MCP step with a distinct span, exact log correlation and inherited application-verified identity. Outside an HTTP request, it starts its own managed operation. It captures the registered operation name, method, client name/version, protocol and error outcome; arguments, result text, resource URIs and prompt content stay off. Pass a stable registered resource name rather than the caller's URI.
177
+ ## Licence
154
178
 
155
- MCP 2026-07-28 metadata comes from the request's public context envelope. Legacy 2025-11-25 HTTP calls retain protocol metadata; a stateless server may have no client name after its discarded initialize request. The adapter keeps no initialize cache across callers. Client info and supplied trace metadata remain untrusted and cannot assert a principal. `isError` results mark the operation as failed while preserving the original result. Thrown application errors retain their original identity. Tests exercise modern tool/resource/prompt requests and the official client's legacy HTTP exchange; other MCP SDK versions/transports have not been verified in this release.
179
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE).
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type MilestoneContext, type VerifiedIdentity } from './options.js';
2
2
  import { type StructuredLog } from './privacy.js';
3
3
  import type { processors } from './processors.js';
4
- import type { Runtime } from './runtime.js';
4
+ import { type Runtime } from './runtime.js';
5
5
  export interface AgentrailNode {
6
6
  identify(identity: VerifiedIdentity): void;
7
7
  milestone(name: string, details: MilestoneContext): void;
package/dist/client.js CHANGED
@@ -2,6 +2,8 @@ import { isCaptureSuppressed } from './suppression.js';
2
2
  import { context, ROOT_CONTEXT, trace, SpanStatusCode, } from '@opentelemetry/api';
3
3
  import { CaptureError, ConfigurationError, } from './options.js';
4
4
  import { makeLog } from './privacy.js';
5
+ import { performanceAttributes } from './performance.js';
6
+ import { registerInternal } from './runtime.js';
5
7
  export function createClient(runtime, queues) {
6
8
  function parent() {
7
9
  const active = context.active();
@@ -10,7 +12,7 @@ export function createClient(runtime, queues) {
10
12
  const external = trace.getSpanContext(active);
11
13
  return ROOT_CONTEXT.setValue(runtime.stateKey, runtime.newState(false, external === undefined ? [] : [{ context: external }]));
12
14
  }
13
- function start(name, details, identity) {
15
+ function start(name, details, identity, extra = {}) {
14
16
  if (!name.isWellFormed() ||
15
17
  !details.kind.isWellFormed() ||
16
18
  name.includes('\u0000') ||
@@ -20,11 +22,25 @@ export function createClient(runtime, queues) {
20
22
  details.kind.length === 0 ||
21
23
  details.kind.length > 256)
22
24
  throw new ConfigurationError('Milestone name and kind must contain 1–256 characters.');
25
+ const { performance, ...metadata } = details;
26
+ let normalized;
27
+ if (performance !== undefined) {
28
+ try {
29
+ normalized = performanceAttributes(performance, runtime.options.input.hashKey);
30
+ }
31
+ catch (error) {
32
+ if (!(error instanceof ConfigurationError))
33
+ throw error;
34
+ runtime.options.report(new CaptureError('invalid_performance', 'context', 1, error));
35
+ }
36
+ }
23
37
  const base = parent();
24
38
  const marked = base.setValue(runtime.markKey, {
25
- ...details,
39
+ ...metadata,
40
+ ...(normalized === undefined ? {} : { performance: normalized }),
26
41
  name,
27
42
  ...(identity === undefined ? {} : { identity }),
43
+ ...extra,
28
44
  });
29
45
  const state = runtime.state(base);
30
46
  const span = trace.getTracer('agentrail-node').startSpan(name, {
@@ -55,7 +71,7 @@ export function createClient(runtime, queues) {
55
71
  }
56
72
  });
57
73
  }
58
- return {
74
+ const client = {
59
75
  identify(identity) {
60
76
  if (identity.id.length === 0 || identity.actingUserId === '')
61
77
  throw new ConfigurationError('Verified identity IDs cannot be empty.');
@@ -92,4 +108,9 @@ export function createClient(runtime, queues) {
92
108
  logs: queues.logs.diagnostics(),
93
109
  }),
94
110
  };
111
+ registerInternal(client, {
112
+ runtime,
113
+ start: (name, details, extra) => start(name, details, undefined, extra),
114
+ });
115
+ return client;
95
116
  }
package/dist/http.js CHANGED
@@ -104,7 +104,27 @@ export function httpCapture(runtime) {
104
104
  if (candidate.kind === 'candidate' || candidate.reason !== 'missing')
105
105
  runtime.options.report(new CaptureError('handoff_refused', 'context', 1));
106
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);
107
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
+ }
108
128
  return {};
109
129
  },
110
130
  startOutgoingSpanHook(request) {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type NodeOptions } from './options.js';
2
- export { CaptureError, ConfigurationError, type NodeOptions, type VerifiedIdentity, type MilestoneContext, type QueueOptions, } 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
3
  export type { AgentrailNode } from './client.js';
4
4
  export type { StructuredLog } from './privacy.js';
5
5
  export { init } from './init.js';
package/dist/init.js CHANGED
@@ -8,6 +8,7 @@ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
8
8
  import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
9
9
  import { createProcessors } from './index.js';
10
10
  import { ConfigurationError } from './options.js';
11
+ import { internalOf, registerInternal } from './runtime.js';
11
12
  let installed;
12
13
  /** Call before loading application HTTP modules. Use createProcessors when another OTel provider owns startup. */
13
14
  export function init(options) {
@@ -72,6 +73,8 @@ export function init(options) {
72
73
  return stopping;
73
74
  },
74
75
  };
76
+ // The MCP adapter finds the runtime through the client it is given.
77
+ registerInternal(client, internalOf(sdk.client));
75
78
  installed = { options, client };
76
79
  return Promise.resolve(client);
77
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 CHANGED
@@ -1,10 +1,51 @@
1
+ import type { McpHandlerRequestOptions, Transport } from '@modelcontextprotocol/server';
1
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
+ }
2
23
  export interface McpCaptureOptions {
3
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;
4
30
  }
5
- /** Wrap the callbacks passed to public registerTool/registerResource/registerPrompt APIs. No transport is patched. */
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
+ */
6
40
  export declare function mcp(options: McpCaptureOptions): {
7
- tool: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
8
- resource: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
9
- prompt: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
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>;
10
51
  };