dd-trace 5.137.0 → 5.138.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.
Files changed (69) hide show
  1. package/index.d.ts +56 -0
  2. package/initialize.mjs +5 -3
  3. package/package.json +9 -8
  4. package/packages/datadog-instrumentations/src/ai.js +88 -127
  5. package/packages/datadog-instrumentations/src/aws-lambda.js +9 -0
  6. package/packages/datadog-instrumentations/src/helpers/hooks.js +0 -1
  7. package/packages/datadog-instrumentations/src/helpers/instrument.js +1 -3
  8. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +4 -1
  9. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +2 -0
  10. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +5 -3
  11. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +26 -2
  12. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +3 -1
  13. package/packages/datadog-instrumentations/src/path-to-regexp.js +11 -11
  14. package/packages/datadog-instrumentations/src/router.js +17 -1
  15. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1 -1
  16. package/packages/datadog-plugin-aws-lambda/src/context/events.js +167 -0
  17. package/packages/datadog-plugin-aws-lambda/src/context/extractor.js +153 -0
  18. package/packages/datadog-plugin-aws-lambda/src/context/http.js +50 -0
  19. package/packages/datadog-plugin-aws-lambda/src/context/span-context.js +26 -0
  20. package/packages/datadog-plugin-aws-lambda/src/context/step-functions.js +142 -0
  21. package/packages/datadog-plugin-aws-lambda/src/context/types.d.ts +17 -0
  22. package/packages/datadog-plugin-aws-lambda/src/context/xray.js +67 -0
  23. package/packages/datadog-plugin-aws-lambda/src/index.js +52 -4
  24. package/packages/datadog-plugin-azure-functions/src/index.js +68 -12
  25. package/packages/datadog-plugin-fetch/src/index.js +7 -0
  26. package/packages/datadog-plugin-http/src/client.js +12 -0
  27. package/packages/datadog-plugin-http/src/server.js +18 -4
  28. package/packages/dd-trace/src/aiguard/client.js +7 -9
  29. package/packages/dd-trace/src/aiguard/evaluation.js +7 -2
  30. package/packages/dd-trace/src/aiguard/messages/utils.js +2 -2
  31. package/packages/dd-trace/src/aiguard/sdk.js +7 -2
  32. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +273 -167
  33. package/packages/dd-trace/src/appsec/channels.js +1 -0
  34. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +21 -14
  35. package/packages/dd-trace/src/appsec/index.js +3 -0
  36. package/packages/dd-trace/src/appsec/rasp/index.js +57 -3
  37. package/packages/dd-trace/src/appsec/rasp/utils.js +14 -0
  38. package/packages/dd-trace/src/carrier.js +7 -1
  39. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +4 -2
  40. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +31 -19
  41. package/packages/dd-trace/src/config/generated-config-types.d.ts +10 -3
  42. package/packages/dd-trace/src/config/index.js +28 -2
  43. package/packages/dd-trace/src/config/parsers.js +25 -0
  44. package/packages/dd-trace/src/config/supported-configurations.json +27 -7
  45. package/packages/dd-trace/src/datastreams/http.js +57 -0
  46. package/packages/dd-trace/src/datastreams/index.js +24 -0
  47. package/packages/dd-trace/src/datastreams/pathway.js +33 -4
  48. package/packages/dd-trace/src/datastreams/processor.js +22 -3
  49. package/packages/dd-trace/src/lambda/handler-paths.js +1 -1
  50. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  51. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +33 -1
  52. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +102 -1
  53. package/packages/dd-trace/src/llmobs/span_processor.js +3 -0
  54. package/packages/dd-trace/src/llmobs/tagger.js +9 -0
  55. package/packages/dd-trace/src/noop/span.js +0 -4
  56. package/packages/dd-trace/src/openfeature/flagging_provider.js +17 -0
  57. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +2 -1
  58. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +2 -1
  59. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +16 -1
  60. package/packages/dd-trace/src/opentelemetry/trace/index.js +5 -4
  61. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +10 -6
  62. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +42 -26
  63. package/packages/dd-trace/src/opentracing/propagation/text_map.js +4 -4
  64. package/packages/dd-trace/src/plugin_manager.js +2 -0
  65. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +3 -5
  66. package/packages/dd-trace/src/plugins/util/url.js +1 -1
  67. package/packages/dd-trace/src/register-loader.js +43 -0
  68. package/register.js +10 -44
  69. package/register.mjs +27 -0
