agents 0.20.0 → 0.20.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/dist/react.d.ts CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  Y as MCPServersState,
3
3
  _ as AgentToolRunState,
4
4
  g as AgentToolRunPart
5
- } from "./agent-tool-types-Btk9ETS-.js";
5
+ } from "./agent-tool-types-BC-WFlsz.js";
6
6
  import { ClientParameters } from "./serializable.js";
7
7
  import {
8
8
  AgentConnectionError,
@@ -1,4 +1,4 @@
1
- import { st as StreamingResponse } from "./agent-tool-types-Btk9ETS-.js";
1
+ import { st as StreamingResponse } from "./agent-tool-types-BC-WFlsz.js";
2
2
 
3
3
  //#region src/serializable.d.ts
4
4
  type SerializablePrimitive = undefined | null | string | number | boolean;
@@ -4,7 +4,7 @@ import {
4
4
  ln as getSubAgentByName,
5
5
  sn as SUB_PREFIX,
6
6
  un as parseSubAgentPath
7
- } from "./agent-tool-types-Btk9ETS-.js";
7
+ } from "./agent-tool-types-BC-WFlsz.js";
8
8
  export {
9
9
  SUB_PREFIX,
10
10
  SubAgentPathMatch,
@@ -1,4 +1,4 @@
1
- import { O as Agent } from "./agent-tool-types-Btk9ETS-.js";
1
+ import { O as Agent } from "./agent-tool-types-BC-WFlsz.js";
2
2
  import {
3
3
  C as WorkflowStatus,
4
4
  S as WorkflowRejectedError,
@@ -18,7 +18,7 @@ The MCP client capability lets your agent:
18
18
  Install the exact MCP client peer used by this Agents release:
19
19
 
20
20
  ```sh
21
- pnpm add agents @modelcontextprotocol/client@2.0.0-beta.5
21
+ pnpm add agents @modelcontextprotocol/client@2.0.0
22
22
  ```
23
23
 
24
24
  ```typescript
@@ -19,7 +19,7 @@ This guide covers the different ways to create MCP servers with the Agents SDK a
19
19
  The simplest way to create an MCP server. Install the exact SDK v2 server peer, then use the isolated server entry point so legacy Agents transports and MCP clients stay out of your Worker bundle:
20
20
 
21
21
  ```sh
22
- pnpm add agents @modelcontextprotocol/server@2.0.0-beta.5 zod
22
+ pnpm add agents @modelcontextprotocol/server@2.0.0 zod
23
23
  ```
24
24
 
25
25
  ```typescript
@@ -466,8 +466,9 @@ exists:
466
466
  | `cloudflare.agents.runtime_context.{key}` | Explicitly included scalar runtime context |
467
467
  | `cloudflare.agents.tool_context.{tool}.{key}` | Explicitly included scalar context on the executed tool span |
468
468
  | `cloudflare.agents.metadata.{key}` | Other scalar v6 telemetry metadata |
469
- | `cloudflare.agents.turn.{request_id,trigger,admission,channel,continuation,generation}` | Think turn context |
469
+ | `cloudflare.agents.turn.{request_id,trigger,admission,channel,continuation,generation}` | Think turn context, from v6 metadata or v7 runtime context |
470
470
  | `cloudflare.agents.canceled` | Recognized cancellation, not a failure |
471
+ | `cloudflare.agents.span.truncated` | Span closed by its invocation ending before the work finished |
471
472
 
472
473
  `gen_ai.response.finish_reasons` and `gen_ai.request.stop_sequences` are arrays
473
474
  in OTel. Workers' custom `Span.setAttribute` currently accepts only a string,
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "durable objects"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.20.0",
12
+ "version": "0.20.1",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/agents",
@@ -39,10 +39,10 @@
39
39
  "devDependencies": {
40
40
  "@ai-sdk/react": "^4.0.0",
41
41
  "@cloudflare/codemode": "^0.5.1",
42
- "@modelcontextprotocol/client": "2.0.0-beta.5",
42
+ "@modelcontextprotocol/client": "2.0.0",
43
43
  "@modelcontextprotocol/conformance-v2": "npm:@modelcontextprotocol/conformance@0.2.0-alpha.10",
44
- "@modelcontextprotocol/sdk": "1.29.0",
45
- "@modelcontextprotocol/server": "2.0.0-beta.5",
44
+ "@modelcontextprotocol/sdk": "1.30.0",
45
+ "@modelcontextprotocol/server": "2.0.0",
46
46
  "@tanstack/ai": "0.38.0",
47
47
  "@types/react": "^19.2.17",
48
48
  "@types/yargs": "^17.0.35",
@@ -60,9 +60,9 @@
60
60
  "peerDependencies": {
61
61
  "@ai-sdk/react": "^3.0.0 || ^4.0.0",
62
62
  "@cloudflare/codemode": ">=0.5.0",
63
- "@modelcontextprotocol/client": "2.0.0-beta.5",
64
- "@modelcontextprotocol/sdk": "1.29.0",
65
- "@modelcontextprotocol/server": "2.0.0-beta.5",
63
+ "@modelcontextprotocol/client": "2.0.0",
64
+ "@modelcontextprotocol/sdk": "1.30.0",
65
+ "@modelcontextprotocol/server": "2.0.0",
66
66
  "@tanstack/ai": ">=0.10.2 <1.0.0",
67
67
  "@x402/core": "^2.0.0",
68
68
  "@x402/evm": "^2.0.0",
@@ -1,117 +0,0 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
2
- import * as cloudflareWorkers from "cloudflare:workers";
3
- //#region src/observability/tracing/tracer.ts
4
- /** Creates a tracer from a runtime span capability. */
5
- function createTracer(runtime) {
6
- return new RuntimeTracer(runtime);
7
- }
8
- var RuntimeTracer = class {
9
- constructor(runtime) {
10
- this.runtime = runtime;
11
- }
12
- withSpan(name, attributes, run) {
13
- return this.activate(name, attributes, (span) => {
14
- const result = run(span);
15
- if (isPromiseLike(result)) return Promise.resolve(result).catch((cause) => {
16
- span.fail(cause);
17
- throw cause;
18
- }).finally(() => {
19
- span.close();
20
- });
21
- span.close();
22
- return result;
23
- });
24
- }
25
- openSpan(name, attributes, activate) {
26
- return this.activate(name, attributes, activate);
27
- }
28
- /**
29
- * Shared scaffold: opens an active span, seeds its attributes, and fails the
30
- * span on a thrown defect before rethrowing. The `body` decides the span's
31
- * finishing policy (managed vs. caller-owned).
32
- */
33
- activate(name, attributes, body) {
34
- return this.runtime.startActiveSpan(name, (writer) => {
35
- setAttributes(writer, attributes);
36
- const span = new ManagedSpan(writer);
37
- try {
38
- return body(span);
39
- } catch (cause) {
40
- span.fail(cause);
41
- throw cause;
42
- }
43
- });
44
- }
45
- };
46
- var _closed = /* @__PURE__ */ new WeakMap();
47
- var ManagedSpan = class {
48
- constructor(span) {
49
- this.span = span;
50
- _classPrivateFieldInitSpec(this, _closed, false);
51
- }
52
- get isTraced() {
53
- return this.span.isTraced;
54
- }
55
- /** INTERNAL: see {@link writeSpanAttributes}. */
56
- writeAttributes(attributes) {
57
- if (_classPrivateFieldGet2(_closed, this)) return;
58
- setAttributes(this.span, attributes);
59
- }
60
- finish(attributes = {}) {
61
- if (_classPrivateFieldGet2(_closed, this)) return;
62
- setAttributes(this.span, attributes);
63
- this.close();
64
- }
65
- fail(cause) {
66
- if (_classPrivateFieldGet2(_closed, this)) return;
67
- if (isCancellation(cause)) setAttributes(this.span, { "cloudflare.agents.canceled": true });
68
- else setAttributes(this.span, { "error.type": cause instanceof Error ? cause.name || "Error" : typeof cause });
69
- this.close();
70
- }
71
- close() {
72
- if (_classPrivateFieldGet2(_closed, this)) return;
73
- _classPrivateFieldSet2(_closed, this, true);
74
- this.span.end();
75
- }
76
- };
77
- /**
78
- * INTERNAL: writes attributes onto an open managed span. Lets instrumentation
79
- * defer expensive attribute computation until after the isTraced check (span
80
- * names must exist at open time; attributes need not). Not part of the public
81
- * barrel surface.
82
- */
83
- function writeSpanAttributes(span, attributes) {
84
- if (span instanceof ManagedSpan) span.writeAttributes(attributes);
85
- }
86
- function setAttributes(span, attributes) {
87
- if (!span.isTraced) return;
88
- try {
89
- for (const [key, value] of Object.entries(attributes)) if (value !== void 0) span.setAttribute(key, value);
90
- } catch {}
91
- }
92
- function isPromiseLike(value) {
93
- return value !== null && value !== void 0 && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
94
- }
95
- /**
96
- * Recognizes caller/runtime cancellation (an `AbortError`, e.g. from an aborted
97
- * `AbortSignal`) so it can be classified separately from genuine failures. A
98
- * `DOMException` named `AbortError` is not always an `Error` instance, so this
99
- * probes the `name` field structurally rather than via `instanceof`.
100
- */
101
- function isCancellation(cause) {
102
- return typeof cause === "object" && cause !== null && "name" in cause && cause.name === "AbortError";
103
- }
104
- //#endregion
105
- //#region src/observability/tracing/cloudflare.ts
106
- const noopSpan = {
107
- isTraced: false,
108
- setAttribute() {},
109
- end() {}
110
- };
111
- const tracer = createTracer(cloudflareWorkers.tracing ?? { startActiveSpan(_name, run) {
112
- return run(noopSpan);
113
- } });
114
- //#endregion
115
- export { writeSpanAttributes as n, tracer as t };
116
-
117
- //# sourceMappingURL=cloudflare-BldFV0Pa.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cloudflare-BldFV0Pa.js","names":[],"sources":["../src/observability/tracing/tracer.ts","../src/observability/tracing/cloudflare.ts"],"sourcesContent":["/** Attribute values accepted by custom spans. */\nexport type TraceAttributeValue = string | number | boolean | undefined;\n\n/** Initial or finish attributes attached to a span. */\nexport type TraceAttributes = Readonly<Record<string, TraceAttributeValue>>;\n\n/** A value that may complete synchronously or through a promise-like result. */\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\n/** Minimal runtime span surface used by tracers. */\nexport type SpanWriter = {\n readonly isTraced: boolean;\n setAttribute(key: string, value: TraceAttributeValue): void;\n end(): void;\n};\n\n/** Runtime capability for starting an active span in the current async context. */\nexport type SpanRuntime = {\n startActiveSpan<T>(name: string, run: (span: SpanWriter) => T): T;\n};\n\n/** AgentTracer seam used by integrations. */\nexport type AgentTracer = {\n /**\n * Runs `run` inside an active span whose lifetime the tracer owns: the span\n * finishes when `run` returns (or its promise resolves) and fails when `run`\n * throws or rejects. Callers do not call {@link AgentSpan.finish}/{@link AgentSpan.fail};\n * doing so early is safe but the tracer guarantees closure.\n *\n * @template T The value produced by the instrumented work.\n */\n withSpan<T>(\n name: string,\n attributes: TraceAttributes,\n run: (span: AgentSpan) => MaybePromise<T>\n ): T | Promise<T>;\n /**\n * Activates a span and returns whatever `activate` returns (typically the\n * {@link AgentSpan} handle itself). The caller owns the span lifetime and MUST call\n * {@link AgentSpan.finish} or {@link AgentSpan.fail}; an unfinished span leaks. Use this\n * for work that outlives the callback, such as streams and event-driven\n * telemetry. A throw from `activate` still fails the span before rethrowing.\n *\n * @template T The value returned to the caller, usually the span handle.\n */\n openSpan<T>(\n name: string,\n attributes: TraceAttributes,\n activate: (span: AgentSpan) => T\n ): T;\n};\n\n/** Active span handle passed to instrumented work. */\nexport type AgentSpan = {\n /**\n * Whether this invocation is actually being traced. Instrumentation can use\n * this to skip expensive capture work when nobody is listening.\n */\n readonly isTraced: boolean;\n /** Records the optional finish attributes and ends the span. Idempotent. */\n finish(attributes?: TraceAttributes): void;\n /**\n * Ends the span as not-successful. Genuine failures record `error.type`;\n * recognized cancellations (an `AbortError`) record `canceled` instead so aborts\n * are not counted as errors. The cause message is never recorded. Idempotent.\n */\n fail(cause: unknown): void;\n};\n\n/** Creates a tracer from a runtime span capability. */\nexport function createTracer(runtime: SpanRuntime): AgentTracer {\n return new RuntimeTracer(runtime);\n}\n\nclass RuntimeTracer implements AgentTracer {\n constructor(private readonly runtime: SpanRuntime) {}\n\n withSpan<T>(\n name: string,\n attributes: TraceAttributes,\n run: (span: AgentSpan) => MaybePromise<T>\n ): T | Promise<T> {\n return this.activate(name, attributes, (span) => {\n const result = run(span);\n if (isPromiseLike(result)) {\n return Promise.resolve(result)\n .catch((cause: unknown) => {\n span.fail(cause);\n throw cause;\n })\n .finally(() => {\n span.close();\n });\n }\n\n span.close();\n return result;\n });\n }\n\n openSpan<T>(\n name: string,\n attributes: TraceAttributes,\n activate: (span: AgentSpan) => T\n ): T {\n return this.activate(name, attributes, activate);\n }\n\n /**\n * Shared scaffold: opens an active span, seeds its attributes, and fails the\n * span on a thrown defect before rethrowing. The `body` decides the span's\n * finishing policy (managed vs. caller-owned).\n */\n private activate<T>(\n name: string,\n attributes: TraceAttributes,\n body: (span: ManagedSpan) => T\n ): T {\n return this.runtime.startActiveSpan(name, (writer) => {\n setAttributes(writer, attributes);\n const span = new ManagedSpan(writer);\n\n try {\n return body(span);\n } catch (cause: unknown) {\n span.fail(cause);\n throw cause;\n }\n });\n }\n}\n\nclass ManagedSpan implements AgentSpan {\n #closed = false;\n\n constructor(private readonly span: SpanWriter) {}\n\n get isTraced(): boolean {\n return this.span.isTraced;\n }\n\n /** INTERNAL: see {@link writeSpanAttributes}. */\n writeAttributes(attributes: TraceAttributes): void {\n if (this.#closed) {\n return;\n }\n\n setAttributes(this.span, attributes);\n }\n\n finish(attributes: TraceAttributes = {}): void {\n if (this.#closed) {\n return;\n }\n\n setAttributes(this.span, attributes);\n this.close();\n }\n\n fail(cause: unknown): void {\n if (this.#closed) {\n return;\n }\n\n if (isCancellation(cause)) {\n // Cancellation is a control path, not a failure: OTel semconv leaves\n // status Unset and records no error.type for cancellations, so aborted\n // operations do not inflate error rates. The vendor marker is additive.\n setAttributes(this.span, { \"cloudflare.agents.canceled\": true });\n } else {\n // Workers' custom Span API does not currently expose setStatus(). Do not\n // invent an `otel.status_code` attribute: status is span state in OTel,\n // not an attribute. error.type remains the standard queryable marker.\n setAttributes(this.span, {\n \"error.type\":\n cause instanceof Error ? cause.name || \"Error\" : typeof cause\n });\n }\n\n this.close();\n }\n\n close(): void {\n if (this.#closed) {\n return;\n }\n\n this.#closed = true;\n this.span.end();\n }\n}\n\n/**\n * INTERNAL: writes attributes onto an open managed span. Lets instrumentation\n * defer expensive attribute computation until after the isTraced check (span\n * names must exist at open time; attributes need not). Not part of the public\n * barrel surface.\n */\nexport function writeSpanAttributes(\n span: AgentSpan,\n attributes: TraceAttributes\n): void {\n if (span instanceof ManagedSpan) {\n span.writeAttributes(attributes);\n }\n}\n\nfunction setAttributes(span: SpanWriter, attributes: TraceAttributes): void {\n if (!span.isTraced) {\n return;\n }\n\n // Fail-safe: a throwing writer must not leak the span or replace the\n // application's original error with a telemetry one.\n try {\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n span.setAttribute(key, value);\n }\n }\n } catch {\n // Drop the attributes; the span still closes.\n }\n}\n\nfunction isPromiseLike<T>(value: MaybePromise<T>): value is PromiseLike<T> {\n return (\n value !== null &&\n value !== undefined &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\n/**\n * Recognizes caller/runtime cancellation (an `AbortError`, e.g. from an aborted\n * `AbortSignal`) so it can be classified separately from genuine failures. A\n * `DOMException` named `AbortError` is not always an `Error` instance, so this\n * probes the `name` field structurally rather than via `instanceof`.\n */\nfunction isCancellation(cause: unknown): boolean {\n return (\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n cause.name === \"AbortError\"\n );\n}\n","import * as cloudflareWorkers from \"cloudflare:workers\";\nimport { createTracer } from \"./tracer\";\nimport type { SpanRuntime, SpanWriter, AgentTracer } from \"./tracer\";\n\nconst noopSpan: SpanWriter = {\n isTraced: false,\n setAttribute() {},\n end() {}\n};\n\nconst noopRuntime: SpanRuntime = {\n startActiveSpan(_name, run) {\n return run(noopSpan);\n }\n};\n\n// Accessed via the namespace so runtimes that predate the `tracing` export\n// degrade to a no-op tracer instead of failing at module-link time — this\n// module loads with the main `agents` entry, not just for tracing users.\nconst runtime: SpanRuntime =\n (cloudflareWorkers as { tracing?: SpanRuntime }).tracing ?? noopRuntime;\n\nexport const tracer: AgentTracer = createTracer(runtime);\n"],"mappings":";;;;AAsEA,SAAgB,aAAa,SAAmC;CAC9D,OAAO,IAAI,cAAc,OAAO;AAClC;AAEA,IAAM,gBAAN,MAA2C;CACzC,YAAY,SAAuC;EAAtB,KAAA,UAAA;CAAuB;CAEpD,SACE,MACA,YACA,KACgB;EAChB,OAAO,KAAK,SAAS,MAAM,aAAa,SAAS;GAC/C,MAAM,SAAS,IAAI,IAAI;GACvB,IAAI,cAAc,MAAM,GACtB,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAC3B,OAAO,UAAmB;IACzB,KAAK,KAAK,KAAK;IACf,MAAM;GACR,CAAC,CAAC,CACD,cAAc;IACb,KAAK,MAAM;GACb,CAAC;GAGL,KAAK,MAAM;GACX,OAAO;EACT,CAAC;CACH;CAEA,SACE,MACA,YACA,UACG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AClD,IAAI,UAAU,KAAA,GACZ,KAAK,aAAa,KAAK,KAAK;CAGlC,QAAQ,CAER;AACF;AAEA,SAAS,cAAiB,OAAiD;CACzE,OACE,UAAU,QACV,UAAU,KAAA,MACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,UAAU,SACV,OAAO,MAAM,SAAS;AAE1B;;;;;;;AAQA,SAAS,eAAe,OAAyB;CAC/C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,MAAM,SAAS;AAEnB;;;ACpPA,MAAM,WAAuB;CAC3B,UAAU;CACV,eAAe,CAAC;CAChB,MAAM,CAAC;AACT;AAcA,MAAa,SAAsB,aAFhC,kBAAgD,WAAW,EAT5D,gBAAgB,OAAO,KAAK;CAC1B,OAAO,IAAI,QAAQ;AACrB,EAOsE,CAEjB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"handler-stateless-8hQN_kC3.js","names":["candidate","createSdkMcpHandler"],"sources":["../src/mcp/sse-keepalive.ts","../src/mcp/auth-context.ts","../src/mcp/handler-errors.ts","../src/mcp/handler-legacy-compat.ts","../src/mcp/handler-stateless.ts"],"sourcesContent":["/**\n * Shared SSE keepalive utility for MCP transports.\n *\n * Cloudflare's edge closes idle SSE responses after ~5 minutes. Writers\n * that may sit silent for that long (long-running tool calls, idle\n * standalone GET streams) arm a keepalive to keep the response under the\n * watchdog.\n *\n * See cloudflare/agents#1583.\n */\n\n/** Interval between SSE keepalive comment frames, in ms.\n *\n * The WHATWG SSE spec recommends a comment line every \"15 seconds or so\"\n * (html.spec.whatwg.org §9.2.7). 25s gives comfortable headroom below\n * both the ~30s post-handler background-work cancellation window on\n * Workers and the ~5min Cloudflare edge idle-stream watchdog.\n */\nexport const KEEPALIVE_INTERVAL_MS = 25_000;\n\n/** SSE comment frame the parser drops before any event dispatch. */\nexport const KEEPALIVE_FRAME = \": keepalive\\n\\n\";\n\n/**\n * Start an SSE keepalive on `writer`. Returns a `clearInterval` handle\n * that the stream cleanup must invoke when the stream closes.\n */\nexport function startKeepalive(\n writer: WritableStreamDefaultWriter<Uint8Array>,\n encoder: TextEncoder\n): ReturnType<typeof setInterval> {\n const handle = setInterval(() => {\n writer\n .write(encoder.encode(KEEPALIVE_FRAME))\n .catch(() => clearInterval(handle));\n }, KEEPALIVE_INTERVAL_MS);\n return handle;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AuthInfo } from \"@modelcontextprotocol/server\";\n\nconst VERIFIED_OAUTH_CONTEXT = Symbol.for(\n \"cloudflare.workers-oauth-provider.verified-context.v1\"\n);\n\ninterface VerifiedWorkersOAuthContext {\n version: 1;\n token: string;\n clientId: string;\n scopes: string[];\n expiresAt?: number;\n resource?: string;\n props: Record<string, unknown>;\n}\n\nexport interface McpAuthContext {\n props: Record<string, unknown>;\n}\n\nconst authContextStorage = new AsyncLocalStorage<McpAuthContext>();\n\nexport function getMcpAuthContext(): McpAuthContext | undefined {\n return authContextStorage.getStore();\n}\n\nexport function runWithAuthContext<T>(context: McpAuthContext, fn: () => T): T {\n return authContextStorage.run(context, fn);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction invalidVerifiedContext(): never {\n throw new TypeError(\"Invalid verified OAuth request context\");\n}\n\nexport function getVerifiedOAuthAuthInfo(\n ctx: ExecutionContext\n): { authInfo: AuthInfo; props: Record<string, unknown> } | undefined {\n const symbolContext = ctx as ExecutionContext & Record<symbol, unknown>;\n if (!(VERIFIED_OAUTH_CONTEXT in symbolContext)) return undefined;\n\n const value = symbolContext[VERIFIED_OAUTH_CONTEXT];\n if (!isPlainRecord(value) || value.version !== 1) invalidVerifiedContext();\n\n const candidate = value as Partial<VerifiedWorkersOAuthContext>;\n const { token, clientId, scopes, expiresAt, resource, props } = candidate;\n if (\n typeof token !== \"string\" ||\n token.length === 0 ||\n typeof clientId !== \"string\" ||\n clientId.length === 0 ||\n !Array.isArray(scopes) ||\n !scopes.every((scope) => typeof scope === \"string\") ||\n !isPlainRecord(props)\n ) {\n invalidVerifiedContext();\n }\n\n if (\n expiresAt !== undefined &&\n (typeof expiresAt !== \"number\" ||\n !Number.isFinite(expiresAt) ||\n expiresAt <= 0)\n ) {\n invalidVerifiedContext();\n }\n\n let resourceUrl: URL | undefined;\n if (resource !== undefined) {\n if (typeof resource !== \"string\") invalidVerifiedContext();\n try {\n resourceUrl = new URL(resource);\n } catch {\n invalidVerifiedContext();\n }\n if (resourceUrl.protocol !== \"http:\" && resourceUrl.protocol !== \"https:\") {\n invalidVerifiedContext();\n }\n }\n\n if (ctx.props !== props) invalidVerifiedContext();\n\n return {\n props,\n authInfo: {\n token,\n clientId,\n scopes: [...scopes],\n ...(expiresAt !== undefined && { expiresAt }),\n ...(resourceUrl !== undefined && { resource: resourceUrl }),\n extra: { props }\n }\n };\n}\n","export function internalErrorResponse(\n id: string | number | null = null\n): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: -32603, message: \"Internal server error\" },\n id\n },\n { status: 500 }\n );\n}\n\nexport function requestIdFromParsedBody(body: unknown): string | number | null {\n if (\n typeof body !== \"object\" ||\n body === null ||\n Array.isArray(body) ||\n !(\"method\" in body) ||\n typeof body.method !== \"string\" ||\n !(\"id\" in body)\n ) {\n return null;\n }\n return typeof body.id === \"string\" || typeof body.id === \"number\"\n ? body.id\n : null;\n}\n\nexport function reportHandlerError(\n onerror: ((error: Error) => void) | undefined,\n error: unknown\n): void {\n try {\n onerror?.(error instanceof Error ? error : new Error(String(error)));\n } catch {\n // Error reporting must not change the response.\n }\n}\n","import {\n WebStandardStreamableHTTPServerTransport,\n isJSONRPCRequest,\n type McpHandlerRequestOptions,\n type McpServer,\n type McpServerFactory,\n type Server\n} from \"@modelcontextprotocol/server\";\nimport {\n internalErrorResponse,\n reportHandlerError,\n requestIdFromParsedBody\n} from \"./handler-errors\";\nimport { KEEPALIVE_FRAME, KEEPALIVE_INTERVAL_MS } from \"./sse-keepalive\";\n\n/**\n * Temporary adapter for Legacy compatibility on the SDK v2 transport.\n *\n * Local deltas from the upstream stateless fallback:\n *\n * - impossible stateless server-to-client requests fail immediately rather\n * than leaving the tool handler waiting for a session response;\n * - streamed POST responses receive Cloudflare's 25-second SSE keepalive.\n *\n * Remove this adapter once the SDK exposes both policies directly.\n */\nexport function createLegacyCompatibilityRequestHandler(\n factory: McpServerFactory,\n onerror?: (error: Error) => void\n) {\n const fetch = async (\n request: Request,\n options: McpHandlerRequestOptions | undefined\n ): Promise<Response> => {\n // Match the upstream Legacy fallback: GET and DELETE are session operations\n // and cannot be served by a fresh per-request transport. Reject\n // them before running a factory with application-visible side effects.\n if (request.method.toUpperCase() !== \"POST\") {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Method not allowed.\" },\n id: null\n },\n { status: 405 }\n );\n }\n\n if (request.signal.aborted) {\n return new Response(null, { status: 499 });\n }\n\n let product: McpServer | Server | undefined;\n let transport: WebStandardStreamableHTTPServerTransport | undefined;\n let clearResponseKeepalive = () => {};\n let teardownPromise: Promise<void> | undefined;\n const teardown = () =>\n (teardownPromise ??= (async () => {\n clearResponseKeepalive();\n await Promise.all([\n transport?.close().catch(() => {}),\n product?.close().catch(() => {})\n ]);\n })());\n const onAbort = () => void teardown();\n\n try {\n product = await factory({\n era: \"legacy\",\n ...(options?.authInfo !== undefined && { authInfo: options.authInfo }),\n requestInfo: request\n });\n transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined\n });\n\n const send = transport.send.bind(transport);\n transport.send = async (message, sendOptions) => {\n if (isJSONRPCRequest(message)) {\n transport?.onmessage?.({\n jsonrpc: \"2.0\",\n id: message.id,\n error: {\n code: -32603,\n message:\n \"Server-to-client requests are unavailable in the Legacy compatibility lane. \" +\n \"Use inputRequired(...) for Stateless clients, or route \" +\n \"Legacy traffic to a sessionful transport.\"\n }\n });\n return;\n }\n await send(message, sendOptions);\n };\n\n await product.connect(transport);\n if (request.signal.aborted) {\n await teardown();\n return new Response(null, { status: 499 });\n }\n request.signal.addEventListener(\"abort\", onAbort, { once: true });\n const response = await transport.handleRequest(request, {\n ...(options?.authInfo !== undefined && {\n authInfo: options.authInfo\n }),\n ...(options?.parsedBody !== undefined && {\n parsedBody: options.parsedBody\n })\n });\n\n if (\n response.body === null ||\n !response.headers.get(\"content-type\")?.includes(\"text/event-stream\")\n ) {\n request.signal.removeEventListener(\"abort\", onAbort);\n await teardown();\n return response;\n }\n\n const reader = response.body.getReader();\n const encoder = new TextEncoder();\n let keepalive: ReturnType<typeof setInterval> | undefined;\n const clearKeepalive = () => {\n if (keepalive !== undefined) {\n clearInterval(keepalive);\n keepalive = undefined;\n }\n };\n clearResponseKeepalive = clearKeepalive;\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n if (teardownPromise) return;\n keepalive = setInterval(() => {\n try {\n controller.enqueue(encoder.encode(KEEPALIVE_FRAME));\n } catch {\n clearKeepalive();\n }\n }, KEEPALIVE_INTERVAL_MS);\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n clearKeepalive();\n request.signal.removeEventListener(\"abort\", onAbort);\n await teardown();\n controller.close();\n } else if (value !== undefined) {\n controller.enqueue(value);\n }\n } catch (error) {\n clearKeepalive();\n request.signal.removeEventListener(\"abort\", onAbort);\n await teardown();\n controller.error(error);\n }\n },\n async cancel(reason) {\n clearKeepalive();\n request.signal.removeEventListener(\"abort\", onAbort);\n await reader.cancel(reason).catch(() => {});\n await teardown();\n }\n });\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers\n });\n } catch (error) {\n request.signal.removeEventListener(\"abort\", onAbort);\n await teardown();\n reportHandlerError(onerror, error);\n return internalErrorResponse(\n requestIdFromParsedBody(options?.parsedBody)\n );\n }\n };\n\n return { fetch };\n}\n","import {\n createMcpHandler as createSdkMcpHandler,\n hostHeaderValidationResponse,\n isLegacyRequest,\n localhostAllowedHostnames,\n localhostAllowedOrigins,\n originValidationResponse,\n type AuthInfo,\n type CreateMcpHandlerOptions as SdkCreateMcpHandlerOptions,\n type McpHandlerRequestOptions,\n type McpServerFactory,\n type ServerNotifier\n} from \"@modelcontextprotocol/server\";\nimport {\n getVerifiedOAuthAuthInfo,\n runWithAuthContext,\n type McpAuthContext\n} from \"./auth-context\";\nimport { internalErrorResponse, reportHandlerError } from \"./handler-errors\";\nimport { createLegacyCompatibilityRequestHandler } from \"./handler-legacy-compat\";\nimport type { CORSOptions } from \"./types\";\n\nexport interface CreateStatelessMcpHandlerOptions extends Omit<\n SdkCreateMcpHandlerOptions,\n \"bus\"\n> {\n /** Exact pathname handled by this Worker wrapper. @default \"/mcp\" */\n route?: string;\n /** CORS headers applied by the Worker wrapper. Pass `false` to disable. */\n corsOptions?: CORSOptions | false;\n /**\n * Restrict `Host` headers to these hostnames. Localhost and `workers.dev`\n * endpoints receive matching defaults; custom domains rely on Cloudflare\n * routing unless this option is set.\n */\n allowedHostnames?: string[];\n /**\n * Restrict present browser `Origin` headers to these hostnames. Requests\n * without an Origin (including non-browser MCP clients) remain valid. The\n * default includes localhost-class Origins, the endpoint's `workers.dev`\n * hostname, and a concrete `corsOptions.origin` hostname. Pass `\"*\"` only\n * when equivalent Origin validation runs in trusted middleware upstream.\n */\n allowedOriginHostnames?: string[] | \"*\";\n /** Application props exposed through {@link getMcpAuthContext}. */\n authContext?: McpAuthContext;\n}\n\nexport type StatelessMcpHandler = {\n (request: Request, env: unknown, ctx: ExecutionContext): Promise<Response>;\n fetch(\n request: Request,\n options?: McpHandlerRequestOptions\n ): Promise<Response>;\n notify: ServerNotifier;\n};\n\nexport type StatelessMcpServerInput = McpServerFactory;\n\nconst DEFAULT_CORS_OPTIONS: Required<CORSOptions> = {\n origin: \"*\",\n headers:\n \"Content-Type, Accept, Authorization, mcp-session-id, MCP-Protocol-Version, Mcp-Method, Mcp-Name\",\n methods: \"GET, POST, DELETE, OPTIONS\",\n exposeHeaders: \"mcp-session-id\",\n maxAge: 86400\n};\n\nfunction corsHeaders(options: CORSOptions = {}): Headers {\n const merged = { ...DEFAULT_CORS_OPTIONS, ...options };\n return new Headers({\n \"Access-Control-Allow-Headers\": merged.headers,\n \"Access-Control-Allow-Methods\": merged.methods,\n \"Access-Control-Allow-Origin\": merged.origin,\n \"Access-Control-Expose-Headers\": merged.exposeHeaders,\n \"Access-Control-Max-Age\": String(merged.maxAge)\n });\n}\n\nfunction withCors(response: Response, options: CORSOptions | false): Response {\n const headers = new Headers(response.headers);\n if (options === false) {\n for (const name of Array.from(headers.keys())) {\n if (name.toLowerCase().startsWith(\"access-control-\")) {\n headers.delete(name);\n }\n }\n } else {\n for (const [name, value] of corsHeaders(options)) {\n headers.set(name, value);\n }\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n}\n\nfunction wrapResponseBodyWithAuthContext(\n response: Response,\n authContext: McpAuthContext | undefined\n): Response {\n if (!authContext || !response.body) return response;\n\n const reader = response.body.getReader();\n const body = new ReadableStream<Uint8Array>({\n pull(controller) {\n return runWithAuthContext(authContext, async () => {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n });\n },\n cancel(reason) {\n return runWithAuthContext(authContext, () => reader.cancel(reason));\n }\n });\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers\n });\n}\n\nexport function createStatelessMcpHandler(\n factory: StatelessMcpServerInput,\n options: CreateStatelessMcpHandlerOptions = {}\n): StatelessMcpHandler {\n const optionRecord = options as Record<string, unknown>;\n if (optionRecord.bus !== undefined) {\n throw new TypeError(\n 'createMcpHandler option \"bus\" is not exposed by the Agents SDK.'\n );\n }\n const legacyOnlyOption = [\n \"transport\",\n \"storage\",\n \"sessionIdGenerator\",\n \"onsessioninitialized\",\n \"onsessionclosed\",\n \"enableJsonResponse\",\n \"eventStore\",\n \"allowedHosts\",\n \"allowedOrigins\",\n \"enableDnsRebindingProtection\",\n \"retryInterval\"\n ].find((key) => optionRecord[key] !== undefined);\n if (legacyOnlyOption) {\n throw new TypeError(\n `createMcpHandler option \"${legacyOnlyOption}\" is only supported with an MCP SDK v1 server. The managed SDK v2 handler is stateless; remove this option or keep the v1 server during migration.`\n );\n }\n\n const {\n route = \"/mcp\",\n corsOptions = {},\n allowedHostnames,\n allowedOriginHostnames,\n authContext,\n legacy = \"stateless\",\n ...sdkOptions\n } = options;\n\n const sdkHandler = createSdkMcpHandler(factory, {\n ...sdkOptions,\n legacy: \"reject\"\n });\n const legacyCompatibilityHandler =\n legacy === \"stateless\"\n ? createLegacyCompatibilityRequestHandler(factory, sdkOptions.onerror)\n : undefined;\n\n const serve = async (\n request: Request,\n requestOptions?: McpHandlerRequestOptions,\n workerCtx?: ExecutionContext\n ): Promise<Response> => {\n const requestUrl = new URL(request.url);\n if (requestUrl.pathname !== route) {\n return withCors(new Response(\"Not Found\", { status: 404 }), corsOptions);\n }\n\n // The SDK app factories can distinguish their bind address from an\n // attacker-controlled Host header. A bare Worker cannot. Use defaults we\n // can establish independently: localhost-class names, a standard\n // workers.dev route, and any concrete CORS Origin the application chose.\n // Custom-domain deployments can provide explicit Host and Origin lists.\n const localEndpoint = localhostAllowedHostnames().includes(\n requestUrl.hostname\n );\n const workersDevEndpoint = requestUrl.hostname.endsWith(\".workers.dev\");\n const acceptedHostnames =\n allowedHostnames ??\n (localEndpoint\n ? localhostAllowedHostnames()\n : workersDevEndpoint\n ? [requestUrl.hostname]\n : undefined);\n const hostRejection = acceptedHostnames\n ? hostHeaderValidationResponse(request, acceptedHostnames)\n : undefined;\n if (hostRejection) {\n return withCors(hostRejection, corsOptions);\n }\n if (allowedOriginHostnames !== \"*\") {\n let acceptedOriginHostnames = allowedOriginHostnames;\n if (acceptedOriginHostnames === undefined) {\n const defaults = new Set(localhostAllowedOrigins());\n if (workersDevEndpoint) defaults.add(requestUrl.hostname);\n if (corsOptions !== false && corsOptions.origin !== undefined) {\n try {\n const configuredOrigin = new URL(corsOptions.origin);\n if (\n (configuredOrigin.protocol === \"http:\" ||\n configuredOrigin.protocol === \"https:\") &&\n configuredOrigin.hostname\n ) {\n defaults.add(configuredOrigin.hostname);\n }\n } catch {\n // A wildcard or malformed CORS value does not expand the allowlist.\n }\n }\n acceptedOriginHostnames = [...defaults];\n }\n const originRejection = originValidationResponse(\n request,\n acceptedOriginHostnames ?? []\n );\n if (originRejection) {\n return withCors(originRejection, corsOptions);\n }\n }\n\n if (request.method === \"OPTIONS\" && corsOptions !== false) {\n return new Response(null, { headers: corsHeaders(corsOptions) });\n }\n\n const legacyRequest =\n legacyCompatibilityHandler !== undefined &&\n (await isLegacyRequest(request, requestOptions?.parsedBody));\n\n try {\n const verified = workerCtx\n ? getVerifiedOAuthAuthInfo(workerCtx)\n : undefined;\n const explicitAuthInfo = requestOptions?.authInfo;\n if (\n verified &&\n explicitAuthInfo &&\n explicitAuthInfo.clientId !== verified.authInfo.clientId\n ) {\n throw new TypeError(\"Conflicting verified OAuth client identity\");\n }\n\n const authInfo: AuthInfo | undefined =\n explicitAuthInfo ?? verified?.authInfo;\n const resolvedAuthContext =\n authContext ??\n (verified\n ? { props: verified.props }\n : workerCtx?.props && Object.keys(workerCtx.props).length > 0\n ? { props: workerCtx.props as Record<string, unknown> }\n : undefined);\n const upstreamOptions: McpHandlerRequestOptions | undefined =\n requestOptions || authInfo\n ? { ...requestOptions, ...(authInfo && { authInfo }) }\n : undefined;\n const invoke = async () => {\n if (legacyRequest && legacyCompatibilityHandler) {\n return legacyCompatibilityHandler.fetch(request, upstreamOptions);\n }\n return sdkHandler.fetch(request, upstreamOptions);\n };\n const response = resolvedAuthContext\n ? await runWithAuthContext(resolvedAuthContext, invoke)\n : await invoke();\n return withCors(\n wrapResponseBodyWithAuthContext(response, resolvedAuthContext),\n corsOptions\n );\n } catch (error) {\n reportHandlerError(sdkOptions.onerror, error);\n return withCors(internalErrorResponse(), corsOptions);\n }\n };\n\n const callable = (request: Request, _env: unknown, ctx: ExecutionContext) =>\n serve(request, undefined, ctx);\n const fetch = (request: Request, requestOptions?: McpHandlerRequestOptions) =>\n serve(request, requestOptions);\n\n return Object.assign(callable, {\n fetch,\n notify: sdkHandler.notify\n }) as StatelessMcpHandler;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,wBAAwB;;AAGrC,MAAa,kBAAkB;;;;;AAM/B,SAAgB,eACd,QACA,SACgC;CAChC,MAAM,SAAS,kBAAkB;EAC/B,OACG,MAAM,QAAQ,OAAO,eAAe,CAAC,CAAC,CACtC,YAAY,cAAc,MAAM,CAAC;CACtC,GAAG,qBAAqB;CACxB,OAAO;AACT;;;AClCA,MAAM,yBAAyB,OAAO,IACpC,uDACF;AAgBA,MAAM,qBAAqB,IAAI,kBAAkC;AAEjE,SAAgB,oBAAgD;CAC9D,OAAO,mBAAmB,SAAS;AACrC;AAEA,SAAgB,mBAAsB,SAAyB,IAAgB;CAC7E,OAAO,mBAAmB,IAAI,SAAS,EAAE;AAC3C;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CAET,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,yBAAgC;CACvC,MAAM,IAAI,UAAU,wCAAwC;AAC9D;AAEA,SAAgB,yBACd,KACoE;CACpE,MAAM,gBAAgB;CACtB,IAAI,EAAE,0BAA0B,gBAAgB,OAAO,KAAA;CAEvD,MAAM,QAAQ,cAAc;CAC5B,IAAI,CAAC,cAAc,KAAK,KAAK,MAAM,YAAY,GAAG,uBAAuB;CAGzE,MAAM,EAAE,OAAO,UAAU,QAAQ,WAAW,UAAU,UAAUA;CAChE,IACE,OAAO,UAAU,YACjB,MAAM,WAAW,KACjB,OAAO,aAAa,YACpB,SAAS,WAAW,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