@adcp/sdk 15.3.0 → 15.5.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 (130) hide show
  1. package/dist/lib/advanced.d.mts +2 -2
  2. package/dist/lib/advanced.d.ts +2 -2
  3. package/dist/lib/advanced.js +8 -2
  4. package/dist/lib/advanced.mjs +8 -2
  5. package/dist/lib/core/AgentClient.d.mts +4 -0
  6. package/dist/lib/core/AgentClient.d.ts +4 -0
  7. package/dist/lib/core/AgentClient.js +8 -0
  8. package/dist/lib/core/AgentClient.mjs +8 -0
  9. package/dist/lib/core/SingleAgentClient.d.mts +154 -0
  10. package/dist/lib/core/SingleAgentClient.d.ts +154 -0
  11. package/dist/lib/core/SingleAgentClient.js +661 -23
  12. package/dist/lib/core/SingleAgentClient.mjs +666 -23
  13. package/dist/lib/core/agent-discovery-cache.d.mts +103 -0
  14. package/dist/lib/core/agent-discovery-cache.d.ts +103 -0
  15. package/dist/lib/core/agent-discovery-cache.js +121 -0
  16. package/dist/lib/core/agent-discovery-cache.mjs +92 -0
  17. package/dist/lib/index.d.mts +5 -3
  18. package/dist/lib/index.d.ts +5 -3
  19. package/dist/lib/index.js +7 -0
  20. package/dist/lib/index.mjs +6 -0
  21. package/dist/lib/protocols/index.d.mts +2 -2
  22. package/dist/lib/protocols/index.d.ts +2 -2
  23. package/dist/lib/protocols/index.js +1 -1
  24. package/dist/lib/protocols/index.mjs +1 -1
  25. package/dist/lib/protocols/mcp-call-context.d.mts +109 -0
  26. package/dist/lib/protocols/mcp-call-context.d.ts +109 -0
  27. package/dist/lib/protocols/mcp-call-context.js +221 -0
  28. package/dist/lib/protocols/mcp-call-context.mjs +186 -0
  29. package/dist/lib/protocols/mcp-modern.d.mts +9 -1
  30. package/dist/lib/protocols/mcp-modern.d.ts +9 -1
  31. package/dist/lib/protocols/mcp-modern.js +180 -104
  32. package/dist/lib/protocols/mcp-modern.mjs +193 -104
  33. package/dist/lib/protocols/mcp-scope.d.mts +15 -0
  34. package/dist/lib/protocols/mcp-scope.d.ts +15 -0
  35. package/dist/lib/protocols/mcp.d.mts +4 -2
  36. package/dist/lib/protocols/mcp.d.ts +4 -2
  37. package/dist/lib/protocols/mcp.js +178 -154
  38. package/dist/lib/protocols/mcp.mjs +189 -153
  39. package/dist/lib/protocols/transportDiagnostics.d.mts +33 -1
  40. package/dist/lib/protocols/transportDiagnostics.d.ts +33 -1
  41. package/dist/lib/protocols/transportDiagnostics.js +128 -12
  42. package/dist/lib/protocols/transportDiagnostics.mjs +128 -12
  43. package/dist/lib/reporting/gcs/index.d.mts +2 -0
  44. package/dist/lib/reporting/gcs/index.d.ts +2 -0
  45. package/dist/lib/reporting/gcs/index.js +3 -0
  46. package/dist/lib/reporting/gcs/index.mjs +2 -0
  47. package/dist/lib/reporting/gcs/row-provider.d.mts +32 -0
  48. package/dist/lib/reporting/gcs/row-provider.d.ts +32 -0
  49. package/dist/lib/reporting/gcs/row-provider.js +205 -0
  50. package/dist/lib/reporting/gcs/row-provider.mjs +188 -0
  51. package/dist/lib/reporting/ledger/change-feed.d.mts +41 -0
  52. package/dist/lib/reporting/ledger/change-feed.d.ts +41 -0
  53. package/dist/lib/reporting/ledger/change-feed.js +101 -0
  54. package/dist/lib/reporting/ledger/change-feed.mjs +74 -0
  55. package/dist/lib/reporting/ledger/handler.d.mts +6 -0
  56. package/dist/lib/reporting/ledger/handler.d.ts +6 -0
  57. package/dist/lib/reporting/ledger/handler.js +51 -8
  58. package/dist/lib/reporting/ledger/handler.mjs +50 -8
  59. package/dist/lib/reporting/ledger/index.d.mts +5 -0
  60. package/dist/lib/reporting/ledger/index.d.ts +5 -0
  61. package/dist/lib/reporting/ledger/index.js +11 -1
  62. package/dist/lib/reporting/ledger/index.mjs +5 -0
  63. package/dist/lib/reporting/ledger/lifecycle.js +3 -2
  64. package/dist/lib/reporting/ledger/lifecycle.mjs +3 -2
  65. package/dist/lib/reporting/ledger/managed-postgres.d.mts +2 -0
  66. package/dist/lib/reporting/ledger/managed-postgres.d.ts +2 -0
  67. package/dist/lib/reporting/ledger/managed-postgres.js +26 -6
  68. package/dist/lib/reporting/ledger/managed-postgres.mjs +26 -6
  69. package/dist/lib/reporting/ledger/managed.d.mts +9 -0
  70. package/dist/lib/reporting/ledger/managed.d.ts +9 -0
  71. package/dist/lib/reporting/ledger/managed.js +18 -0
  72. package/dist/lib/reporting/ledger/managed.mjs +18 -0
  73. package/dist/lib/reporting/ledger/postgres.d.mts +179 -1
  74. package/dist/lib/reporting/ledger/postgres.d.ts +179 -1
  75. package/dist/lib/reporting/ledger/postgres.js +882 -19
  76. package/dist/lib/reporting/ledger/postgres.mjs +890 -19
  77. package/dist/lib/reporting/ledger/producer.js +13 -3
  78. package/dist/lib/reporting/ledger/producer.mjs +13 -3
  79. package/dist/lib/reporting/ledger/revision-metadata.d.mts +17 -0
  80. package/dist/lib/reporting/ledger/revision-metadata.d.ts +17 -0
  81. package/dist/lib/reporting/ledger/revision-metadata.js +71 -0
  82. package/dist/lib/reporting/ledger/revision-metadata.mjs +44 -0
  83. package/dist/lib/reporting/ledger/row-encoding.d.mts +128 -0
  84. package/dist/lib/reporting/ledger/row-encoding.d.ts +128 -0
  85. package/dist/lib/reporting/ledger/row-encoding.js +355 -0
  86. package/dist/lib/reporting/ledger/row-encoding.mjs +315 -0
  87. package/dist/lib/reporting/ledger/row-storage-errors.d.mts +7 -0
  88. package/dist/lib/reporting/ledger/row-storage-errors.d.ts +7 -0
  89. package/dist/lib/reporting/ledger/row-storage-errors.js +41 -0
  90. package/dist/lib/reporting/ledger/row-storage-errors.mjs +16 -0
  91. package/dist/lib/reporting/ledger/row-storage-migration.d.mts +41 -0
  92. package/dist/lib/reporting/ledger/row-storage-migration.d.ts +41 -0
  93. package/dist/lib/reporting/ledger/row-storage-migration.js +234 -0
  94. package/dist/lib/reporting/ledger/row-storage-migration.mjs +208 -0
  95. package/dist/lib/reporting/ledger/row-storage-object.d.mts +112 -0
  96. package/dist/lib/reporting/ledger/row-storage-object.d.ts +112 -0
  97. package/dist/lib/reporting/ledger/row-storage-object.js +281 -0
  98. package/dist/lib/reporting/ledger/row-storage-object.mjs +239 -0
  99. package/dist/lib/reporting/ledger/row-storage-provider-io.d.mts +51 -0
  100. package/dist/lib/reporting/ledger/row-storage-provider-io.d.ts +51 -0
  101. package/dist/lib/reporting/ledger/row-storage-provider-io.js +152 -0
  102. package/dist/lib/reporting/ledger/row-storage-provider-io.mjs +119 -0
  103. package/dist/lib/reporting/ledger/row-storage.d.mts +224 -0
  104. package/dist/lib/reporting/ledger/row-storage.d.ts +224 -0
  105. package/dist/lib/reporting/ledger/row-storage.js +692 -0
  106. package/dist/lib/reporting/ledger/row-storage.mjs +680 -0
  107. package/dist/lib/reporting/ledger/types.d.mts +45 -0
  108. package/dist/lib/reporting/ledger/types.d.ts +45 -0
  109. package/dist/lib/reporting/service/index.d.mts +41 -1
  110. package/dist/lib/reporting/service/index.d.ts +41 -1
  111. package/dist/lib/reporting/service/index.js +68 -1
  112. package/dist/lib/reporting/service/index.mjs +70 -1
  113. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  114. package/dist/lib/signing/agent-resolver/fetch-helpers.js +1 -1
  115. package/dist/lib/signing/agent-resolver/fetch-helpers.mjs +1 -1
  116. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  117. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  118. package/dist/lib/version.d.mts +3 -3
  119. package/dist/lib/version.d.ts +3 -3
  120. package/dist/lib/version.js +3 -3
  121. package/dist/lib/version.mjs +3 -3
  122. package/docs/README.md +1 -1
  123. package/docs/TYPE-SUMMARY.md +35 -2
  124. package/docs/guides/DISCOVERY-CACHE-AND-SESSION-REUSE.md +142 -0
  125. package/docs/guides/EXISTING-PLATFORM.md +43 -12
  126. package/docs/guides/REPORTING-LEDGER.md +209 -0
  127. package/docs/llms.txt +4 -2
  128. package/docs/migration-14.x-rc-worksheet.md +4 -4
  129. package/docs/recipes/verifying-inbound-webhooks.md +8 -0
  130. package/package.json +1 -1
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Per-call context for MCP connections that are shared between calls.
3
+ *
4
+ * A reusable MCP session must be keyed only by what changes the *connection*:
5
+ * endpoint, credential, tenant/routing headers, signing identity and transport
6
+ * policy. Correlation headers (`x-request-id`, `traceparent`, ...), the caller's
7
+ * `AbortSignal` and the per-call timeout describe one *call*. They are carried
8
+ * in an `AsyncLocalStorage` store and applied by the transport fetch on every
9
+ * request, so concurrent calls over one session never see each other's values.
10
+ */
11
+ export interface MCPCallContext {
12
+ /** Correlation-only headers applied to every request made inside this call. */
13
+ headers?: Record<string, string>;
14
+ /** Cancellation for this call's own POST requests; set by {@link runCallPhase}. */
15
+ callSignal?: AbortSignal;
16
+ /** Per-call request timeout (already resolved; `undefined` means no SDK-imposed cap). */
17
+ requestTimeoutMs?: number;
18
+ }
19
+ export declare function runWithMCPCallContext<T>(context: MCPCallContext, fn: () => T): T;
20
+ export declare function currentMCPCallContext(): MCPCallContext | undefined;
21
+ /** Is this header a transient per-request correlation header (excluded from connection identity)? */
22
+ export declare function isCorrelationHeader(name: string): boolean;
23
+ /** Snapshot ambient routing headers before choosing a connection or discovery key. */
24
+ export declare function withAmbientIdentityHeaders(headers?: Record<string, string>): Record<string, string>;
25
+ /**
26
+ * Split a header bag into the headers that define the connection and the
27
+ * correlation headers that are sent per request.
28
+ */
29
+ export declare function splitConnectionHeaders(headers: Record<string, string> | undefined): {
30
+ identity: Record<string, string>;
31
+ perRequest: Record<string, string>;
32
+ };
33
+ /**
34
+ * Apply correlation headers to an outgoing request. Inside a call context the
35
+ * active call's headers apply (and only those, so a shared session never leaks
36
+ * another caller's values). With no active call — a caller who owns the
37
+ * connection directly — the headers configured on that connection apply.
38
+ */
39
+ export declare function applyMCPCallHeaders(headers: Headers, directDefaults?: Record<string, string>): void;
40
+ /**
41
+ * Run one call over a shared connection while counting it as a user of that
42
+ * connection, so a failure in one call can retire the session without closing
43
+ * it underneath other in-flight calls.
44
+ */
45
+ export declare function trackConnectionUse<T>(client: object, fn: () => Promise<T>): Promise<T>;
46
+ /**
47
+ * Close a connection that must no longer be used: immediately when idle,
48
+ * otherwise once the last in-flight call has finished.
49
+ */
50
+ export declare function closeWhenIdle(client: object, close: () => Promise<void>): Promise<void>;
51
+ /** Bounded retries for joiners whose shared connect was cancelled by its creator. */
52
+ export declare const MAX_FOREIGN_ABORT_RETRIES = 2;
53
+ export declare const RETRY_CONNECT: unique symbol;
54
+ /**
55
+ * Wait for a connect another caller started, under *this* caller's signal and
56
+ * timeout. The creator's cancellation or deadline belongs to the creator: when
57
+ * the shared connect fails that way, resolve `RETRY_CONNECT` so this caller
58
+ * connects for itself instead of inheriting someone else's abort. This
59
+ * caller's own abort or timeout still rejects.
60
+ */
61
+ export declare function joinPendingConnection<T>(pending: Promise<T>, caller: {
62
+ signal?: AbortSignal;
63
+ requestTimeoutMs?: number;
64
+ }, attempt: number): Promise<T | typeof RETRY_CONNECT>;
65
+ /**
66
+ * Give a call over a shared v1 session its own cancellable HTTP scope. Every
67
+ * request the call makes (its POSTs and any `Last-Event-ID` stream resumption)
68
+ * observes one per-call signal, which fires when the caller's own signal does
69
+ * and, regardless of outcome, once the call settles. A call that is aborted, or
70
+ * that the v1 client timed out on while its HTTP request was still open, so
71
+ * leaves nothing running on the shared session, which stays usable by others.
72
+ *
73
+ * No deadline is applied here: the v1 client's per-request timeout resets on
74
+ * progress, so an absolute timer would cut a long-running Tasks stream.
75
+ *
76
+ * Only this call's requests observe the signal (`callRequestSignal`). The
77
+ * transport's long-lived background GET/SSE listener is created at connect
78
+ * time, outside this phase, and keeps its own lifetime.
79
+ */
80
+ /** Internal cleanup of a response stream after the SDK has delivered a successful result. */
81
+ declare const MCP_CALL_COMPLETED_MARKER: unique symbol;
82
+ export declare const MCP_CALL_COMPLETED: DOMException & {
83
+ [MCP_CALL_COMPLETED_MARKER]: boolean;
84
+ };
85
+ /** Recognize the cleanup reason across independently bundled CJS/ESM entry points. */
86
+ export declare function isMCPCallCompleted(reason: unknown): boolean;
87
+ export declare function runCallPhase<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
88
+ /**
89
+ * The active call's cancellation signal for its own requests: POSTs, and the
90
+ * `Last-Event-ID` GET that resumes a dropped response stream for that call.
91
+ */
92
+ export declare function callRequestSignal(init: RequestInit | undefined): AbortSignal | undefined;
93
+ /**
94
+ * Deadline for one HTTP request: the active call's timeout, or `fallback` when
95
+ * no call context is active (a direct caller who owns the connection). The
96
+ * transport's background GET/SSE listener is long-lived by design and is never
97
+ * given a per-call deadline.
98
+ */
99
+ export declare function requestTimeoutFor(init: RequestInit | undefined, fallback?: number): number | undefined;
100
+ /**
101
+ * `{ signal }` for an outgoing request: the request's own signal combined with
102
+ * the active call's. Applied at the outermost transport wrapper so every layer
103
+ * below (diagnostics, signing, network) observes the call's cancellation and
104
+ * classifies the stream as aborted, rather than seeing only a raw network abort.
105
+ */
106
+ export declare function linkedCallSignal(init: RequestInit | undefined): {
107
+ signal?: AbortSignal;
108
+ };
109
+ export {};
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Per-call context for MCP connections that are shared between calls.
3
+ *
4
+ * A reusable MCP session must be keyed only by what changes the *connection*:
5
+ * endpoint, credential, tenant/routing headers, signing identity and transport
6
+ * policy. Correlation headers (`x-request-id`, `traceparent`, ...), the caller's
7
+ * `AbortSignal` and the per-call timeout describe one *call*. They are carried
8
+ * in an `AsyncLocalStorage` store and applied by the transport fetch on every
9
+ * request, so concurrent calls over one session never see each other's values.
10
+ */
11
+ export interface MCPCallContext {
12
+ /** Correlation-only headers applied to every request made inside this call. */
13
+ headers?: Record<string, string>;
14
+ /** Cancellation for this call's own POST requests; set by {@link runCallPhase}. */
15
+ callSignal?: AbortSignal;
16
+ /** Per-call request timeout (already resolved; `undefined` means no SDK-imposed cap). */
17
+ requestTimeoutMs?: number;
18
+ }
19
+ export declare function runWithMCPCallContext<T>(context: MCPCallContext, fn: () => T): T;
20
+ export declare function currentMCPCallContext(): MCPCallContext | undefined;
21
+ /** Is this header a transient per-request correlation header (excluded from connection identity)? */
22
+ export declare function isCorrelationHeader(name: string): boolean;
23
+ /** Snapshot ambient routing headers before choosing a connection or discovery key. */
24
+ export declare function withAmbientIdentityHeaders(headers?: Record<string, string>): Record<string, string>;
25
+ /**
26
+ * Split a header bag into the headers that define the connection and the
27
+ * correlation headers that are sent per request.
28
+ */
29
+ export declare function splitConnectionHeaders(headers: Record<string, string> | undefined): {
30
+ identity: Record<string, string>;
31
+ perRequest: Record<string, string>;
32
+ };
33
+ /**
34
+ * Apply correlation headers to an outgoing request. Inside a call context the
35
+ * active call's headers apply (and only those, so a shared session never leaks
36
+ * another caller's values). With no active call — a caller who owns the
37
+ * connection directly — the headers configured on that connection apply.
38
+ */
39
+ export declare function applyMCPCallHeaders(headers: Headers, directDefaults?: Record<string, string>): void;
40
+ /**
41
+ * Run one call over a shared connection while counting it as a user of that
42
+ * connection, so a failure in one call can retire the session without closing
43
+ * it underneath other in-flight calls.
44
+ */
45
+ export declare function trackConnectionUse<T>(client: object, fn: () => Promise<T>): Promise<T>;
46
+ /**
47
+ * Close a connection that must no longer be used: immediately when idle,
48
+ * otherwise once the last in-flight call has finished.
49
+ */
50
+ export declare function closeWhenIdle(client: object, close: () => Promise<void>): Promise<void>;
51
+ /** Bounded retries for joiners whose shared connect was cancelled by its creator. */
52
+ export declare const MAX_FOREIGN_ABORT_RETRIES = 2;
53
+ export declare const RETRY_CONNECT: unique symbol;
54
+ /**
55
+ * Wait for a connect another caller started, under *this* caller's signal and
56
+ * timeout. The creator's cancellation or deadline belongs to the creator: when
57
+ * the shared connect fails that way, resolve `RETRY_CONNECT` so this caller
58
+ * connects for itself instead of inheriting someone else's abort. This
59
+ * caller's own abort or timeout still rejects.
60
+ */
61
+ export declare function joinPendingConnection<T>(pending: Promise<T>, caller: {
62
+ signal?: AbortSignal;
63
+ requestTimeoutMs?: number;
64
+ }, attempt: number): Promise<T | typeof RETRY_CONNECT>;
65
+ /**
66
+ * Give a call over a shared v1 session its own cancellable HTTP scope. Every
67
+ * request the call makes (its POSTs and any `Last-Event-ID` stream resumption)
68
+ * observes one per-call signal, which fires when the caller's own signal does
69
+ * and, regardless of outcome, once the call settles. A call that is aborted, or
70
+ * that the v1 client timed out on while its HTTP request was still open, so
71
+ * leaves nothing running on the shared session, which stays usable by others.
72
+ *
73
+ * No deadline is applied here: the v1 client's per-request timeout resets on
74
+ * progress, so an absolute timer would cut a long-running Tasks stream.
75
+ *
76
+ * Only this call's requests observe the signal (`callRequestSignal`). The
77
+ * transport's long-lived background GET/SSE listener is created at connect
78
+ * time, outside this phase, and keeps its own lifetime.
79
+ */
80
+ /** Internal cleanup of a response stream after the SDK has delivered a successful result. */
81
+ declare const MCP_CALL_COMPLETED_MARKER: unique symbol;
82
+ export declare const MCP_CALL_COMPLETED: DOMException & {
83
+ [MCP_CALL_COMPLETED_MARKER]: boolean;
84
+ };
85
+ /** Recognize the cleanup reason across independently bundled CJS/ESM entry points. */
86
+ export declare function isMCPCallCompleted(reason: unknown): boolean;
87
+ export declare function runCallPhase<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
88
+ /**
89
+ * The active call's cancellation signal for its own requests: POSTs, and the
90
+ * `Last-Event-ID` GET that resumes a dropped response stream for that call.
91
+ */
92
+ export declare function callRequestSignal(init: RequestInit | undefined): AbortSignal | undefined;
93
+ /**
94
+ * Deadline for one HTTP request: the active call's timeout, or `fallback` when
95
+ * no call context is active (a direct caller who owns the connection). The
96
+ * transport's background GET/SSE listener is long-lived by design and is never
97
+ * given a per-call deadline.
98
+ */
99
+ export declare function requestTimeoutFor(init: RequestInit | undefined, fallback?: number): number | undefined;
100
+ /**
101
+ * `{ signal }` for an outgoing request: the request's own signal combined with
102
+ * the active call's. Applied at the outermost transport wrapper so every layer
103
+ * below (diagnostics, signing, network) observes the call's cancellation and
104
+ * classifies the stream as aborted, rather than seeing only a raw network abort.
105
+ */
106
+ export declare function linkedCallSignal(init: RequestInit | undefined): {
107
+ signal?: AbortSignal;
108
+ };
109
+ export {};
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var mcp_call_context_exports = {};
20
+ __export(mcp_call_context_exports, {
21
+ MAX_FOREIGN_ABORT_RETRIES: () => MAX_FOREIGN_ABORT_RETRIES,
22
+ MCP_CALL_COMPLETED: () => MCP_CALL_COMPLETED,
23
+ RETRY_CONNECT: () => RETRY_CONNECT,
24
+ applyMCPCallHeaders: () => applyMCPCallHeaders,
25
+ callRequestSignal: () => callRequestSignal,
26
+ closeWhenIdle: () => closeWhenIdle,
27
+ currentMCPCallContext: () => currentMCPCallContext,
28
+ isCorrelationHeader: () => isCorrelationHeader,
29
+ isMCPCallCompleted: () => isMCPCallCompleted,
30
+ joinPendingConnection: () => joinPendingConnection,
31
+ linkedCallSignal: () => linkedCallSignal,
32
+ requestTimeoutFor: () => requestTimeoutFor,
33
+ runCallPhase: () => runCallPhase,
34
+ runWithMCPCallContext: () => runWithMCPCallContext,
35
+ splitConnectionHeaders: () => splitConnectionHeaders,
36
+ trackConnectionUse: () => trackConnectionUse,
37
+ withAmbientIdentityHeaders: () => withAmbientIdentityHeaders
38
+ });
39
+ module.exports = __toCommonJS(mcp_call_context_exports);
40
+ var import_node_async_hooks = require("node:async_hooks");
41
+ var import_tracing = require('../observability/tracing.js');
42
+ var import_abort = require('./abort.js');
43
+ const callContextStorage = new import_node_async_hooks.AsyncLocalStorage();
44
+ function runWithMCPCallContext(context, fn) {
45
+ return callContextStorage.run(context, fn);
46
+ }
47
+ function currentMCPCallContext() {
48
+ return callContextStorage.getStore();
49
+ }
50
+ const CORRELATION_HEADER_NAMES = /* @__PURE__ */ new Set([
51
+ "traceparent",
52
+ "tracestate",
53
+ "sentry-trace",
54
+ "b3",
55
+ "x-request-id",
56
+ "x-correlation-id",
57
+ "x-trace-id",
58
+ "x-span-id",
59
+ "x-debug-id",
60
+ "x-client-request-id",
61
+ "x-amzn-trace-id",
62
+ "x-cloud-trace-context",
63
+ "x-ms-client-request-id",
64
+ "x-b3-traceid",
65
+ "x-b3-spanid",
66
+ "x-b3-parentspanid",
67
+ "x-b3-sampled",
68
+ "x-b3-flags",
69
+ "x-datadog-trace-id",
70
+ "x-datadog-parent-id",
71
+ "x-datadog-sampling-priority",
72
+ "x-datadog-tags"
73
+ ]);
74
+ const CORRELATION_HEADER_PATTERN = /^x-(?:[a-z0-9]+-)+(?:request|correlation|trace|span|debug)-id$/;
75
+ const IDENTITY_HEADER_HINT = /auth|token|key|secret|cookie|session|tenant|account|org|user|principal|cred|signature|advertiser|workspace|seat|brand|buyer|seller|customer|network|publisher|property|route|routing|region|project|team/;
76
+ function isCorrelationHeader(name) {
77
+ const lower = name.toLowerCase();
78
+ if (IDENTITY_HEADER_HINT.test(lower)) return false;
79
+ return CORRELATION_HEADER_NAMES.has(lower) || CORRELATION_HEADER_PATTERN.test(lower);
80
+ }
81
+ function withAmbientIdentityHeaders(headers) {
82
+ const effective = new Headers(headers);
83
+ if (!effective.has("traceparent")) {
84
+ for (const [name, value] of Object.entries((0, import_tracing.injectTraceHeaders)())) {
85
+ if (!isCorrelationHeader(name) && !effective.has(name)) effective.set(name, value);
86
+ }
87
+ }
88
+ const result = {};
89
+ effective.forEach((value, name) => {
90
+ result[name] = value;
91
+ });
92
+ return result;
93
+ }
94
+ function splitConnectionHeaders(headers) {
95
+ const identity = {};
96
+ const perRequest = {};
97
+ for (const [key, value] of Object.entries(headers ?? {})) {
98
+ (isCorrelationHeader(key) ? perRequest : identity)[key] = value;
99
+ }
100
+ return { identity, perRequest };
101
+ }
102
+ function applyMCPCallHeaders(headers, directDefaults) {
103
+ const context = callContextStorage.getStore();
104
+ const perCall = context ? context.headers : directDefaults;
105
+ if (!perCall) return;
106
+ for (const [key, value] of Object.entries(perCall)) headers.set(key, value);
107
+ }
108
+ const connectionUse = /* @__PURE__ */ new WeakMap();
109
+ async function trackConnectionUse(client, fn) {
110
+ let use = connectionUse.get(client);
111
+ if (!use) {
112
+ use = { active: 0 };
113
+ connectionUse.set(client, use);
114
+ }
115
+ use.active++;
116
+ try {
117
+ return await fn();
118
+ } finally {
119
+ use.active--;
120
+ if (use.active === 0 && use.retire) {
121
+ const retire = use.retire;
122
+ use.retire = void 0;
123
+ void retire().catch(() => {
124
+ });
125
+ }
126
+ }
127
+ }
128
+ async function closeWhenIdle(client, close) {
129
+ const use = connectionUse.get(client);
130
+ if (!use || use.active === 0) {
131
+ await close();
132
+ return;
133
+ }
134
+ use.retire = close;
135
+ }
136
+ const MAX_FOREIGN_ABORT_RETRIES = 2;
137
+ const RETRY_CONNECT = /* @__PURE__ */ Symbol("retry-connect");
138
+ async function joinPendingConnection(pending, caller, attempt) {
139
+ const settled = pending.then(
140
+ (value) => ({ value }),
141
+ (error) => ({ error })
142
+ );
143
+ const outcome = await (0, import_abort.withAbortSignal)(
144
+ [caller.signal],
145
+ (0, import_abort.resolveRequestTimeoutMs)(caller.requestTimeoutMs),
146
+ () => settled
147
+ );
148
+ if ("value" in outcome) return outcome.value;
149
+ if ((0, import_abort.isAbortOrTimeoutError)(outcome.error) && attempt < MAX_FOREIGN_ABORT_RETRIES) return RETRY_CONNECT;
150
+ throw outcome.error;
151
+ }
152
+ const MCP_CALL_COMPLETED_MARKER = /* @__PURE__ */ Symbol.for("@adcp/sdk/mcp-call-completed");
153
+ const MCP_CALL_COMPLETED = Object.assign(new DOMException("MCP call completed", "AbortError"), {
154
+ [MCP_CALL_COMPLETED_MARKER]: true
155
+ });
156
+ function isMCPCallCompleted(reason) {
157
+ return typeof reason === "object" && reason !== null && reason[MCP_CALL_COMPLETED_MARKER] === true;
158
+ }
159
+ async function runCallPhase(signal, fn) {
160
+ const context = callContextStorage.getStore();
161
+ if (!context) return fn();
162
+ const controller = new AbortController();
163
+ const forward = () => controller.abort(signal?.reason);
164
+ if (signal?.aborted) forward();
165
+ else signal?.addEventListener("abort", forward, { once: true });
166
+ let completed = false;
167
+ try {
168
+ const result = await callContextStorage.run({ ...context, callSignal: controller.signal }, fn);
169
+ completed = true;
170
+ return result;
171
+ } finally {
172
+ signal?.removeEventListener("abort", forward);
173
+ controller.abort(completed ? MCP_CALL_COMPLETED : void 0);
174
+ }
175
+ }
176
+ const JSON_RPC_NOTIFICATION = /^\s*\{[^]{0,120}?"method"\s*:\s*"notifications\//;
177
+ function isNotificationBody(body) {
178
+ if (!JSON_RPC_NOTIFICATION.test(body)) return false;
179
+ try {
180
+ const message = JSON.parse(body);
181
+ return message !== null && typeof message === "object" && !Array.isArray(message) && !Object.prototype.hasOwnProperty.call(message, "id") && typeof message.method === "string" && message.method.startsWith("notifications/");
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+ function callRequestSignal(init) {
187
+ const method = (init?.method ?? "GET").toUpperCase();
188
+ if (method !== "POST" && !(method === "GET" && new Headers(init?.headers).has("last-event-id"))) return void 0;
189
+ if (method === "POST" && typeof init?.body === "string" && isNotificationBody(init.body)) return void 0;
190
+ return callContextStorage.getStore()?.callSignal;
191
+ }
192
+ function requestTimeoutFor(init, fallback) {
193
+ if ((init?.method ?? "GET").toUpperCase() === "GET") return void 0;
194
+ const context = callContextStorage.getStore();
195
+ return context ? context.requestTimeoutMs : fallback;
196
+ }
197
+ function linkedCallSignal(init) {
198
+ const callSignal = callRequestSignal(init);
199
+ if (!callSignal) return {};
200
+ return { signal: init?.signal ? AbortSignal.any([init.signal, callSignal]) : callSignal };
201
+ }
202
+ // Annotate the CommonJS export names for ESM import in node:
203
+ 0 && (module.exports = {
204
+ MAX_FOREIGN_ABORT_RETRIES,
205
+ MCP_CALL_COMPLETED,
206
+ RETRY_CONNECT,
207
+ applyMCPCallHeaders,
208
+ callRequestSignal,
209
+ closeWhenIdle,
210
+ currentMCPCallContext,
211
+ isCorrelationHeader,
212
+ isMCPCallCompleted,
213
+ joinPendingConnection,
214
+ linkedCallSignal,
215
+ requestTimeoutFor,
216
+ runCallPhase,
217
+ runWithMCPCallContext,
218
+ splitConnectionHeaders,
219
+ trackConnectionUse,
220
+ withAmbientIdentityHeaders
221
+ });
@@ -0,0 +1,186 @@
1
+ import { fileURLToPath as __adcpFileURLToPath } from "node:url";
2
+ import { dirname as __adcpDirname } from "node:path";
3
+ import { createRequire as __adcpCreateRequire } from "node:module";
4
+ const __dirname = __adcpDirname(__adcpFileURLToPath(import.meta.url));
5
+ const require2 = __adcpCreateRequire(import.meta.url);
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ import { injectTraceHeaders } from "../observability/tracing.mjs";
8
+ import { isAbortOrTimeoutError, resolveRequestTimeoutMs, withAbortSignal } from "./abort.mjs";
9
+ const callContextStorage = new AsyncLocalStorage();
10
+ function runWithMCPCallContext(context, fn) {
11
+ return callContextStorage.run(context, fn);
12
+ }
13
+ function currentMCPCallContext() {
14
+ return callContextStorage.getStore();
15
+ }
16
+ const CORRELATION_HEADER_NAMES = /* @__PURE__ */ new Set([
17
+ "traceparent",
18
+ "tracestate",
19
+ "sentry-trace",
20
+ "b3",
21
+ "x-request-id",
22
+ "x-correlation-id",
23
+ "x-trace-id",
24
+ "x-span-id",
25
+ "x-debug-id",
26
+ "x-client-request-id",
27
+ "x-amzn-trace-id",
28
+ "x-cloud-trace-context",
29
+ "x-ms-client-request-id",
30
+ "x-b3-traceid",
31
+ "x-b3-spanid",
32
+ "x-b3-parentspanid",
33
+ "x-b3-sampled",
34
+ "x-b3-flags",
35
+ "x-datadog-trace-id",
36
+ "x-datadog-parent-id",
37
+ "x-datadog-sampling-priority",
38
+ "x-datadog-tags"
39
+ ]);
40
+ const CORRELATION_HEADER_PATTERN = /^x-(?:[a-z0-9]+-)+(?:request|correlation|trace|span|debug)-id$/;
41
+ const IDENTITY_HEADER_HINT = /auth|token|key|secret|cookie|session|tenant|account|org|user|principal|cred|signature|advertiser|workspace|seat|brand|buyer|seller|customer|network|publisher|property|route|routing|region|project|team/;
42
+ function isCorrelationHeader(name) {
43
+ const lower = name.toLowerCase();
44
+ if (IDENTITY_HEADER_HINT.test(lower)) return false;
45
+ return CORRELATION_HEADER_NAMES.has(lower) || CORRELATION_HEADER_PATTERN.test(lower);
46
+ }
47
+ function withAmbientIdentityHeaders(headers) {
48
+ const effective = new Headers(headers);
49
+ if (!effective.has("traceparent")) {
50
+ for (const [name, value] of Object.entries(injectTraceHeaders())) {
51
+ if (!isCorrelationHeader(name) && !effective.has(name)) effective.set(name, value);
52
+ }
53
+ }
54
+ const result = {};
55
+ effective.forEach((value, name) => {
56
+ result[name] = value;
57
+ });
58
+ return result;
59
+ }
60
+ function splitConnectionHeaders(headers) {
61
+ const identity = {};
62
+ const perRequest = {};
63
+ for (const [key, value] of Object.entries(headers ?? {})) {
64
+ (isCorrelationHeader(key) ? perRequest : identity)[key] = value;
65
+ }
66
+ return { identity, perRequest };
67
+ }
68
+ function applyMCPCallHeaders(headers, directDefaults) {
69
+ const context = callContextStorage.getStore();
70
+ const perCall = context ? context.headers : directDefaults;
71
+ if (!perCall) return;
72
+ for (const [key, value] of Object.entries(perCall)) headers.set(key, value);
73
+ }
74
+ const connectionUse = /* @__PURE__ */ new WeakMap();
75
+ async function trackConnectionUse(client, fn) {
76
+ let use = connectionUse.get(client);
77
+ if (!use) {
78
+ use = { active: 0 };
79
+ connectionUse.set(client, use);
80
+ }
81
+ use.active++;
82
+ try {
83
+ return await fn();
84
+ } finally {
85
+ use.active--;
86
+ if (use.active === 0 && use.retire) {
87
+ const retire = use.retire;
88
+ use.retire = void 0;
89
+ void retire().catch(() => {
90
+ });
91
+ }
92
+ }
93
+ }
94
+ async function closeWhenIdle(client, close) {
95
+ const use = connectionUse.get(client);
96
+ if (!use || use.active === 0) {
97
+ await close();
98
+ return;
99
+ }
100
+ use.retire = close;
101
+ }
102
+ const MAX_FOREIGN_ABORT_RETRIES = 2;
103
+ const RETRY_CONNECT = /* @__PURE__ */ Symbol("retry-connect");
104
+ async function joinPendingConnection(pending, caller, attempt) {
105
+ const settled = pending.then(
106
+ (value) => ({ value }),
107
+ (error) => ({ error })
108
+ );
109
+ const outcome = await withAbortSignal(
110
+ [caller.signal],
111
+ resolveRequestTimeoutMs(caller.requestTimeoutMs),
112
+ () => settled
113
+ );
114
+ if ("value" in outcome) return outcome.value;
115
+ if (isAbortOrTimeoutError(outcome.error) && attempt < MAX_FOREIGN_ABORT_RETRIES) return RETRY_CONNECT;
116
+ throw outcome.error;
117
+ }
118
+ const MCP_CALL_COMPLETED_MARKER = /* @__PURE__ */ Symbol.for("@adcp/sdk/mcp-call-completed");
119
+ const MCP_CALL_COMPLETED = Object.assign(new DOMException("MCP call completed", "AbortError"), {
120
+ [MCP_CALL_COMPLETED_MARKER]: true
121
+ });
122
+ function isMCPCallCompleted(reason) {
123
+ return typeof reason === "object" && reason !== null && reason[MCP_CALL_COMPLETED_MARKER] === true;
124
+ }
125
+ async function runCallPhase(signal, fn) {
126
+ const context = callContextStorage.getStore();
127
+ if (!context) return fn();
128
+ const controller = new AbortController();
129
+ const forward = () => controller.abort(signal?.reason);
130
+ if (signal?.aborted) forward();
131
+ else signal?.addEventListener("abort", forward, { once: true });
132
+ let completed = false;
133
+ try {
134
+ const result = await callContextStorage.run({ ...context, callSignal: controller.signal }, fn);
135
+ completed = true;
136
+ return result;
137
+ } finally {
138
+ signal?.removeEventListener("abort", forward);
139
+ controller.abort(completed ? MCP_CALL_COMPLETED : void 0);
140
+ }
141
+ }
142
+ const JSON_RPC_NOTIFICATION = /^\s*\{[^]{0,120}?"method"\s*:\s*"notifications\//;
143
+ function isNotificationBody(body) {
144
+ if (!JSON_RPC_NOTIFICATION.test(body)) return false;
145
+ try {
146
+ const message = JSON.parse(body);
147
+ return message !== null && typeof message === "object" && !Array.isArray(message) && !Object.prototype.hasOwnProperty.call(message, "id") && typeof message.method === "string" && message.method.startsWith("notifications/");
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+ function callRequestSignal(init) {
153
+ const method = (init?.method ?? "GET").toUpperCase();
154
+ if (method !== "POST" && !(method === "GET" && new Headers(init?.headers).has("last-event-id"))) return void 0;
155
+ if (method === "POST" && typeof init?.body === "string" && isNotificationBody(init.body)) return void 0;
156
+ return callContextStorage.getStore()?.callSignal;
157
+ }
158
+ function requestTimeoutFor(init, fallback) {
159
+ if ((init?.method ?? "GET").toUpperCase() === "GET") return void 0;
160
+ const context = callContextStorage.getStore();
161
+ return context ? context.requestTimeoutMs : fallback;
162
+ }
163
+ function linkedCallSignal(init) {
164
+ const callSignal = callRequestSignal(init);
165
+ if (!callSignal) return {};
166
+ return { signal: init?.signal ? AbortSignal.any([init.signal, callSignal]) : callSignal };
167
+ }
168
+ export {
169
+ MAX_FOREIGN_ABORT_RETRIES,
170
+ MCP_CALL_COMPLETED,
171
+ RETRY_CONNECT,
172
+ applyMCPCallHeaders,
173
+ callRequestSignal,
174
+ closeWhenIdle,
175
+ currentMCPCallContext,
176
+ isCorrelationHeader,
177
+ isMCPCallCompleted,
178
+ joinPendingConnection,
179
+ linkedCallSignal,
180
+ requestTimeoutFor,
181
+ runCallPhase,
182
+ runWithMCPCallContext,
183
+ splitConnectionHeaders,
184
+ trackConnectionUse,
185
+ withAmbientIdentityHeaders
186
+ };
@@ -52,12 +52,20 @@ export declare function tryCallModernMCPTool(agentUrl: string, toolName: string,
52
52
  /**
53
53
  * Probe an endpoint with the official v2 client's auto negotiation.
54
54
  * `connected: false` lets endpoint discovery retain its v1 SSE fallback.
55
+ *
56
+ * Inside a caller-owned connection scope the negotiated session is the scope's
57
+ * shared session, so the probe, capability discovery and the tool calls that
58
+ * follow run over one `initialize`. Outside a scope the probe stays a fresh,
59
+ * self-closing negotiation.
55
60
  */
56
61
  export declare function probeModernMCPConnection(agentUrl: string, authToken?: string, customHeaders?: Record<string, string>, options?: ModernMCPConnectionOptions): Promise<{
57
62
  connected: boolean;
58
63
  era?: 'legacy' | 'modern';
59
64
  }>;
60
- /** List tools when the endpoint selected the modern era; otherwise let the v1 caller continue. */
65
+ /**
66
+ * List tools when the endpoint selected the modern era (or, with `handleLegacy`,
67
+ * over the v2 client's negotiated legacy session); otherwise let the v1 caller continue.
68
+ */
61
69
  export declare function tryListModernMCPTools(agentUrl: string, authToken?: string, customHeaders?: Record<string, string>, options?: ModernMCPConnectionOptions): Promise<ModernMCPListAttempt>;
62
70
  export declare function closeModernMCPConnections(): Promise<void>;
63
71
  export {};
@@ -52,12 +52,20 @@ export declare function tryCallModernMCPTool(agentUrl: string, toolName: string,
52
52
  /**
53
53
  * Probe an endpoint with the official v2 client's auto negotiation.
54
54
  * `connected: false` lets endpoint discovery retain its v1 SSE fallback.
55
+ *
56
+ * Inside a caller-owned connection scope the negotiated session is the scope's
57
+ * shared session, so the probe, capability discovery and the tool calls that
58
+ * follow run over one `initialize`. Outside a scope the probe stays a fresh,
59
+ * self-closing negotiation.
55
60
  */
56
61
  export declare function probeModernMCPConnection(agentUrl: string, authToken?: string, customHeaders?: Record<string, string>, options?: ModernMCPConnectionOptions): Promise<{
57
62
  connected: boolean;
58
63
  era?: 'legacy' | 'modern';
59
64
  }>;
60
- /** List tools when the endpoint selected the modern era; otherwise let the v1 caller continue. */
65
+ /**
66
+ * List tools when the endpoint selected the modern era (or, with `handleLegacy`,
67
+ * over the v2 client's negotiated legacy session); otherwise let the v1 caller continue.
68
+ */
61
69
  export declare function tryListModernMCPTools(agentUrl: string, authToken?: string, customHeaders?: Record<string, string>, options?: ModernMCPConnectionOptions): Promise<ModernMCPListAttempt>;
62
70
  export declare function closeModernMCPConnections(): Promise<void>;
63
71
  export {};