package/index.d.ts CHANGED
@@ -1957,6 +1957,58 @@ declare namespace tracer {
1957
1957
  */
1958
1958
  arguments: string;
1959
1959
  };
1960
+ /**
1961
+ * Set when the tool call runs an MCP tool: references an entry of the `mcpServers` evaluate option.
1962
+ */
1963
+ mcp?: {
1964
+ /**
1965
+ * The `id` of the MCP server entry of the tool.
1966
+ */
1967
+ server_id: string;
1968
+ };
1969
+ }
1970
+
1971
+ /**
1972
+ * An MCP server referenced by the `mcp.server_id` of tool calls, sent in the `mcpServers` evaluate option.
1973
+ * The SDK sends these values to AI Guard and stores them on the AI Guard span as given, without redaction:
1974
+ * remove any credential before passing them.
1975
+ */
1976
+ export interface McpServer {
1977
+ /**
1978
+ * Server ID that the tool calls reference with `mcp.server_id`.
1979
+ */
1980
+ id: string;
1981
+ /**
1982
+ * Who runs the MCP client: `client` when the application runs it, `provider` when the model provider runs it.
1983
+ */
1984
+ managed_by: 'client' | 'provider';
1985
+ /**
1986
+ * Transport of the server.
1987
+ */
1988
+ transport: 'streamable_http' | 'sse' | 'stdio' | 'in_process' | 'unknown';
1989
+ /**
1990
+ * Configured name of the server.
1991
+ */
1992
+ name?: string;
1993
+ /**
1994
+ * Origin of the server URL: scheme, host and port only. Remove userinfo, path, query and fragment before
1995
+ * passing it: many MCP providers put the API key there.
1996
+ */
1997
+ url?: string;
1998
+ /**
1999
+ * Program name of a stdio server command. Pass the program name, not the full path, which can contain the
2000
+ * user name.
2001
+ */
2002
+ command?: string;
2003
+ /**
2004
+ * Package or module that a stdio server runs. Leave out other arguments, which can contain paths, tokens or
2005
+ * secrets.
2006
+ */
2007
+ args?: string[];
2008
+ /**
2009
+ * Original MCP tool name of each function name that the model uses.
2010
+ */
2011
+ tools: { [functionName: string]: string };
1960
2012
  }
1961
2013
 
1962
2014
  /**
@@ -2162,6 +2214,9 @@ declare namespace tracer {
2162
2214
  * `ai_guard` or starting with `ai_guard.` are reserved and ignored. Entries with an
2163
2215
  * empty key, a key longer than 200 characters, a string value longer than 25000
2164
2216
  * characters, or a value that is not a string, finite number or boolean are dropped.
2217
+ * - `mcpServers`: The MCP servers that the `mcp.server_id` of the tool calls reference. Sent with the
2218
+ * messages and reported on the AI Guard span; omitted when empty. The entries are sent
2219
+ * and stored as given and are not redacted: remove any credential from them first.
2165
2220
  * @returns Promise resolving to an Evaluation with the security decision and reasoning.
2166
2221
  * The promise rejects with AIGuardAbortError when `opts.block` is true and the evaluation result would block the request.
2167
2222
  * The promise rejects with AIGuardClientError when communication with the AI Guard service fails.
@@ -2171,6 +2226,7 @@ declare namespace tracer {
2171
2226
  opts?: {
2172
2227
  block?: boolean,
2173
2228
  tags?: { [key: string]: string | number | boolean },
2229
+ mcpServers?: McpServer[],
2174
2230
  }
2175
2231
  ): Promise<Evaluation>;
2176
2232
  }
package/initialize.mjs CHANGED
@@ -26,6 +26,7 @@ const brokenLoaders = NODE_VERSION.startsWith('18.0')
26
26
  const isNode20LoaderWorker = !isMainThread && NODE_VERSION.startsWith('20.0')
27
27
  const useDefaultLoader = brokenLoaders || isNode20LoaderWorker
28
28
  // Avoid CommonJS in the loader worker on Node 20.0: https://github.com/nodejs/node/issues/47566
29
+ // @ts-expect-error Node supports query strings in module specifiers.
29
30
  const loaderHook = useDefaultLoader ? undefined : await import('./loader-hook.mjs?initialize')
30
31
 
31
32
  let hasInsertedInit = false
@@ -43,7 +44,7 @@ export const globalPreload = isNode20LoaderWorker
43
44
  /**
44
45
  * @param {{ source?: string|Buffer|Uint8Array, format?: string }} result
45
46
  * @param {unknown} _url_
46
- * @param {{ format?: string, isMain?: boolean }} context
47
+ * @param {{ format?: string | null, isMain?: boolean }} context
47
48
  * @returns {{ source?: string|Buffer|Uint8Array, format?: string }}
48
49
  */
49
50
  function insertInit (result, _url_, context) {
@@ -103,7 +104,8 @@ if (isMainThread) {
103
104
  // Only register the loader hook when instrumentation initialized. On a bailout the
104
105
  // loader has nothing to instrument and can keep a short-lived process from exiting.
105
106
  // `registerHooks` alone keeps the gate open once Node.js drops `register` (nodejs/node#67090).
106
- if ((Module.registerHooks || Module.register) && initialized) {
107
- require('./register.js')
107
+ const hasSyncHooks = 'registerHooks' in Module && typeof Module.registerHooks === 'function'
108
+ if (initialized && (hasSyncHooks || typeof Module.register === 'function')) {
109
+ await import('./register.mjs')
108
110
  }
109
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dd-trace",
3
- "version": "5.137.0",
3
+ "version": "5.138.0",
4
4
  "description": "Datadog APM tracing client for JavaScript",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
@@ -186,6 +186,7 @@
186
186
  "packages/datadog-instrumentations/orchestrion.yml",
187
187
  "README.md",
188
188
  "register.js",
189
+ "register.mjs",
189
190
  "vendor/dist/**/*.d.ts",
190
191
  "vendor/dist/**/*.js",
191
192
  "vendor/dist/**/*.wasm",
@@ -216,7 +217,7 @@
216
217
  "@eslint/eslintrc": "^3.3.7",
217
218
  "@eslint/js": "^10.0.1",
218
219
  "@eslint/plugin-kit": "^0.7.3",
219
- "@datadog/openfeature-node-server": "2.7.0",
220
+ "@datadog/openfeature-node-server": "2.8.0",
220
221
  "@msgpack/msgpack": "^3.1.3",
221
222
  "@openfeature/core": "^1.12.0",
222
223
  "@openfeature/server-sdk": "~1.23.0",
@@ -224,22 +225,22 @@
224
225
  "@types/mocha": "^10.0.10",
225
226
  "@types/node": "^18.19.106",
226
227
  "@types/sinon": "^22.0.2",
227
- "@vercel/nft": "^1.11.1",
228
+ "@vercel/nft": "^1.11.7",
228
229
  "benchmark": "^2.1.4",
229
230
  "body-parser": "^2.4.0",
230
231
  "bun": "1.4.4",
231
232
  "c8": "^12.0.0",
232
233
  "codeowners-audit": "^2.9.0",
233
- "eslint": "^10.14.0",
234
- "eslint-plugin-cypress": "^7.0.4",
234
+ "eslint": "^10.15.0",
235
+ "eslint-plugin-cypress": "^7.0.5",
235
236
  "eslint-plugin-import-x": "^4.18.1",
236
- "eslint-plugin-jsdoc": "^65.4.5",
237
+ "eslint-plugin-jsdoc": "^65.4.12",
237
238
  "eslint-plugin-mocha": "^12.0.2",
238
239
  "eslint-plugin-n": "^18.5.0",
239
240
  "eslint-plugin-promise": "^7.3.0",
240
241
  "eslint-plugin-regexp": "^3.3.3",
241
242
  "eslint-plugin-sonarjs": "^4.2.2",
242
- "eslint-plugin-unicorn": "^79.0.0",
243
+ "eslint-plugin-unicorn": "^80.0.0",
243
244
  "express": "^5.3.0",
244
245
  "glob": "^10.4.5",
245
246
  "globals": "^17.14.0",
@@ -249,7 +250,7 @@
249
250
  "istanbul-reports": "^3.0.2",
250
251
  "jsonc-parser": "^3.3.1",
251
252
  "jszip": "^3.10.2",
252
- "minimatch": "^11.0.8",
253
+ "minimatch": "^11.0.9",
253
254
  "mocha": "^11.8.0",
254
255
  "mocha-junit-reporter": "^2.2.1",
255
256
  "mocha-multi-reporters": "^1.5.2",
@@ -2,7 +2,6 @@
2
2
 
3
3
  const { channel, tracingChannel } = require('dc-polyfill')
4
4
  const shimmer = require('../../datadog-shimmer')
5
- const { addHook, getHooks } = require('./helpers/instrument')
6
5
 
7
6
  const vercelAiTracingChannel = tracingChannel('dd-trace:vercel-ai')
8
7
  const vercelAiSpanSetAttributesChannel = channel('dd-trace:vercel-ai:span:setAttributes')
@@ -145,148 +144,110 @@ function wrapTracer (tracer) {
145
144
  })
146
145
  }
147
146
 
148
- let orchestrionSubscribed = false
147
+ // Orchestrion setup requires this module before activating the plugins. Module caching keeps these subscribers
148
+ // singletons even when both entry points or multiple copies of the SDK are loaded.
149
+ tracingChannel('orchestrion:ai:getTracer').subscribe({
150
+ end (ctx) {
151
+ const { arguments: args, result: tracer } = ctx
152
+ const { isEnabled } = args[0] ?? {}
149
153
 
150
- for (const hook of getHooks('ai').values()) {
151
- if (hook.file === 'dist/index.js') {
152
- // if not removed, the below hook will never match correctly
153
- // however, it is still needed in the orchestrion definition
154
- hook.file = null
155
- }
156
-
157
- addHook(hook, exports => {
158
- if (orchestrionSubscribed) return exports
159
- orchestrionSubscribed = true
160
-
161
- const getTracerChannel = tracingChannel('orchestrion:ai:getTracer')
162
- getTracerChannel.subscribe({
163
- end (ctx) {
164
- const { arguments: args, result: tracer } = ctx
165
- const { isEnabled } = args[0] ?? {}
166
-
167
- if (isEnabled !== false) {
168
- wrapTracer(tracer)
169
- }
170
- },
171
- })
154
+ if (isEnabled !== false) {
155
+ wrapTracer(tracer)
156
+ }
157
+ },
158
+ })
172
159
 
173
- /**
174
- * We patch this function to ensure that the telemetry attributes/tags are set always,
175
- * even when telemetry options are not specified. This is to ensure easy use of this integration.
176
- *
177
- * If it is explicitly disabled, however, we will not change the options.
178
- */
179
- const selectTelemetryAttributesChannel = tracingChannel('orchestrion:ai:selectTelemetryAttributes')
180
- selectTelemetryAttributesChannel.subscribe({
181
- start (ctx) {
182
- const { arguments: args } = ctx
183
- const options = args[0]
184
-
185
- if (options.telemetry?.isEnabled !== false) {
186
- args[0] = {
187
- ...options,
188
- telemetry: {
189
- ...options.telemetry,
190
- isEnabled: true,
191
- },
192
- }
193
- }
194
- },
195
- })
160
+ // Collect telemetry attributes by default, without overriding an explicit opt-out.
161
+ tracingChannel('orchestrion:ai:selectTelemetryAttributes').subscribe({
162
+ start (ctx) {
163
+ const { arguments: args } = ctx
164
+ const options = args[0]
165
+
166
+ if (options.telemetry?.isEnabled !== false) {
167
+ args[0] = {
168
+ ...options,
169
+ telemetry: {
170
+ ...options.telemetry,
171
+ isEnabled: true,
172
+ },
173
+ }
174
+ }
175
+ },
176
+ })
196
177
 
197
- tracingChannel('orchestrion:ai:includeRuntimeContext').subscribe({
198
- start (ctx) {
199
- const options = ctx.arguments[0]
200
- const runtimeContext = options?.runtimeContext
201
- const telemetry = options?.telemetry ?? options?.experimental_telemetry
178
+ tracingChannel('orchestrion:ai:includeRuntimeContext').subscribe({
179
+ start (ctx) {
180
+ const options = ctx.arguments[0]
181
+ const runtimeContext = options?.runtimeContext
182
+ const telemetry = options?.telemetry ?? options?.experimental_telemetry
202
183
 
203
- if (!runtimeContext || typeof runtimeContext !== 'object' || telemetry?.isEnabled === false) return
184
+ if (!runtimeContext || typeof runtimeContext !== 'object' || telemetry?.isEnabled === false) return
204
185
 
205
- const keys = Object.keys(runtimeContext)
206
- if (!keys.length) return
186
+ const keys = Object.keys(runtimeContext)
187
+ if (!keys.length) return
207
188
 
208
- const includeRuntimeContext = { ...telemetry?.includeRuntimeContext }
209
- for (const key of keys) {
210
- if (includeRuntimeContext[key] === undefined) includeRuntimeContext[key] = true
211
- }
189
+ const includeRuntimeContext = { ...telemetry?.includeRuntimeContext }
190
+ for (const key of keys) {
191
+ if (includeRuntimeContext[key] === undefined) includeRuntimeContext[key] = true
192
+ }
212
193
 
213
- ctx.arguments[0] = {
214
- ...options,
215
- telemetry: {
216
- ...telemetry,
217
- includeRuntimeContext,
218
- },
219
- }
194
+ ctx.arguments[0] = {
195
+ ...options,
196
+ telemetry: {
197
+ ...telemetry,
198
+ includeRuntimeContext,
220
199
  },
221
- })
222
-
223
- // resolveLanguageModel is called by all LLM entry points (generateText, streamText,
224
- // generateObject, streamObject)
225
- tracingChannel('orchestrion:ai:resolveLanguageModel').subscribe({
226
- end (ctx) {
227
- const model = ctx.arguments[0]
228
-
229
- // The SDK builds a model from a string id, in which case only the resolved instance is
230
- // worth wrapping; when the caller passed an instance, that is the one the SDK calls.
231
- if (typeof model === 'string' || model === ctx.result) {
232
- wrapModel(ctx.result)
233
- } else {
234
- wrapModel(model)
235
- wrappedModels.add(ctx.result)
236
- }
237
- },
238
- })
200
+ }
201
+ },
202
+ })
239
203
 
240
- return exports
241
- })
242
- }
204
+ // resolveLanguageModel is called by all LLM entry points (generateText, streamText, generateObject, streamObject).
205
+ tracingChannel('orchestrion:ai:resolveLanguageModel').subscribe({
206
+ end (ctx) {
207
+ const model = ctx.arguments[0]
208
+
209
+ // The SDK builds a model from a string id, in which case only the resolved instance is
210
+ // worth wrapping; when the caller passed an instance, that is the one the SDK calls.
211
+ if (typeof model === 'string' || model === ctx.result) {
212
+ wrapModel(ctx.result)
213
+ } else {
214
+ wrapModel(model)
215
+ wrappedModels.add(ctx.result)
216
+ }
217
+ },
218
+ })
243
219
 
244
220
  const aiSdkTelemetryChannel = tracingChannel('ai:telemetry')
245
221
  const aiSdkTelemetryStreamedChunkChannel = channel('dd-trace:vercel-ai:chunk')
246
222
 
247
- // for testing, and possibly actual instrumentation use, we want to
248
- // guard against double-subscribing to the asyncEnd channel of the
249
- // vercel ai-provided tracingChannel
250
- let subscribed = false
251
-
252
- // as of the v7 release, the ai sdk does not automatically aggregate streamed responses
253
- // we will handle emitting the chunks directly for products to handle
254
- addHook({ name: 'ai', versions: ['>=7.0.0'] }, exports => {
255
- if (subscribed) return exports
256
- subscribed = true
257
-
258
- // ai sdk v7 only supported on node.js 22+
259
- // inlining this import here so we only import in those cases
260
- // eslint-disable-next-line n/no-unsupported-features/node-builtins
261
- const { TransformStream } = require('node:stream/web')
262
-
263
- aiSdkTelemetryChannel.subscribe({
264
- asyncEnd (ctx) {
265
- // guard against this event being re-emitted.
266
- if (!ctx.isStream || !ctx.result?.stream || ctx.streamConsumed) return
223
+ // Only v7+ publishes this channel, so older SDKs never run the stream observer.
224
+ aiSdkTelemetryChannel.subscribe({
225
+ asyncEnd (ctx) {
226
+ // guard against this event being re-emitted.
227
+ if (!ctx.isStream || !ctx.result?.stream || ctx.streamConsumed) return
267
228
 
268
- const transform = new TransformStream({
269
- transform (chunk, controller) {
270
- const done = chunk.type === 'finish'
229
+ // ai sdk v7 only supported on node.js 22+
230
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
231
+ const { TransformStream } = require('node:stream/web')
232
+ const transform = new TransformStream({
233
+ transform (chunk, controller) {
234
+ const done = chunk.type === 'finish'
271
235
 
272
- aiSdkTelemetryStreamedChunkChannel.publish({ ctx, chunk, done })
236
+ aiSdkTelemetryStreamedChunkChannel.publish({ ctx, chunk, done })
273
237
 
274
- if (done) {
275
- aiSdkTelemetryChannel.asyncEnd.publish(ctx)
276
- }
277
-
278
- controller.enqueue(chunk) // pass through value
279
- },
280
- })
238
+ if (done) {
239
+ aiSdkTelemetryChannel.asyncEnd.publish(ctx)
240
+ }
281
241
 
282
- // The telemetry result may be a copy, but its stream is shared with the SDK.
283
- // Preserve that identity and attach the observer when the SDK pipes the stream.
284
- shimmer.wrap(ctx.result.stream, 'pipeThrough', pipeThrough => function () {
285
- const stream = pipeThrough.call(this, transform)
286
- return pipeThrough.apply(stream, arguments)
287
- })
288
- },
289
- })
242
+ controller.enqueue(chunk) // pass through value
243
+ },
244
+ })
290
245
 
291
- return exports
246
+ // The telemetry result may be a copy, but its stream is shared with the SDK.
247
+ // Preserve that identity and attach the observer when the SDK pipes the stream.
248
+ shimmer.wrap(ctx.result.stream, 'pipeThrough', pipeThrough => function () {
249
+ const stream = pipeThrough.call(this, transform)
250
+ return pipeThrough.apply(stream, arguments)
251
+ })
252
+ },
292
253
  })
@@ -14,6 +14,7 @@ const {
14
14
  // same marker. The value is the wrapper itself, so a second wrap of the same handler returns the
15
15
  // instrumented function rather than the raw one.
16
16
  const WRAPPED = Symbol.for('dd-trace.lambda.wrapped')
17
+ const prepareChannel = dc.channel('datadog:aws-lambda:invocation:prepare')
17
18
  const invocationChannel = dc.tracingChannel('datadog:aws-lambda:invoke')
18
19
 
19
20
  /**
@@ -46,6 +47,14 @@ function wrapHandler (handler, config, monitor) {
46
47
 
47
48
  // The shim awaits its startup listeners before calling the adapter. Preserve that boundary so
48
49
  // legacy RIC captures native context completion methods before the adapter replaces them.
50
+ // Resolve parent context before the invocation span starts. Diagnostic-channel publishing is synchronous,
51
+ // so the plugin supplies `preparation` when extraction must be awaited.
52
+ if (prepareChannel.hasSubscribers) prepareChannel.publish(invocationContext)
53
+ if (invocationContext.preparation) {
54
+ return invocationContext.preparation.then(() => invocationChannel.tracePromise(
55
+ () => Promise.resolve().then(() => Reflect.apply(invoke, this, args)), invocationContext
56
+ ))
57
+ }
49
58
  return invocationChannel.tracePromise(
50
59
  () => Promise.resolve().then(() => Reflect.apply(invoke, this, args)),
51
60
  invocationContext
@@ -58,7 +58,6 @@ module.exports = {
58
58
  '@smithy/smithy-client': () => require('../aws-sdk'),
59
59
  '@vitest/runner': { esmFirst: true, fn: () => require('../vitest') },
60
60
  aerospike: () => require('../aerospike'),
61
- ai: () => require('../ai'),
62
61
  amqp10: () => require('../amqp10'),
63
62
  amqplib: () => require('../amqplib'),
64
63
  avsc: () => require('../avsc'),
@@ -88,9 +88,7 @@ exports.getHooks = function getHooks (names) {
88
88
  for (const { module } of rewriterInstrumentations) {
89
89
  if (!requested.has(module.name)) continue
90
90
  // Fresh objects, including the versions array: callers may adjust a hook
91
- // for their own registration (the ai and
92
- // aws-durable-execution-sdk-js plugins set `hook.file = null`), which must
93
- // not leak into any other call.
91
+ // for their own registration, which must not leak into any other call.
94
92
  const hook = { name: module.name, versions: [module.versionRange], file: module.filePath }
95
93
  sourceRewritePaths.set(hook, module.filePath)
96
94
  hooks.set(`${module.name}|${module.versionRange}|${module.filePath}`, hook)
@@ -22,7 +22,10 @@
22
22
 
23
23
  /** @satisfies {InstrumentationRegistryEntry[]} */
24
24
  const registry = [
25
- { instrumentations: require('./instrumentations/ai') },
25
+ {
26
+ activate: { setup: () => require('../../ai') },
27
+ instrumentations: require('./instrumentations/ai'),
28
+ },
26
29
  { activate: true, instrumentations: require('./instrumentations/async-mutex') },
27
30
  { activate: true, instrumentations: require('./instrumentations/azure-cosmos') },
28
31
  { instrumentations: require('./instrumentations/azure-durable-functions') },
@@ -1,5 +1,7 @@
1
1
  'use strict'
2
2
 
3
+ // v4–6 publish separate CommonJS (.js) and ESM (.mjs) builds. v7 is ESM-only and uses
4
+ // dist/index.js for both import and require, so that file must still be rewritten for setup to run.
3
5
  module.exports = [
4
6
  // getTracer - for patching tracer
5
7
  {
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  // Match the private closure only while its captured identifiers retain the verified
4
- // 0.7–0.9 contract. A future rewrite then misses safely instead of injecting stale names.
4
+ // compiler contract. A future rewrite then misses safely instead of injecting stale names.
5
5
  const CREATE_BOUND_QUERY = 'FunctionDeclaration[id.name="createBoundQuery"]' +
6
6
  '[params.0.name="compilationContext"][params.1.name="document"][params.4.name="operationName"]'
7
7
  const WRAP_QUERY = `${CREATE_BOUND_QUERY} ` +
@@ -78,7 +78,9 @@ addInstrumentations('>=0.7.0 <0.8.5 || >=0.8.7 <0.9.0', 'dist/execution.js')
78
78
  addInstrumentations('>=0.8.5 <0.8.7', 'dist/cjs/execution.js')
79
79
  addInstrumentations('>=0.8.5 <0.8.7', 'dist/esm/execution.js')
80
80
  addInstrumentations('>=0.8.7 <0.9.0', 'dist/execution.mjs')
81
- addInstrumentations('>=0.9.1 <0.10.0', 'dist/cjs/execution.js')
82
- addInstrumentations('>=0.9.1 <0.10.0', 'dist/esm/execution.js')
81
+ for (const versionRange of ['>=0.9.1 <0.10.0', '>=0.10.0 <0.11.0']) {
82
+ addInstrumentations(versionRange, 'dist/cjs/execution.js')
83
+ addInstrumentations(versionRange, 'dist/esm/execution.js')
84
+ }
83
85
 
84
86
  module.exports = instrumentations
@@ -49,6 +49,30 @@ function finishServerRequest (protocol, requestId) {
49
49
  serverRequestCh.asyncEnd.publish(ctx)
50
50
  }
51
51
 
52
+ /**
53
+ * Plugins can replace the request a handler gets and the result the SDK sends. A failing transform keeps the result.
54
+ *
55
+ * @param {{ request: object, transformResult?: (result: unknown) => unknown }} ctx
56
+ * @param {Function} handler
57
+ * @param {object} thisArg
58
+ * @param {unknown[]} args
59
+ */
60
+ function callRequestHandler (ctx, handler, thisArg, args) {
61
+ const result = args[0] === ctx.request
62
+ ? handler.apply(thisArg, args)
63
+ : handler.call(thisArg, ctx.request, ...Array.prototype.slice.call(args, 1))
64
+ const { transformResult } = ctx
65
+ if (!transformResult) return result
66
+
67
+ return Promise.resolve(result).then(value => {
68
+ try {
69
+ return transformResult(value)
70
+ } catch {
71
+ return value
72
+ }
73
+ })
74
+ }
75
+
52
76
  function wrapRequestHandler (protocol, handler) {
53
77
  if (wrappedRequestHandlers.has(handler)) return handler
54
78
 
@@ -58,7 +82,7 @@ function wrapRequestHandler (protocol, handler) {
58
82
 
59
83
  let result
60
84
  try {
61
- result = handler.apply(this, arguments)
85
+ result = callRequestHandler(ctx, handler, this, arguments)
62
86
  } catch (err) {
63
87
  ctx.error = err
64
88
  throw err
@@ -257,4 +281,4 @@ addHook({
257
281
  return exports
258
282
  })
259
283
 
260
- module.exports = { addTraceContextToRequest }
284
+ module.exports = { addTraceContextToRequest, callRequestHandler }
@@ -3,6 +3,7 @@
3
3
  const { channel, tracingChannel } = require('dc-polyfill')
4
4
 
5
5
  const shimmer = require('../../datadog-shimmer')
6
+ const { callRequestHandler } = require('./modelcontextprotocol-sdk')
6
7
 
7
8
  const wrapHandlerCh = tracingChannel('orchestrion:@modelcontextprotocol/server:Server__wrapHandler')
8
9
  const registerToolCh = tracingChannel('orchestrion:@modelcontextprotocol/server:McpServer_registerTool')
@@ -21,7 +22,8 @@ wrapHandlerCh.end.subscribe(ctx => {
21
22
  ctx.result = shimmer.wrapFunction(handler, handler => function tracedRequestHandler (request, extra) {
22
23
  if (!serverRequestCh.hasSubscribers) return handler.apply(this, arguments)
23
24
 
24
- return serverRequestCh.tracePromise(handler, { request, extra, server }, this, ...arguments)
25
+ const requestCtx = { request, extra, server }
26
+ return serverRequestCh.tracePromise(callRequestHandler, requestCtx, undefined, requestCtx, handler, this, arguments)
25
27
  })
26
28
  })
27
29
 
@@ -8,7 +8,7 @@ let compileToRegexp
8
8
  /** @type {((pattern: string) => { tokens: object[] } | undefined) | undefined} */
9
9
  let parseTokens
10
10
 
11
- /** @type {((route: string) => ((url: string) => object | undefined) | undefined) | undefined} */
11
+ /** @type {((tokens: object[], options?: object) => ((url: string) => object | undefined) | undefined) | undefined} */
12
12
  let makeMatcher
13
13
 
14
14
  addHook({ name: 'path-to-regexp', versions: ['*'] }, moduleExports => {
@@ -39,9 +39,9 @@ addHook({ name: 'path-to-regexp', versions: ['*'] }, moduleExports => {
39
39
  // `{ tokens }` too, yet its tokens are bare strings rather than typed nodes. Gating on the version
40
40
  // keeps those from installing adapters the consumers would misread.
41
41
  addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
42
- const { parse, match } = moduleExports
42
+ const { parse, match, TokenData } = moduleExports
43
43
 
44
- if (typeof parse === 'function' && typeof match === 'function') {
44
+ if (typeof parse === 'function' && typeof match === 'function' && typeof TokenData === 'function') {
45
45
  parseTokens = pattern => {
46
46
  let result
47
47
  try {
@@ -52,12 +52,12 @@ addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
52
52
  if (Array.isArray(result?.tokens)) return result
53
53
  }
54
54
 
55
- makeMatcher = route => {
55
+ makeMatcher = (tokens, options) => {
56
56
  let matcher
57
57
  try {
58
- // Callers read which params matched, never their values: skipping decode is faster and
58
+ // Callers read raw param values only: skipping decode is faster and
59
59
  // stops a malformed escape ('%ZZ') from throwing URIError, which would read as "no match".
60
- matcher = match(route, { decode: false })
60
+ matcher = match(new TokenData(tokens), { ...options, decode: false })
61
61
  } catch {
62
62
  return
63
63
  }
@@ -68,7 +68,7 @@ addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
68
68
  } catch {
69
69
  return
70
70
  }
71
- return result ? result.params : undefined
71
+ return result || undefined
72
72
  }
73
73
  }
74
74
  }
@@ -98,10 +98,10 @@ function getParse () {
98
98
  }
99
99
 
100
100
  /**
101
- * Returns the host's path-to-regexp 8.x `match` adapter: a factory `route => (url => params)` that
102
- * compiles a route once and returns a matcher yielding the captured params (or undefined on no
103
- * match / unusable route). `undefined` when the host has not loaded an 8.x path-to-regexp.
104
- * @returns {((route: string) => ((url: string) => object | undefined) | undefined) | undefined}
101
+ * Returns the host's path-to-regexp 8.x `match` adapter: a factory `(tokens, options) => (url => match)`
102
+ * that compiles a token sequence once and returns a matcher yielding the matched `{ path, params }` (or
103
+ * undefined on no match / unusable route). `undefined` when the host has not loaded an 8.x path-to-regexp.
104
+ * @returns {((tokens: object[], options?: object) => ((url: string) => object | undefined) | undefined) | undefined}
105
105
  */
106
106
  function getMatch () {
107
107
  return makeMatcher