agents 0.30.1 → 0.31.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 (126) hide show
  1. package/README.md +2 -1
  2. package/dist/{agent-routing-CDbpVjYq.d.ts → agent-routing-wS1TimZ_.d.ts} +64 -603
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-C8DH8Yii.d.ts → agent-tools-Bamxxb6Y.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-iXw0uOGj.d.ts → ai-CDn3Abax.d.ts} +30 -4
  8. package/dist/{ai-sdk-DRPh2rRa.js → ai-sdk-Kon40i0q.js} +2 -36
  9. package/dist/ai-sdk-Kon40i0q.js.map +1 -0
  10. package/dist/ai-sdk-hW3vntnk.d.ts +72 -0
  11. package/dist/browser/ai.d.ts +1 -1
  12. package/dist/browser/ai.js +16 -3
  13. package/dist/browser/ai.js.map +1 -1
  14. package/dist/browser/index.d.ts +64 -16
  15. package/dist/browser/index.js +4 -4
  16. package/dist/browser/tools/ai-sdk.d.ts +7 -70
  17. package/dist/browser/tools/ai-sdk.js +4 -4
  18. package/dist/browser/tools/ai-sdk.js.map +1 -1
  19. package/dist/browser/tools/pi.d.ts +9 -15
  20. package/dist/browser/tools/pi.js +6 -14
  21. package/dist/browser/tools/pi.js.map +1 -1
  22. package/dist/browser/tools/tanstack-ai.d.ts +46 -23
  23. package/dist/browser/tools/tanstack-ai.js +8 -4
  24. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  25. package/dist/{browser-DccPw_wW.js → browser-1eUbPvC2.js} +413 -14
  26. package/dist/browser-1eUbPvC2.js.map +1 -0
  27. package/dist/{browser-DlXhSAdf.d.ts → browser-D9RNpJuT.d.ts} +254 -20
  28. package/dist/browser-tool-BhjCcNVE.d.ts +71 -0
  29. package/dist/browser-tool-lGnvEBLJ.js +497 -0
  30. package/dist/browser-tool-lGnvEBLJ.js.map +1 -0
  31. package/dist/capability-id-B3J8Nok_.js +13 -0
  32. package/dist/capability-id-B3J8Nok_.js.map +1 -0
  33. package/dist/chat/index.d.ts +2 -2
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/client-4OlMIJx-.js.map +1 -1
  37. package/dist/{client-BnYbNT3z.js → client-DMWujQJ1.js} +68 -244
  38. package/dist/client-DMWujQJ1.js.map +1 -0
  39. package/dist/{client-C27CtRZr.d.ts → client-wn4-yqGz.d.ts} +9 -7
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-DAXBOIIi.js → connector-CM-uuxKM.js} +96 -8
  42. package/dist/connector-CM-uuxKM.js.map +1 -0
  43. package/dist/{connector-20DJ6p4k.d.ts → connector-DZ71EjE-.d.ts} +109 -9
  44. package/dist/experimental/webmcp.js +1 -1
  45. package/dist/{handler-stateless-Bly_nSH3.js → handler-stateless-B5hU3dxK.js} +35 -2
  46. package/dist/handler-stateless-B5hU3dxK.js.map +1 -0
  47. package/dist/{handler-stateless-DxYpJ_XF.d.ts → handler-stateless-C90kD5_R.d.ts} +3 -47
  48. package/dist/harness/container/index.d.ts +15 -15
  49. package/dist/harness/opencode/index.js.map +1 -1
  50. package/dist/harness/pi/index.d.ts +4 -3
  51. package/dist/harness/pi/index.js +31 -10
  52. package/dist/harness/pi/index.js.map +1 -1
  53. package/dist/harness/think/index.d.ts +2 -1
  54. package/dist/{images-xaDv2Fqe.js → images-CfuRCjwq.js} +1 -5
  55. package/dist/images-CfuRCjwq.js.map +1 -0
  56. package/dist/{index-DCxk3OSJ.d.ts → index-8k4qsX1T.d.ts} +2 -28
  57. package/dist/index.d.ts +14 -14
  58. package/dist/index.js +2 -2
  59. package/dist/internal-hosts-Kfp5A392.d.ts +230 -0
  60. package/dist/internal-kmw70xwR.js.map +1 -1
  61. package/dist/invoker-BC1SZ3q1.js +26 -0
  62. package/dist/invoker-BC1SZ3q1.js.map +1 -0
  63. package/dist/invoker-DoLFPJZV.d.ts +21 -0
  64. package/dist/mcp/client/index.d.ts +15 -1
  65. package/dist/mcp/client/index.js +2 -2
  66. package/dist/mcp/client/x402.d.ts +7 -5
  67. package/dist/mcp/client/x402.js +34 -1
  68. package/dist/mcp/client/x402.js.map +1 -1
  69. package/dist/mcp/index.d.ts +561 -27
  70. package/dist/mcp/index.js +180 -3
  71. package/dist/mcp/index.js.map +1 -1
  72. package/dist/mcp/server/index.d.ts +1 -1
  73. package/dist/mcp/server/index.js +1 -1
  74. package/dist/models/ai-sdk/index.d.ts +2 -2
  75. package/dist/models/ai-sdk/index.js +1 -1
  76. package/dist/models/opencode/index.d.ts +2 -2
  77. package/dist/models/opencode/index.js +1 -1
  78. package/dist/models/pi-ai/index.d.ts +3 -28
  79. package/dist/models/pi-ai/index.js +31 -16
  80. package/dist/models/pi-ai/index.js.map +1 -1
  81. package/dist/protocol-BEgrJYC5.d.ts +29 -29
  82. package/dist/react.d.ts +2 -2
  83. package/dist/routing/index.d.ts +1 -1
  84. package/dist/serializable.d.ts +1 -1
  85. package/dist/{session-store-yvwq1f9x.js → session-7CDgVE0z.js} +455 -33
  86. package/dist/session-7CDgVE0z.js.map +1 -0
  87. package/dist/{session-store-_IK6dV-w.d.ts → session-store-B7Ca-u1t.d.ts} +8 -1
  88. package/dist/settings-Dk2il2Hf.js.map +1 -1
  89. package/dist/{src-DfLzdwlK.js → src-BGolXG_H.js} +18 -2
  90. package/dist/src-BGolXG_H.js.map +1 -0
  91. package/dist/sub-routing.d.ts +12 -12
  92. package/dist/tool-CTp72Jb_.d.ts +10 -10
  93. package/dist/tool-DoVberpN.d.ts +22 -22
  94. package/dist/tool-helpers-BodWi4gd.js +256 -0
  95. package/dist/tool-helpers-BodWi4gd.js.map +1 -0
  96. package/dist/{transport-CPh7YGiw.d.ts → transport-5moD2pW5.d.ts} +1 -43
  97. package/dist/types-D2naO3rA.d.ts +49 -0
  98. package/dist/voice/index.d.ts +1 -1
  99. package/dist/workflow-types.d.ts +1 -1
  100. package/dist/workflows.d.ts +1 -1
  101. package/dist/workflows.js +1 -1
  102. package/docs/browse-the-web.md +247 -413
  103. package/docs/harnesses/pi.md +27 -27
  104. package/docs/index.md +4 -4
  105. package/docs/mcp-client.md +2 -0
  106. package/docs/mcp-servers.md +25 -6
  107. package/docs/models-pi-ai.md +9 -11
  108. package/docs/models.md +1 -8
  109. package/docs/securing-mcp-servers.md +113 -302
  110. package/package.json +8 -3
  111. package/dist/ai-sdk-DRPh2rRa.js.map +0 -1
  112. package/dist/browser-DccPw_wW.js.map +0 -1
  113. package/dist/browser-tool-B1mhifin.js +0 -616
  114. package/dist/browser-tool-B1mhifin.js.map +0 -1
  115. package/dist/browser-tool-Cxjk5sgG.d.ts +0 -92
  116. package/dist/client-BnYbNT3z.js.map +0 -1
  117. package/dist/connector-DAXBOIIi.js.map +0 -1
  118. package/dist/handler-stateless-Bly_nSH3.js.map +0 -1
  119. package/dist/images-xaDv2Fqe.js.map +0 -1
  120. package/dist/invoker-CG0_p_Wq.d.ts +0 -20
  121. package/dist/invoker-CHMnoxIA.js +0 -57
  122. package/dist/invoker-CHMnoxIA.js.map +0 -1
  123. package/dist/session-store-yvwq1f9x.js.map +0 -1
  124. package/dist/src-DfLzdwlK.js.map +0 -1
  125. package/dist/tool-helpers-O5BDVEAY.js +0 -58
  126. package/dist/tool-helpers-O5BDVEAY.js.map +0 -1
@@ -0,0 +1,230 @@
1
+ import { WorkerEntrypoint } from "cloudflare:workers";
2
+
3
+ //#region src/browser/internal-hosts.d.ts
4
+ /** The most hostnames one browser can have. A Browser Run limit. */
5
+ declare const MAX_INTERNAL_HOSTS = 8;
6
+ /** A Standard Schema: something that validates a value. */
7
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ readonly "~standard": {
9
+ readonly version: 1;
10
+ readonly vendor: string;
11
+ readonly validate: (
12
+ value: unknown
13
+ ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
14
+ readonly types?:
15
+ | {
16
+ readonly input: Input;
17
+ readonly output: Output;
18
+ }
19
+ | undefined;
20
+ };
21
+ }
22
+ type StandardSchemaResult<Output> =
23
+ | {
24
+ readonly value: Output;
25
+ readonly issues?: undefined;
26
+ }
27
+ | {
28
+ readonly issues: ReadonlyArray<{
29
+ readonly message: string;
30
+ readonly path?: ReadonlyArray<
31
+ | PropertyKey
32
+ | {
33
+ readonly key: PropertyKey;
34
+ }
35
+ >;
36
+ }>;
37
+ };
38
+ /** A Standard JSON Schema: something that can describe itself as JSON Schema. */
39
+ interface StandardJSONSchemaV1 {
40
+ readonly "~standard": {
41
+ readonly jsonSchema: {
42
+ readonly input: (options: {
43
+ readonly target: string;
44
+ }) => Record<string, unknown>;
45
+ };
46
+ };
47
+ }
48
+ /** A typed schema: validates (Standard Schema) and describes itself (Standard JSON Schema). */
49
+ type TypedTargetSchema = StandardSchemaV1 & StandardJSONSchemaV1;
50
+ /** A plain JSON Schema object, such as TypeBox output or a hand-written one. */
51
+ type JsonSchemaObject = {
52
+ readonly [key: string]: unknown;
53
+ };
54
+ /**
55
+ * What the model passes to `browser.assignHost()` for a host. A typed schema (zod
56
+ * 4.2+, ArkType, Valibot) types `fetch`'s `target`; a plain JSON Schema
57
+ * leaves it `unknown`.
58
+ */
59
+ type TargetSchema = TypedTargetSchema | JsonSchemaObject;
60
+ /** The value a schema validates to: typed for a Standard Schema, else `unknown`. */
61
+ type TargetOf<S> =
62
+ S extends StandardSchemaV1<unknown, infer Output> ? Output : unknown;
63
+ /** A host served by code in your agent. */
64
+ interface InternalHost<S = unknown> {
65
+ /** Shown to the model next to the hostname. */
66
+ description?: string;
67
+ /**
68
+ * What the model passes to `browser.assignHost()` to point this host somewhere,
69
+ * as a schema. Omit it for a host that always serves the same thing.
70
+ *
71
+ * The model picks this value, so if part of it becomes a path, URL or
72
+ * command in `fetch`, limit it in the schema (an enum, a pattern, a range)
73
+ * rather than trusting it.
74
+ */
75
+ target?: S & TargetSchema;
76
+ /**
77
+ * Serves every browser request to this hostname. Runs in your agent, with
78
+ * the target the model last assigned (validated by `target`), or
79
+ * `undefined` when the host has no `target` schema.
80
+ *
81
+ * Any http page open in the browser can send requests here, not only
82
+ * pages on this host: a page on another internal hostname, or an http
83
+ * site the guardrails allow, can POST to `http://preview.internal`. Chrome
84
+ * doesn't send `Sec-Fetch-*` headers to http hosts, so if a request has
85
+ * side effects, check that its `Origin` is this host.
86
+ *
87
+ * If it throws, the browser gets a 502 and the error is logged, not shown
88
+ * to the page.
89
+ */
90
+ fetch: (request: Request, target: TargetOf<S>) => Promise<Response>;
91
+ worker?: never;
92
+ }
93
+ /**
94
+ * A host served by a deployed Worker directly, without going through your
95
+ * agent: a service binding, or an entrypoint of your own Worker. Not a
96
+ * Dynamic Worker or Durable Object stub — Browser Run can't hold those.
97
+ */
98
+ interface InternalWorkerHost {
99
+ /** Shown to the model next to the hostname. */
100
+ description?: string;
101
+ /**
102
+ * The Worker that serves this hostname: a service binding, or an
103
+ * entrypoint of your own Worker. Requests go straight to it, without
104
+ * waking your agent.
105
+ *
106
+ * An entrypoint passed as is (`this.ctx.exports.DocsSite`) is called with
107
+ * empty props; to give it props, call it yourself
108
+ * (`this.ctx.exports.DocsSite({ props })`). A Durable Object stub doesn't
109
+ * type-check: Browser Run accepts one, then resets every request.
110
+ */
111
+ worker: Fetcher & {
112
+ id?: never;
113
+ };
114
+ target?: never;
115
+ fetch?: never;
116
+ }
117
+ /** The entrypoint loopback for {@link InternalHostRouter}: `this.ctx.exports.InternalHostRouter`. */
118
+ type InternalHostRouterLoopback = (init: {
119
+ props: InternalHostRouterProps;
120
+ }) => Fetcher;
121
+ /**
122
+ * `browserRun()`'s `internalHosts`: hostnames only this browser can open.
123
+ *
124
+ * Fixed when a browser starts. Adding or removing a hostname replaces the
125
+ * browser (the model sees `restarted`); changing a host's `fetch`,
126
+ * `description` or `target` doesn't. Nor does pointing a `worker` host at
127
+ * a different Worker: the running browser keeps the old one until it is
128
+ * replaced, so call `browser.close()` after such a change.
129
+ */
130
+ interface InternalHostsOptions<S = Record<string, unknown>> {
131
+ /**
132
+ * Your Worker's {@link InternalHostRouter} export, as
133
+ * `this.ctx.exports.InternalHostRouter`. Needed for `fetch` hosts.
134
+ */
135
+ router?: InternalHostRouterLoopback;
136
+ /**
137
+ * At most {@link MAX_INTERNAL_HOSTS} hostnames: bare and lowercase, no
138
+ * scheme, port, or path, ending in a suffix that can't be a real site:
139
+ * `.internal`, `.test`, `.example` or `.invalid`, like `preview.internal`.
140
+ */
141
+ hosts: { [K in keyof S]: InternalHost<S[K]> | InternalWorkerHost };
142
+ }
143
+ /** One host, as the host API and the model see it. */
144
+ interface InternalHostInfo {
145
+ /** The hostname, such as `preview.internal`. */
146
+ host: string;
147
+ /** Where the browser opens it: `http://<host>/`. */
148
+ url: string;
149
+ description?: string;
150
+ /** Whether the model can point it somewhere with `browser.assignHost()`. */
151
+ assignable: boolean;
152
+ /** The JSON Schema `browser.assignHost()` checks the target against. */
153
+ targetSchema?: Record<string, unknown>;
154
+ /** The target last assigned, as assigned (before the schema transforms it). */
155
+ target?: unknown;
156
+ }
157
+ /**
158
+ * What {@link InternalHostRouter} is given for one hostname: which agent and
159
+ * browser own it. Browser Run keeps these for the whole session, across
160
+ * redeploys, so they hold names only, never secrets or config.
161
+ */
162
+ type InternalHostRouterProps = {
163
+ readonly v: 1 /** The agent's class name, as exported from the Worker. */;
164
+ readonly className: string /** The agent's name. */;
165
+ readonly name: string /** The name of the `Browser` that owns the host. */;
166
+ readonly browser: string /** The hostname this route serves. */;
167
+ readonly host: string;
168
+ };
169
+ /**
170
+ * One browser request to an internal hostname, as {@link InternalHostRouter}
171
+ * hands it to the agent's `fetchInternalHost()`.
172
+ *
173
+ * `Agent` has `fetchInternalHost()` built in. A plain Durable Object adds it
174
+ * and passes the message to its `Browser`:
175
+ *
176
+ * ```ts
177
+ * fetchInternalHost(message: InternalHostMessage) {
178
+ * return this.browser.fetchInternalHost(message);
179
+ * }
180
+ * ```
181
+ */
182
+ type InternalHostMessage = {
183
+ /** The name of the `Browser` that owns the host. */ readonly browser: string /** The hostname, such as `preview.internal`. */;
184
+ readonly host: string /** The browser's request. */;
185
+ readonly request: Request;
186
+ };
187
+ /**
188
+ * Carries a browser's requests for an internal hostname to the agent that
189
+ * owns it. Export it from your Worker's main module, so
190
+ * `this.ctx.exports.InternalHostRouter` exists:
191
+ *
192
+ * ```ts
193
+ * export { InternalHostRouter } from "agents/browser";
194
+ * ```
195
+ *
196
+ * It trusts its props: Browser Run sets them from your routes, but another
197
+ * Worker in your account with a service binding to this entrypoint could
198
+ * set its own and reach any agent's hosts. That Worker could already call
199
+ * your agents directly, so this grants nothing new.
200
+ *
201
+ * It holds no logic of its own: it calls the agent's `fetchInternalHost()`
202
+ * with an {@link InternalHostMessage}, and the agent's `Browser` runs the
203
+ * host's `fetch`. `Agent` has `fetchInternalHost()` built in; a plain
204
+ * Durable Object adds it (see {@link InternalHostMessage}).
205
+ *
206
+ * @experimental The API may change before it stabilizes.
207
+ */
208
+ declare class InternalHostRouter extends WorkerEntrypoint<
209
+ unknown,
210
+ InternalHostRouterProps
211
+ > {
212
+ fetch(request: Request): Promise<Response>;
213
+ }
214
+ //#endregion
215
+ export {
216
+ InternalHostRouterLoopback as a,
217
+ InternalWorkerHost as c,
218
+ TargetOf as d,
219
+ TargetSchema as f,
220
+ InternalHostRouter as i,
221
+ JsonSchemaObject as l,
222
+ InternalHostInfo as n,
223
+ InternalHostRouterProps as o,
224
+ TypedTargetSchema as p,
225
+ InternalHostMessage as r,
226
+ InternalHostsOptions as s,
227
+ InternalHost as t,
228
+ MAX_INTERNAL_HOSTS as u
229
+ };
230
+ //# sourceMappingURL=internal-hosts-Kfp5A392.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-kmw70xwR.js","names":[],"sources":["../src/experimental/channels/internal.ts"],"sourcesContent":["import type {\n ChannelMessage,\n DeliveryResult,\n ParticipantResult\n} from \"./channel\";\nimport type { ChannelIngressResult } from \"./ingress\";\nimport type { Participant } from \"./protocol\";\n\nconst textEncoder = new TextEncoder();\n\nexport function encodeUtf8(value: string): Uint8Array<ArrayBuffer> {\n return textEncoder.encode(value);\n}\n\nexport function utf8ByteLength(value: string): number {\n return encodeUtf8(value).byteLength;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function defaultText(message: ChannelMessage): string {\n return message.title\n ? `${message.title}\\n\\n${message.markdown}`\n : message.markdown;\n}\n\nexport function renderInput(input: unknown): string {\n if (typeof input === \"string\") return input;\n try {\n return JSON.stringify(input, null, 2) ?? String(input);\n } catch {\n return String(input);\n }\n}\n\nexport function uncertain(\n code: string,\n message: string,\n reference?: string\n): Extract<DeliveryResult, { status: \"uncertain\" }> {\n return {\n status: \"uncertain\",\n ...(reference !== undefined && { reference }),\n error: { code, message }\n };\n}\n\nexport function emptyIngressResponse<TRaw>(\n status = 200\n): ChannelIngressResult<TRaw> {\n return { events: [], response: new Response(null, { status }) };\n}\n\nexport function unsupported(\n code: string,\n message: string\n): Extract<DeliveryResult, { status: \"failed\" }> {\n return {\n status: \"failed\",\n retryable: false,\n error: { code, message }\n };\n}\n\n/** The agent object of a participant's own, namespaced so app routes cannot collide. */\nexport function participantRoute(participant: Participant): string {\n return `participant:${participant.id}`;\n}\n\n/** Check what an application's `participant` callback returned. */\nexport function toParticipant(\n result: ParticipantResult,\n source: string\n): Participant | null {\n if (result === null) return null;\n if (typeof result === \"string\") {\n if (result.length > 0) return { id: result };\n } else if (\n isRecord(result) &&\n typeof result.id === \"string\" &&\n result.id.length > 0 &&\n (result.name === undefined || typeof result.name === \"string\")\n ) {\n return result.name === undefined\n ? { id: result.id }\n : { id: result.id, name: result.name };\n }\n throw new Error(\n `${source} participant must return a non-empty id, a participant, or null`\n );\n}\n"],"mappings":";AAQA,MAAM,cAAc,IAAI,YAAY;AAEpC,SAAgB,WAAW,OAAwC;CACjE,OAAO,YAAY,OAAO,KAAK;AACjC;AAEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,WAAW,KAAK,CAAC,CAAC;AAC3B;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AA6BA,SAAgB,qBACd,SAAS,KACmB;CAC5B,OAAO;EAAE,QAAQ,CAAC;EAAG,UAAU,IAAI,SAAS,MAAM,EAAE,OAAO,CAAC;CAAE;AAChE;AAEA,SAAgB,YACd,MACA,SAC+C;CAC/C,OAAO;EACL,QAAQ;EACR,WAAW;EACX,OAAO;GAAE;GAAM;EAAQ;CACzB;AACF;;AAGA,SAAgB,iBAAiB,aAAkC;CACjE,OAAO,eAAe,YAAY;AACpC;;AAGA,SAAgB,cACd,QACA,QACoB;CACpB,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,WAAW;MAChB,OAAO,SAAS,GAAG,OAAO,EAAE,IAAI,OAAO;CAAA,OACtC,IACL,SAAS,MAAM,KACf,OAAO,OAAO,OAAO,YACrB,OAAO,GAAG,SAAS,MAClB,OAAO,SAAS,KAAA,KAAa,OAAO,OAAO,SAAS,WAErD,OAAO,OAAO,SAAS,KAAA,IACnB,EAAE,IAAI,OAAO,GAAG,IAChB;EAAE,IAAI,OAAO;EAAI,MAAM,OAAO;CAAK;CAEzC,MAAM,IAAI,MACR,GAAG,OAAO,gEACZ;AACF"}
1
+ {"version":3,"file":"internal-kmw70xwR.js","names":[],"sources":["../src/experimental/channels/internal.ts"],"sourcesContent":["import type { DeliveryResult, ParticipantResult } from \"./channel\";\nimport type { ChannelIngressResult } from \"./ingress\";\nimport type { Participant } from \"./protocol\";\n\nconst textEncoder = new TextEncoder();\n\nexport function encodeUtf8(value: string): Uint8Array<ArrayBuffer> {\n return textEncoder.encode(value);\n}\n\nexport function utf8ByteLength(value: string): number {\n return encodeUtf8(value).byteLength;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function emptyIngressResponse<TRaw>(\n status = 200\n): ChannelIngressResult<TRaw> {\n return { events: [], response: new Response(null, { status }) };\n}\n\nexport function unsupported(\n code: string,\n message: string\n): Extract<DeliveryResult, { status: \"failed\" }> {\n return {\n status: \"failed\",\n retryable: false,\n error: { code, message }\n };\n}\n\n/** The agent object of a participant's own, namespaced so app routes cannot collide. */\nexport function participantRoute(participant: Participant): string {\n return `participant:${participant.id}`;\n}\n\n/** Check what an application's `participant` callback returned. */\nexport function toParticipant(\n result: ParticipantResult,\n source: string\n): Participant | null {\n if (result === null) return null;\n if (typeof result === \"string\") {\n if (result.length > 0) return { id: result };\n } else if (\n isRecord(result) &&\n typeof result.id === \"string\" &&\n result.id.length > 0 &&\n (result.name === undefined || typeof result.name === \"string\")\n ) {\n return result.name === undefined\n ? { id: result.id }\n : { id: result.id, name: result.name };\n }\n throw new Error(\n `${source} participant must return a non-empty id, a participant, or null`\n );\n}\n"],"mappings":";AAIA,MAAM,cAAc,IAAI,YAAY;AAEpC,SAAgB,WAAW,OAAwC;CACjE,OAAO,YAAY,OAAO,KAAK;AACjC;AAEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,WAAW,KAAK,CAAC,CAAC;AAC3B;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,qBACd,SAAS,KACmB;CAC5B,OAAO;EAAE,QAAQ,CAAC;EAAG,UAAU,IAAI,SAAS,MAAM,EAAE,OAAO,CAAC;CAAE;AAChE;AAEA,SAAgB,YACd,MACA,SAC+C;CAC/C,OAAO;EACL,QAAQ;EACR,WAAW;EACX,OAAO;GAAE;GAAM;EAAQ;CACzB;AACF;;AAGA,SAAgB,iBAAiB,aAAkC;CACjE,OAAO,eAAe,YAAY;AACpC;;AAGA,SAAgB,cACd,QACA,QACoB;CACpB,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,WAAW;MAChB,OAAO,SAAS,GAAG,OAAO,EAAE,IAAI,OAAO;CAAA,OACtC,IACL,SAAS,MAAM,KACf,OAAO,OAAO,OAAO,YACrB,OAAO,GAAG,SAAS,MAClB,OAAO,SAAS,KAAA,KAAa,OAAO,OAAO,SAAS,WAErD,OAAO,OAAO,SAAS,KAAA,IACnB,EAAE,IAAI,OAAO,GAAG,IAChB;EAAE,IAAI,OAAO;EAAI,MAAM,OAAO;CAAK;CAEzC,MAAM,IAAI,MACR,GAAG,OAAO,gEACZ;AACF"}
@@ -0,0 +1,26 @@
1
+ //#region src/mcp/client/invoker.ts
2
+ function isLegacyResultSchema(value) {
3
+ return typeof value?.parse === "function";
4
+ }
5
+ function normalizeCallToolArguments(schemaOrOptions, options) {
6
+ return isLegacyResultSchema(schemaOrOptions) ? {
7
+ schema: schemaOrOptions,
8
+ options
9
+ } : { options: schemaOrOptions ?? options };
10
+ }
11
+ /**
12
+ * Invoke SDK v2 while preserving the deprecated v1 result-schema overload.
13
+ * The v2 request funnel still owns decoding and automatic MRTR.
14
+ */
15
+ function callV2Tool(client, params, schemaOrOptions, options) {
16
+ const normalized = normalizeCallToolArguments(schemaOrOptions, options);
17
+ if (normalized.schema) return client.request({
18
+ method: "tools/call",
19
+ params
20
+ }, normalized.schema, normalized.options);
21
+ return client.callTool(params, normalized.options);
22
+ }
23
+ //#endregion
24
+ export { normalizeCallToolArguments as n, callV2Tool as t };
25
+
26
+ //# sourceMappingURL=invoker-BC1SZ3q1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoker-BC1SZ3q1.js","names":[],"sources":["../src/mcp/client/invoker.ts"],"sourcesContent":["import type {\n CallToolRequest,\n CallToolRequestOptions,\n CallToolResult,\n Client\n} from \"@modelcontextprotocol/client\";\n\n/**\n * A v1 result schema such as `CallToolResultSchema` or\n * `CompatibilityCallToolResultSchema` from `@modelcontextprotocol/sdk`.\n *\n * Typed structurally so the MCP client (reachable from the root `agents`\n * entry) does not depend on `@modelcontextprotocol/sdk`, which is an optional\n * peer.\n */\nexport type LegacyCallToolResultSchema = {\n parse(data: unknown): unknown;\n};\n\nexport type CallToolSchemaOrOptions =\n | LegacyCallToolResultSchema\n | CallToolRequestOptions;\n\nfunction isLegacyResultSchema(\n value: CallToolSchemaOrOptions | undefined\n): value is LegacyCallToolResultSchema {\n return (\n typeof (value as { parse?: unknown } | undefined)?.parse === \"function\"\n );\n}\n\nexport function normalizeCallToolArguments(\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n): {\n schema?: LegacyCallToolResultSchema;\n options?: CallToolRequestOptions;\n} {\n return isLegacyResultSchema(schemaOrOptions)\n ? { schema: schemaOrOptions, options }\n : { options: schemaOrOptions ?? options };\n}\n\n/**\n * Invoke SDK v2 while preserving the deprecated v1 result-schema overload.\n * The v2 request funnel still owns decoding and automatic MRTR.\n */\nexport function callV2Tool(\n client: Client,\n params: CallToolRequest[\"params\"],\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n): Promise<CallToolResult> {\n const normalized = normalizeCallToolArguments(schemaOrOptions, options);\n if (normalized.schema) {\n return client.request(\n { method: \"tools/call\", params },\n normalized.schema as never,\n normalized.options\n ) as Promise<CallToolResult>;\n }\n return client.callTool(params, normalized.options);\n}\n"],"mappings":";AAuBA,SAAS,qBACP,OACqC;CACrC,OACE,OAAQ,OAA2C,UAAU;AAEjE;AAEA,SAAgB,2BACd,iBACA,SAIA;CACA,OAAO,qBAAqB,eAAe,IACvC;EAAE,QAAQ;EAAiB;CAAQ,IACnC,EAAE,SAAS,mBAAmB,QAAQ;AAC5C;;;;;AAMA,SAAgB,WACd,QACA,QACA,iBACA,SACyB;CACzB,MAAM,aAAa,2BAA2B,iBAAiB,OAAO;CACtE,IAAI,WAAW,QACb,OAAO,OAAO,QACZ;EAAE,QAAQ;EAAc;CAAO,GAC/B,WAAW,QACX,WAAW,OACb;CAEF,OAAO,OAAO,SAAS,QAAQ,WAAW,OAAO;AACnD"}
@@ -0,0 +1,21 @@
1
+ import {
2
+ CallToolRequest,
3
+ CallToolRequestOptions,
4
+ Client
5
+ } from "@modelcontextprotocol/client";
6
+
7
+ //#region src/mcp/client/invoker.d.ts
8
+ /**
9
+ * A v1 result schema such as `CallToolResultSchema` or
10
+ * `CompatibilityCallToolResultSchema` from `@modelcontextprotocol/sdk`.
11
+ *
12
+ * Typed structurally so the MCP client (reachable from the root `agents`
13
+ * entry) does not depend on `@modelcontextprotocol/sdk`, which is an optional
14
+ * peer.
15
+ */
16
+ type LegacyCallToolResultSchema = {
17
+ parse(data: unknown): unknown;
18
+ };
19
+ //#endregion
20
+ export { LegacyCallToolResultSchema as t };
21
+ //# sourceMappingURL=invoker-DoLFPJZV.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import {
2
+ $t as RPCClientTransportOptions,
2
3
  At as ElicitRequest,
3
4
  Bt as MCPConnectionResult,
4
5
  Ft as MCPClientElicitationHandlers,
@@ -11,14 +12,20 @@ import {
11
12
  Mt as MCPAITool,
12
13
  Nt as MCPAIToolSet,
13
14
  Pt as MCPClientElicitationHandler,
15
+ Qt as RPCClientTransport,
14
16
  Rt as MCPClientOAuthCallbackConfig,
15
17
  Ut as MCPServerFilter,
16
18
  Vt as MCPDiscoverResult,
17
19
  Wt as MCPServerOptions,
20
+ Xt as MCPElicitationHandlers,
21
+ Yt as MCPElicitationHandler,
22
+ Zt as McpRpcAgent,
23
+ en as RPC_DO_PREFIX,
18
24
  jt as ElicitResult,
19
25
  qt as getNamespacedData,
20
26
  zt as MCPClientOAuthResult
21
- } from "../../agent-routing-CDbpVjYq.js";
27
+ } from "../../agent-routing-wS1TimZ_.js";
28
+ import { i as McpClientOptions } from "../../types-D2naO3rA.js";
22
29
  export {
23
30
  type ElicitRequest,
24
31
  type ElicitResult,
@@ -32,10 +39,17 @@ export {
32
39
  MCPClientOAuthResult,
33
40
  MCPConnectionResult,
34
41
  MCPDiscoverResult,
42
+ type MCPElicitationHandler,
43
+ type MCPElicitationHandlers,
35
44
  MCPOAuthCallbackResult,
36
45
  MCPServerFilter,
37
46
  MCPServerOptions,
38
47
  MCP_SERVER_ID_MAX_LENGTH,
48
+ type McpClientOptions,
49
+ type McpRpcAgent,
50
+ RPCClientTransport,
51
+ type RPCClientTransportOptions,
52
+ RPC_DO_PREFIX,
39
53
  RegisterServerOptions,
40
54
  getNamespacedData,
41
55
  normalizeServerId
@@ -1,2 +1,2 @@
1
- import { i as normalizeServerId, n as MCP_SERVER_ID_MAX_LENGTH, r as getNamespacedData, t as MCPClientManager } from "../../client-BnYbNT3z.js";
2
- export { MCPClientManager, MCP_SERVER_ID_MAX_LENGTH, getNamespacedData, normalizeServerId };
1
+ import { c as RPCClientTransport, i as normalizeServerId, l as RPC_DO_PREFIX, n as MCP_SERVER_ID_MAX_LENGTH, r as getNamespacedData, t as MCPClientManager } from "../../client-DMWujQJ1.js";
2
+ export { MCPClientManager, MCP_SERVER_ID_MAX_LENGTH, RPCClientTransport, RPC_DO_PREFIX, getNamespacedData, normalizeServerId };
@@ -1,12 +1,11 @@
1
- import {
2
- n as LegacyCallToolResultSchema,
3
- t as CompatibleMcpClient
4
- } from "../../invoker-CG0_p_Wq.js";
1
+ import { t as LegacyCallToolResultSchema } from "../../invoker-DoLFPJZV.js";
5
2
  import { ZodRawShape, z } from "zod";
6
3
  import {
7
4
  CallToolRequest,
8
- CallToolRequestOptions
5
+ CallToolRequestOptions,
6
+ Client
9
7
  } from "@modelcontextprotocol/client";
8
+ import { Client as Client$1 } from "@modelcontextprotocol/sdk/client/index.js";
10
9
  import {
11
10
  CallToolResult,
12
11
  ToolAnnotations
@@ -38,6 +37,9 @@ import {
38
37
  ClientEvmSigner as ClientEvmSigner$1
39
38
  } from "@x402/evm";
40
39
 
40
+ //#region src/mcp/client/invoker-compat.d.ts
41
+ type CompatibleMcpClient = Client | Client$1;
42
+ //#endregion
41
43
  //#region src/mcp/client/x402.d.ts
42
44
  /**
43
45
  * Normalize a network identifier to CAIP-2 format.
@@ -1,8 +1,41 @@
1
- import { t as bindMcpClient } from "../../invoker-CHMnoxIA.js";
1
+ import { n as normalizeCallToolArguments } from "../../invoker-BC1SZ3q1.js";
2
2
  import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server";
3
3
  import { x402Client } from "@x402/core/client";
4
4
  import { registerExactEvmScheme } from "@x402/evm/exact/server";
5
5
  import { registerExactEvmScheme as registerExactEvmScheme$1 } from "@x402/evm/exact/client";
6
+ //#region src/mcp/client/invoker-compat.ts
7
+ /**
8
+ * Bind the original methods before decorators such as x402 replace them. All
9
+ * generation-specific calling conventions stay behind this small interface.
10
+ */
11
+ function bindMcpClient(client) {
12
+ if ("getProtocolEra" in client && typeof client.getProtocolEra === "function") {
13
+ const v2Client = client;
14
+ const listTools = v2Client.listTools.bind(v2Client);
15
+ const callTool = v2Client.callTool.bind(v2Client);
16
+ return {
17
+ listTools: (params, options) => listTools(params, options),
18
+ callTool: (params, schemaOrOptions, options) => {
19
+ const normalized = normalizeCallToolArguments(schemaOrOptions, options);
20
+ return normalized.schema ? v2Client.request({
21
+ method: "tools/call",
22
+ params
23
+ }, normalized.schema, normalized.options) : callTool(params, normalized.options);
24
+ }
25
+ };
26
+ }
27
+ const legacy = client;
28
+ const listTools = legacy.listTools.bind(legacy);
29
+ const callTool = legacy.callTool.bind(legacy);
30
+ return {
31
+ listTools: (params, options) => listTools(params, options),
32
+ callTool: (params, schemaOrOptions, options) => {
33
+ const normalized = normalizeCallToolArguments(schemaOrOptions, options);
34
+ return callTool(params, normalized.schema, normalized.options);
35
+ }
36
+ };
37
+ }
38
+ //#endregion
6
39
  //#region src/mcp/client/x402.ts
7
40
  /**
8
41
  * Map of legacy v1 network names to CAIP-2 identifiers.
@@ -1 +1 @@
1
- {"version":3,"file":"x402.js","names":[],"sources":["../../../src/mcp/client/x402.ts"],"sourcesContent":["/**\n * X402 MCP Integration (v2)\n *\n * Based on:\n * - Coinbase's x402 (Apache 2.0): https://github.com/coinbase/x402\n * - @ethanniser and his work at https://github.com/ethanniser/x402-mcp\n */\n\nimport type {\n McpServer,\n RegisteredTool,\n ToolCallback\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n CallToolRequest,\n CallToolRequestOptions,\n Client as MCPClient\n} from \"@modelcontextprotocol/client\";\nimport type {\n CallToolResult as V2CallToolResult,\n McpServer as V2McpServer,\n RegisteredTool as V2RegisteredTool,\n ServerContext as V2ServerContext\n} from \"@modelcontextprotocol/server\";\nimport type {\n CallToolResult,\n ToolAnnotations\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n bindMcpClient,\n type CallToolSchemaOrOptions,\n type CompatibleMcpClient,\n type LegacyCallToolResultSchema\n} from \"./invoker\";\nimport type { z, ZodRawShape } from \"zod\";\n\n// v2 imports from @x402/core\nimport { x402ResourceServer, HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { FacilitatorConfig, ResourceConfig } from \"@x402/core/server\";\nimport { x402Client } from \"@x402/core/client\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\n\n// v2 imports from @x402/evm\nimport { registerExactEvmScheme as registerServerEvmScheme } from \"@x402/evm/exact/server\";\nimport { registerExactEvmScheme as registerClientEvmScheme } from \"@x402/evm/exact/client\";\nimport type { ClientEvmSigner } from \"@x402/evm\";\n\n// Re-export commonly used types for consumer convenience\nexport type {\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\nexport type { FacilitatorConfig } from \"@x402/core/server\";\nexport type { ClientEvmSigner } from \"@x402/evm\";\n\n/**\n * Map of legacy v1 network names to CAIP-2 identifiers.\n * Allows backward compatibility with v1 config.\n */\nconst LEGACY_NETWORK_MAP: Record<string, string> = {\n \"base-sepolia\": \"eip155:84532\",\n base: \"eip155:8453\",\n ethereum: \"eip155:1\",\n sepolia: \"eip155:11155111\"\n};\n\n/**\n * Normalize a network identifier to CAIP-2 format.\n * Accepts both legacy v1 names (\"base-sepolia\") and CAIP-2 (\"eip155:84532\").\n */\nexport function normalizeNetwork(network: string): Network {\n return (LEGACY_NETWORK_MAP[network] ?? network) as Network;\n}\n\n/*\n ======= SERVER SIDE =======\n*/\n\nexport type X402Config = {\n /**\n * Network identifier.\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n */\n network: string;\n /** Payment recipient address */\n recipient: `0x${string}`;\n /** Facilitator configuration. Defaults to https://x402.org/facilitator */\n facilitator?: FacilitatorConfig;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n};\n\n/**\n * The tool body passed to `paidTool`. On an SDK v1 server it is the v1\n * `ToolCallback`; on an SDK v2 server it receives the v2 `ServerContext`.\n */\nexport type PaidToolCallback<\n Args extends ZodRawShape,\n Server extends McpServer | V2McpServer = McpServer\n> = Server extends V2McpServer\n ? (\n args: z.infer<z.ZodObject<Args>>,\n ctx: V2ServerContext\n ) => V2CallToolResult | Promise<V2CallToolResult>\n : ToolCallback<Args>;\n\nexport interface X402AugmentedServer<\n Server extends McpServer | V2McpServer = McpServer\n> {\n paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: PaidToolCallback<Args, Server>\n ): Server extends V2McpServer ? V2RegisteredTool : RegisteredTool;\n}\n\ntype RequestMeta = Record<string, unknown>;\ntype HeaderGetter = { get(name: string): string | null };\ntype HeaderRecord = Record<string, string | string[] | undefined>;\n\n/**\n * The parts of a tool handler's second argument that x402 reads. SDK v1\n * passes `{ _meta, requestInfo: { headers } }`, where headers is a plain\n * object (every SDK v1 transport lowercases the keys). SDK v2 passes\n * `{ mcpReq: { _meta }, http: { req } }`, where `req` is the web `Request`.\n */\ntype ToolHandlerContext = {\n _meta?: RequestMeta;\n requestInfo?: { headers?: HeaderGetter | HeaderRecord };\n mcpReq?: { _meta?: RequestMeta };\n http?: { req?: { headers?: HeaderGetter } };\n};\n\nfunction readHeader(\n headers: HeaderGetter | HeaderRecord | undefined,\n name: string\n): string | undefined {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return (headers as HeaderGetter).get(name) ?? undefined;\n }\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers as HeaderRecord)) {\n if (key.toLowerCase() !== wanted) continue;\n const first = Array.isArray(value) ? value[0] : value;\n if (typeof first === \"string\") return first;\n }\n return undefined;\n}\n\n/**\n * Read the x402 payment token from a tool handler context of either SDK\n * generation. Request `_meta` wins over headers, and header names match\n * case-insensitively. `PAYMENT-SIGNATURE` is x402 v2; `X-PAYMENT` is v1.\n */\nfunction readPaymentToken(extra: unknown): unknown {\n const ctx = (extra ?? {}) as ToolHandlerContext;\n const meta = ctx.mcpReq?._meta ?? ctx._meta;\n const headers = ctx.http?.req?.headers ?? ctx.requestInfo?.headers;\n return (\n meta?.[\"x402/payment\"] ??\n readHeader(headers, \"PAYMENT-SIGNATURE\") ??\n readHeader(headers, \"X-PAYMENT\")\n );\n}\n\n/**\n * Add `paidTool` to an MCP server. Accepts an SDK v1 `McpServer`\n * (`@modelcontextprotocol/sdk`) or an SDK v2 `McpServer`\n * (`@modelcontextprotocol/server`).\n */\nexport function withX402<T extends V2McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer<V2McpServer>;\n// The SDK v1 overload is last so `ReturnType<typeof withX402>` and generic\n// v1 callers resolve to exactly the pre-v2 types.\nexport function withX402<T extends McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer;\nexport function withX402(\n server: McpServer | V2McpServer,\n cfg: X402Config\n): (McpServer | V2McpServer) & X402AugmentedServer<McpServer | V2McpServer> {\n const network = normalizeNetwork(cfg.network);\n const facilitatorConfig: FacilitatorConfig = cfg.facilitator ?? {\n url: \"https://x402.org/facilitator\"\n };\n\n // Create v2 resource server with facilitator client\n const facilitatorClient = new HTTPFacilitatorClient(facilitatorConfig);\n const resourceServer = new x402ResourceServer(facilitatorClient);\n registerServerEvmScheme(resourceServer);\n\n // Lazy initialization: fetch supported kinds from facilitator on first use\n let initPromise: Promise<void> | null = null;\n function ensureInitialized(): Promise<void> {\n if (!initPromise) {\n initPromise = resourceServer.initialize().catch((err) => {\n initPromise = null; // allow retry on failure\n throw err;\n });\n }\n return initPromise;\n }\n\n function paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n toolCb: PaidToolCallback<Args, McpServer | V2McpServer>\n ) {\n // Both SDK generations accept a raw Zod shape and call the handler as\n // (args, ctx), so one registration serves either server. The public\n // callback type is enforced by X402AugmentedServer; internally the\n // context is opaque and forwarded to the tool body unchanged.\n const cb = toolCb as unknown as (\n args: unknown,\n extra: unknown\n ) => CallToolResult | Promise<CallToolResult>;\n return (server as McpServer).registerTool(\n name,\n {\n description,\n inputSchema: paramsSchema,\n annotations,\n _meta: {\n \"agents-x402/paymentRequired\": true,\n \"agents-x402/priceUSD\": priceUSD\n }\n },\n (async (args, extra) => {\n await ensureInitialized();\n\n // Build v2 payment requirements for this tool call\n const resourceConfig: ResourceConfig = {\n scheme: \"exact\",\n payTo: cfg.recipient,\n price: priceUSD,\n network,\n maxTimeoutSeconds: 300\n };\n\n let requirements: PaymentRequirements[];\n try {\n requirements =\n await resourceServer.buildPaymentRequirements(resourceConfig);\n } catch {\n const payload = { x402Version: 2, error: \"PRICE_COMPUTE_FAILED\" };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n }\n\n const resourceInfo = {\n url: `x402://${name}`,\n description,\n mimeType: \"application/json\"\n };\n\n const token = readPaymentToken(extra);\n\n const paymentRequired = (\n reason = \"PAYMENT_REQUIRED\",\n extraFields: Record<string, unknown> = {}\n ) => {\n const payload = {\n x402Version: 2,\n error: reason,\n resource: resourceInfo,\n accepts: requirements,\n ...extraFields\n };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n };\n\n if (!token || typeof token !== \"string\") return paymentRequired();\n\n // Decode the payment payload (base64-encoded JSON)\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = JSON.parse(atob(token));\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Find matching requirements for this payment\n const matchingReq = resourceServer.findMatchingRequirements(\n requirements,\n paymentPayload\n );\n if (!matchingReq) {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Verify payment with facilitator\n try {\n const vr = await resourceServer.verifyPayment(\n paymentPayload,\n matchingReq\n );\n if (!vr.isValid) {\n return paymentRequired(vr.invalidReason ?? \"INVALID_PAYMENT\", {\n payer: vr.payer\n });\n }\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Execute the tool callback\n let result: CallToolResult;\n let failed = false;\n try {\n result = await cb(args, extra);\n if (\n result &&\n typeof result === \"object\" &&\n \"isError\" in result &&\n result.isError\n ) {\n failed = true;\n }\n } catch (e) {\n failed = true;\n result = {\n isError: true,\n content: [\n { type: \"text\", text: `Tool execution failed: ${String(e)}` }\n ]\n };\n }\n\n // Settle payment only on success\n if (!failed) {\n try {\n const s = await resourceServer.settlePayment(\n paymentPayload,\n matchingReq\n );\n if (s.success) {\n result._meta ??= {};\n result._meta[\"x402/payment-response\"] = {\n success: true,\n transaction: s.transaction,\n network: s.network,\n payer: s.payer\n };\n } else {\n return paymentRequired(s.errorReason ?? \"SETTLEMENT_FAILED\");\n }\n } catch {\n return paymentRequired(\"SETTLEMENT_FAILED\");\n }\n }\n\n return result;\n }) as ToolCallback<Args>\n );\n }\n\n Object.defineProperty(server, \"paidTool\", {\n value: paidTool,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n // Tell TS the object now also has the paidTool method\n return server as (McpServer | V2McpServer) &\n X402AugmentedServer<McpServer | V2McpServer>;\n}\n\n/*\n ======= CLIENT SIDE =======\n*/\n\nexport interface X402AugmentedClient {\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n /**\n * @deprecated Prefer the request-options overload. Explicit legacy result\n * schemas remain honored through the SDK v2 request funnel.\n */\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n resultSchema: LegacyCallToolResultSchema,\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n}\n\nexport type X402ClientConfig = {\n /**\n * EVM account/signer for signing payment authorizations.\n * Use `privateKeyToAccount()` from viem/accounts to create one.\n */\n account: ClientEvmSigner;\n /**\n * Preferred network identifier (optional).\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n * When set, the client prefers payment requirements matching this network.\n * If omitted, the client automatically selects from available requirements.\n */\n network?: string;\n /** Maximum payment value in atomic units (default: 0.10 USDC = 100000) */\n maxPaymentValue?: bigint;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n /** Confirmation callback for payment approval */\n confirmationCallback?: (payment: PaymentRequirements[]) => Promise<boolean>;\n};\n\nclass PaymentCapError extends Error {}\n// Thrown when the selected requirement cannot be cap-checked; the caller\n// returns the server's original 402 result, as before the hook existed.\nclass PaymentPassthroughError extends Error {}\n\nexport function withX402Client<T extends CompatibleMcpClient>(\n client: T,\n x402Config: X402ClientConfig\n): X402AugmentedClient & T {\n const invoker = bindMcpClient(client);\n const { account } = x402Config;\n\n const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(100_000); // 0.10 USDC\n\n // Create v2 x402 payment client with EVM scheme support\n const paymentClient = new x402Client();\n registerClientEvmScheme(paymentClient, { signer: account });\n\n // Payment requests whose selection reached the hook below. x402 selects a\n // requirement before it runs any hook, so a request that failed without\n // getting here offered nothing this client can sign.\n const selected = new WeakSet<PaymentRequired>();\n\n // Selection applies scheme support and network preference before this hook.\n // Enforce the cap on the requirement that will actually be signed. We throw\n // rather than return `{ abort: true }` because @x402/core rewraps an abort in\n // a plain Error, which would lose the typed errors the catch below relies on.\n paymentClient.onBeforePaymentCreation(\n async ({ paymentRequired, selectedRequirements }) => {\n selected.add(paymentRequired);\n const { scheme, amount } = selectedRequirements;\n if (scheme !== \"exact\") throw new PaymentPassthroughError();\n let value: bigint;\n try {\n value = BigInt(amount);\n } catch {\n throw new PaymentPassthroughError(); // malformed amount\n }\n if (value < 0n) throw new PaymentPassthroughError();\n if (value > maxPaymentValue) {\n throw new PaymentCapError(\n `Payment exceeds client cap: ${value} > ${maxPaymentValue}`\n );\n }\n }\n );\n\n // If a preferred network is specified, register a policy to prefer it\n if (x402Config.network) {\n const preferredNetwork = normalizeNetwork(x402Config.network);\n paymentClient.registerPolicy((_version, reqs) => {\n const matching = reqs.filter((r) => r.network === preferredNetwork);\n return matching.length > 0 ? matching : reqs;\n });\n }\n\n const listTools = async (\n params?: Parameters<MCPClient[\"listTools\"]>[0],\n options?: Parameters<MCPClient[\"listTools\"]>[1]\n ) => {\n const toolsRes = await invoker.listTools(params, options);\n return {\n ...toolsRes,\n tools: toolsRes.tools.map((tool) => {\n let description = tool.description;\n // Check _meta for payment information (agents-x402/ is our extension for pre-advertising prices)\n if (tool._meta?.[\"agents-x402/paymentRequired\"]) {\n const cost = tool._meta?.[\"agents-x402/priceUSD\"]\n ? `$${tool._meta?.[\"agents-x402/priceUSD\"]}`\n : \"an unknown amount\";\n description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;\n }\n return {\n ...tool,\n description\n };\n })\n };\n };\n\n const callToolWithPayment = async (\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n ): ReturnType<MCPClient[\"callTool\"]> => {\n const invoke = (callParams: CallToolRequest[\"params\"]) =>\n invoker.callTool(callParams, schemaOrOptions, options);\n const res = await invoke(params);\n\n // Check for x402 payment required error in response metadata\n const maybeX402Error = res._meta?.[\"x402/error\"] as\n | (PaymentRequired & Record<string, unknown>)\n | undefined;\n\n if (\n res.isError &&\n maybeX402Error &&\n maybeX402Error.accepts &&\n Array.isArray(maybeX402Error.accepts) &&\n maybeX402Error.accepts.length > 0\n ) {\n // Snapshot the requirements: what is cap-checked and signed below is\n // this copy, not the server's result object or anything aliasing it.\n const accepts = structuredClone(\n maybeX402Error.accepts\n ) as PaymentRequirements[];\n const confirmationCallback =\n x402ConfirmationCallback ?? x402Config.confirmationCallback;\n\n // Use the confirmation callback if provided. It receives deep copies\n // so a retained reference cannot alter what is cap-checked and signed.\n if (\n confirmationCallback &&\n !(await confirmationCallback(\n accepts.map((req) => structuredClone(req))\n ))\n ) {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"User declined payment\" }]\n };\n }\n\n // Reconstruct the PaymentRequired response for the v2 x402 client\n const paymentRequiredResponse: PaymentRequired = {\n x402Version: (maybeX402Error.x402Version as number) ?? 2,\n resource: (maybeX402Error.resource as PaymentRequired[\"resource\"]) ?? {\n url: \"\",\n description: \"\",\n mimeType: \"application/json\"\n },\n accepts,\n extensions: maybeX402Error.extensions as\n | Record<string, unknown>\n | undefined\n };\n\n // Create the payment payload using the v2 x402 client\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = await paymentClient.createPaymentPayload(\n paymentRequiredResponse\n );\n } catch (error) {\n // Nothing this client can sign, or a selection it cannot cap-check:\n // return the server's 402 with its payment options, as before.\n if (\n error instanceof PaymentPassthroughError ||\n !selected.has(paymentRequiredResponse)\n ) {\n return res;\n }\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text:\n error instanceof PaymentCapError\n ? error.message\n : \"Failed to create payment payload\"\n }\n ]\n };\n }\n\n // Encode the payment payload as a base64 JSON token for MCP transport\n const token = btoa(JSON.stringify(paymentPayload));\n\n // Retry the tool call with the payment token\n return invoke({\n ...params,\n _meta: {\n ...params._meta,\n \"x402/payment\": token\n }\n });\n }\n\n return res;\n };\n\n const _client = client as X402AugmentedClient & T;\n Object.defineProperty(_client, \"listTools\", {\n value: listTools,\n writable: false,\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(_client, \"callTool\", {\n value: callToolWithPayment,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n return _client;\n}\n"],"mappings":";;;;;;;;;;AAiEA,MAAM,qBAA6C;CACjD,gBAAgB;CAChB,MAAM;CACN,UAAU;CACV,SAAS;AACX;;;;;AAMA,SAAgB,iBAAiB,SAA0B;CACzD,OAAQ,mBAAmB,YAAY;AACzC;AAgEA,SAAS,WACP,SACA,MACoB;CACpB,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,OAAO,QAAQ,QAAQ,YACzB,OAAQ,QAAyB,IAAI,IAAI,KAAK,KAAA;CAEhD,MAAM,SAAS,KAAK,YAAY;CAChC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAuB,GAAG;EAClE,IAAI,IAAI,YAAY,MAAM,QAAQ;EAClC,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;EAChD,IAAI,OAAO,UAAU,UAAU,OAAO;CACxC;AAEF;;;;;;AAOA,SAAS,iBAAiB,OAAyB;CACjD,MAAM,MAAO,SAAS,CAAC;CACvB,MAAM,OAAO,IAAI,QAAQ,SAAS,IAAI;CACtC,MAAM,UAAU,IAAI,MAAM,KAAK,WAAW,IAAI,aAAa;CAC3D,OACE,OAAO,mBACP,WAAW,SAAS,mBAAmB,KACvC,WAAW,SAAS,WAAW;AAEnC;AAiBA,SAAgB,SACd,QACA,KAC0E;CAC1E,MAAM,UAAU,iBAAiB,IAAI,OAAO;CAO5C,MAAM,iBAAiB,IAAI,mBAAmB,IADhB,sBALe,IAAI,eAAe,EAC9D,KAAK,+BACP,CAI8D,CAAC;CAC/D,uBAAwB,cAAc;CAGtC,IAAI,cAAoC;CACxC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ACA,eAAe,WACf,MAAM,QAAQ,eAAe,OAAO,KACpC,eAAe,QAAQ,SAAS,GAChC;GAGA,MAAM,UAAU,gBACd,eAAe,OACjB;GACA,MAAM,uBACJ,4BAA4B,WAAW;GAIzC,IACE,wBACA,CAAE,MAAM,qBACN,QAAQ,KAAK,QAAQ,gBAAgB,GAAG,CAAC,CAC3C,GAEA,OAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM;IAAwB,CAAC;GAC3D;GAIF,MAAM,0BAA2C;IAC/C,aAAc,eAAe,eAA0B;IACvD,UAAW,eAAe,YAA4C;KACpE,KAAK;KACL,aAAa;KACb,UAAU;IACZ;IACA;IACA,YAAY,eAAe;GAG7B;GAGA,IAAI;GACJ,IAAI;IACF,iBAAiB,MAAM,cAAc,qBACnC,uBACF;GACF,SAAS,OAAO;IAGd,IACE,iBAAiB,2BACjB,CAAC,SAAS,IAAI,uBAAuB,GAErC,OAAO;IAET,OAAO;KACL,SAAS;KACT,SAAS,CACP;MACE,MAAM;MACN,MACE,iBAAiB,kBACb,MAAM,UACN;KACR,CACF;IACF;GACF;GAGA,MAAM,QAAQ,KAAK,KAAK,UAAU,cAAc,CAAC;GAGjD,OAAO,OAAO;IACZ,GAAG;IACH,OAAO;KACL,GAAG,OAAO;KACV,gBAAgB;IAClB;GACF,CAAC;EACH;EAEA,OAAO;CACT;CAEA,MAAM,UAAU;CAChB,OAAO,eAAe,SAAS,aAAa;EAC1C,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO,eAAe,SAAS,YAAY;EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"x402.js","names":[],"sources":["../../../src/mcp/client/invoker-compat.ts","../../../src/mcp/client/x402.ts"],"sourcesContent":["import type {\n CallToolRequest,\n CallToolRequestOptions,\n Client,\n ListToolsResult\n} from \"@modelcontextprotocol/client\";\nimport type { Client as LegacyClient } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type {\n CallToolResult as LegacyCallToolResult,\n ListToolsRequest\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { RequestOptions as LegacyRequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport {\n type CallToolSchemaOrOptions,\n normalizeCallToolArguments\n} from \"./invoker\";\n\n// Accepts both SDK v1 and v2 clients. Kept separate from `./invoker` because\n// its types depend on `@modelcontextprotocol/sdk`, an optional peer that only\n// the x402 entry needs.\n\nexport type CompatibleMcpClient = Client | LegacyClient;\n\nexport interface BoundMcpClientInvoker {\n listTools(\n params?: ListToolsRequest[\"params\"],\n options?: CallToolRequestOptions\n ): Promise<ListToolsResult>;\n callTool(\n params: CallToolRequest[\"params\"],\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n ): Promise<LegacyCallToolResult>;\n}\n\n/**\n * Bind the original methods before decorators such as x402 replace them. All\n * generation-specific calling conventions stay behind this small interface.\n */\nexport function bindMcpClient(\n client: CompatibleMcpClient\n): BoundMcpClientInvoker {\n const isV2 =\n \"getProtocolEra\" in client &&\n typeof (client as { getProtocolEra?: unknown }).getProtocolEra ===\n \"function\";\n\n if (isV2) {\n const v2Client = client as Client;\n const listTools = v2Client.listTools.bind(v2Client);\n const callTool = v2Client.callTool.bind(v2Client);\n return {\n listTools: (params, options) => listTools(params, options),\n callTool: (params, schemaOrOptions, options) => {\n const normalized = normalizeCallToolArguments(schemaOrOptions, options);\n const pending = normalized.schema\n ? v2Client.request(\n { method: \"tools/call\", params },\n normalized.schema as never,\n normalized.options\n )\n : callTool(params, normalized.options);\n return pending as Promise<LegacyCallToolResult>;\n }\n };\n }\n\n const legacy = client as LegacyClient;\n const listTools = legacy.listTools.bind(legacy);\n const callTool = legacy.callTool.bind(legacy);\n return {\n listTools: (params, options) =>\n listTools(\n params,\n options as LegacyRequestOptions\n ) as Promise<ListToolsResult>,\n callTool: (params, schemaOrOptions, options) => {\n const normalized = normalizeCallToolArguments(schemaOrOptions, options);\n return callTool(\n params as Parameters<LegacyClient[\"callTool\"]>[0],\n normalized.schema as Parameters<LegacyClient[\"callTool\"]>[1],\n normalized.options as LegacyRequestOptions\n ) as Promise<LegacyCallToolResult>;\n }\n };\n}\n","/**\n * X402 MCP Integration (v2)\n *\n * Based on:\n * - Coinbase's x402 (Apache 2.0): https://github.com/coinbase/x402\n * - @ethanniser and his work at https://github.com/ethanniser/x402-mcp\n */\n\nimport type {\n McpServer,\n RegisteredTool,\n ToolCallback\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n CallToolRequest,\n CallToolRequestOptions,\n Client as MCPClient\n} from \"@modelcontextprotocol/client\";\nimport type {\n CallToolResult as V2CallToolResult,\n McpServer as V2McpServer,\n RegisteredTool as V2RegisteredTool,\n ServerContext as V2ServerContext\n} from \"@modelcontextprotocol/server\";\nimport type {\n CallToolResult,\n ToolAnnotations\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n CallToolSchemaOrOptions,\n LegacyCallToolResultSchema\n} from \"./invoker\";\nimport { bindMcpClient, type CompatibleMcpClient } from \"./invoker-compat\";\nimport type { z, ZodRawShape } from \"zod\";\n\n// v2 imports from @x402/core\nimport { x402ResourceServer, HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { FacilitatorConfig, ResourceConfig } from \"@x402/core/server\";\nimport { x402Client } from \"@x402/core/client\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\n\n// v2 imports from @x402/evm\nimport { registerExactEvmScheme as registerServerEvmScheme } from \"@x402/evm/exact/server\";\nimport { registerExactEvmScheme as registerClientEvmScheme } from \"@x402/evm/exact/client\";\nimport type { ClientEvmSigner } from \"@x402/evm\";\n\n// Re-export commonly used types for consumer convenience\nexport type {\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\nexport type { FacilitatorConfig } from \"@x402/core/server\";\nexport type { ClientEvmSigner } from \"@x402/evm\";\n\n/**\n * Map of legacy v1 network names to CAIP-2 identifiers.\n * Allows backward compatibility with v1 config.\n */\nconst LEGACY_NETWORK_MAP: Record<string, string> = {\n \"base-sepolia\": \"eip155:84532\",\n base: \"eip155:8453\",\n ethereum: \"eip155:1\",\n sepolia: \"eip155:11155111\"\n};\n\n/**\n * Normalize a network identifier to CAIP-2 format.\n * Accepts both legacy v1 names (\"base-sepolia\") and CAIP-2 (\"eip155:84532\").\n */\nexport function normalizeNetwork(network: string): Network {\n return (LEGACY_NETWORK_MAP[network] ?? network) as Network;\n}\n\n/*\n ======= SERVER SIDE =======\n*/\n\nexport type X402Config = {\n /**\n * Network identifier.\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n */\n network: string;\n /** Payment recipient address */\n recipient: `0x${string}`;\n /** Facilitator configuration. Defaults to https://x402.org/facilitator */\n facilitator?: FacilitatorConfig;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n};\n\n/**\n * The tool body passed to `paidTool`. On an SDK v1 server it is the v1\n * `ToolCallback`; on an SDK v2 server it receives the v2 `ServerContext`.\n */\nexport type PaidToolCallback<\n Args extends ZodRawShape,\n Server extends McpServer | V2McpServer = McpServer\n> = Server extends V2McpServer\n ? (\n args: z.infer<z.ZodObject<Args>>,\n ctx: V2ServerContext\n ) => V2CallToolResult | Promise<V2CallToolResult>\n : ToolCallback<Args>;\n\nexport interface X402AugmentedServer<\n Server extends McpServer | V2McpServer = McpServer\n> {\n paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: PaidToolCallback<Args, Server>\n ): Server extends V2McpServer ? V2RegisteredTool : RegisteredTool;\n}\n\ntype RequestMeta = Record<string, unknown>;\ntype HeaderGetter = { get(name: string): string | null };\ntype HeaderRecord = Record<string, string | string[] | undefined>;\n\n/**\n * The parts of a tool handler's second argument that x402 reads. SDK v1\n * passes `{ _meta, requestInfo: { headers } }`, where headers is a plain\n * object (every SDK v1 transport lowercases the keys). SDK v2 passes\n * `{ mcpReq: { _meta }, http: { req } }`, where `req` is the web `Request`.\n */\ntype ToolHandlerContext = {\n _meta?: RequestMeta;\n requestInfo?: { headers?: HeaderGetter | HeaderRecord };\n mcpReq?: { _meta?: RequestMeta };\n http?: { req?: { headers?: HeaderGetter } };\n};\n\nfunction readHeader(\n headers: HeaderGetter | HeaderRecord | undefined,\n name: string\n): string | undefined {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return (headers as HeaderGetter).get(name) ?? undefined;\n }\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers as HeaderRecord)) {\n if (key.toLowerCase() !== wanted) continue;\n const first = Array.isArray(value) ? value[0] : value;\n if (typeof first === \"string\") return first;\n }\n return undefined;\n}\n\n/**\n * Read the x402 payment token from a tool handler context of either SDK\n * generation. Request `_meta` wins over headers, and header names match\n * case-insensitively. `PAYMENT-SIGNATURE` is x402 v2; `X-PAYMENT` is v1.\n */\nfunction readPaymentToken(extra: unknown): unknown {\n const ctx = (extra ?? {}) as ToolHandlerContext;\n const meta = ctx.mcpReq?._meta ?? ctx._meta;\n const headers = ctx.http?.req?.headers ?? ctx.requestInfo?.headers;\n return (\n meta?.[\"x402/payment\"] ??\n readHeader(headers, \"PAYMENT-SIGNATURE\") ??\n readHeader(headers, \"X-PAYMENT\")\n );\n}\n\n/**\n * Add `paidTool` to an MCP server. Accepts an SDK v1 `McpServer`\n * (`@modelcontextprotocol/sdk`) or an SDK v2 `McpServer`\n * (`@modelcontextprotocol/server`).\n */\nexport function withX402<T extends V2McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer<V2McpServer>;\n// The SDK v1 overload is last so `ReturnType<typeof withX402>` and generic\n// v1 callers resolve to exactly the pre-v2 types.\nexport function withX402<T extends McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer;\nexport function withX402(\n server: McpServer | V2McpServer,\n cfg: X402Config\n): (McpServer | V2McpServer) & X402AugmentedServer<McpServer | V2McpServer> {\n const network = normalizeNetwork(cfg.network);\n const facilitatorConfig: FacilitatorConfig = cfg.facilitator ?? {\n url: \"https://x402.org/facilitator\"\n };\n\n // Create v2 resource server with facilitator client\n const facilitatorClient = new HTTPFacilitatorClient(facilitatorConfig);\n const resourceServer = new x402ResourceServer(facilitatorClient);\n registerServerEvmScheme(resourceServer);\n\n // Lazy initialization: fetch supported kinds from facilitator on first use\n let initPromise: Promise<void> | null = null;\n function ensureInitialized(): Promise<void> {\n if (!initPromise) {\n initPromise = resourceServer.initialize().catch((err) => {\n initPromise = null; // allow retry on failure\n throw err;\n });\n }\n return initPromise;\n }\n\n function paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n toolCb: PaidToolCallback<Args, McpServer | V2McpServer>\n ) {\n // Both SDK generations accept a raw Zod shape and call the handler as\n // (args, ctx), so one registration serves either server. The public\n // callback type is enforced by X402AugmentedServer; internally the\n // context is opaque and forwarded to the tool body unchanged.\n const cb = toolCb as unknown as (\n args: unknown,\n extra: unknown\n ) => CallToolResult | Promise<CallToolResult>;\n return (server as McpServer).registerTool(\n name,\n {\n description,\n inputSchema: paramsSchema,\n annotations,\n _meta: {\n \"agents-x402/paymentRequired\": true,\n \"agents-x402/priceUSD\": priceUSD\n }\n },\n (async (args, extra) => {\n await ensureInitialized();\n\n // Build v2 payment requirements for this tool call\n const resourceConfig: ResourceConfig = {\n scheme: \"exact\",\n payTo: cfg.recipient,\n price: priceUSD,\n network,\n maxTimeoutSeconds: 300\n };\n\n let requirements: PaymentRequirements[];\n try {\n requirements =\n await resourceServer.buildPaymentRequirements(resourceConfig);\n } catch {\n const payload = { x402Version: 2, error: \"PRICE_COMPUTE_FAILED\" };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n }\n\n const resourceInfo = {\n url: `x402://${name}`,\n description,\n mimeType: \"application/json\"\n };\n\n const token = readPaymentToken(extra);\n\n const paymentRequired = (\n reason = \"PAYMENT_REQUIRED\",\n extraFields: Record<string, unknown> = {}\n ) => {\n const payload = {\n x402Version: 2,\n error: reason,\n resource: resourceInfo,\n accepts: requirements,\n ...extraFields\n };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n };\n\n if (!token || typeof token !== \"string\") return paymentRequired();\n\n // Decode the payment payload (base64-encoded JSON)\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = JSON.parse(atob(token));\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Find matching requirements for this payment\n const matchingReq = resourceServer.findMatchingRequirements(\n requirements,\n paymentPayload\n );\n if (!matchingReq) {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Verify payment with facilitator\n try {\n const vr = await resourceServer.verifyPayment(\n paymentPayload,\n matchingReq\n );\n if (!vr.isValid) {\n return paymentRequired(vr.invalidReason ?? \"INVALID_PAYMENT\", {\n payer: vr.payer\n });\n }\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Execute the tool callback\n let result: CallToolResult;\n let failed = false;\n try {\n result = await cb(args, extra);\n if (\n result &&\n typeof result === \"object\" &&\n \"isError\" in result &&\n result.isError\n ) {\n failed = true;\n }\n } catch (e) {\n failed = true;\n result = {\n isError: true,\n content: [\n { type: \"text\", text: `Tool execution failed: ${String(e)}` }\n ]\n };\n }\n\n // Settle payment only on success\n if (!failed) {\n try {\n const s = await resourceServer.settlePayment(\n paymentPayload,\n matchingReq\n );\n if (s.success) {\n result._meta ??= {};\n result._meta[\"x402/payment-response\"] = {\n success: true,\n transaction: s.transaction,\n network: s.network,\n payer: s.payer\n };\n } else {\n return paymentRequired(s.errorReason ?? \"SETTLEMENT_FAILED\");\n }\n } catch {\n return paymentRequired(\"SETTLEMENT_FAILED\");\n }\n }\n\n return result;\n }) as ToolCallback<Args>\n );\n }\n\n Object.defineProperty(server, \"paidTool\", {\n value: paidTool,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n // Tell TS the object now also has the paidTool method\n return server as (McpServer | V2McpServer) &\n X402AugmentedServer<McpServer | V2McpServer>;\n}\n\n/*\n ======= CLIENT SIDE =======\n*/\n\nexport interface X402AugmentedClient {\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n /**\n * @deprecated Prefer the request-options overload. Explicit legacy result\n * schemas remain honored through the SDK v2 request funnel.\n */\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n resultSchema: LegacyCallToolResultSchema,\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n}\n\nexport type X402ClientConfig = {\n /**\n * EVM account/signer for signing payment authorizations.\n * Use `privateKeyToAccount()` from viem/accounts to create one.\n */\n account: ClientEvmSigner;\n /**\n * Preferred network identifier (optional).\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n * When set, the client prefers payment requirements matching this network.\n * If omitted, the client automatically selects from available requirements.\n */\n network?: string;\n /** Maximum payment value in atomic units (default: 0.10 USDC = 100000) */\n maxPaymentValue?: bigint;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n /** Confirmation callback for payment approval */\n confirmationCallback?: (payment: PaymentRequirements[]) => Promise<boolean>;\n};\n\nclass PaymentCapError extends Error {}\n// Thrown when the selected requirement cannot be cap-checked; the caller\n// returns the server's original 402 result, as before the hook existed.\nclass PaymentPassthroughError extends Error {}\n\nexport function withX402Client<T extends CompatibleMcpClient>(\n client: T,\n x402Config: X402ClientConfig\n): X402AugmentedClient & T {\n const invoker = bindMcpClient(client);\n const { account } = x402Config;\n\n const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(100_000); // 0.10 USDC\n\n // Create v2 x402 payment client with EVM scheme support\n const paymentClient = new x402Client();\n registerClientEvmScheme(paymentClient, { signer: account });\n\n // Payment requests whose selection reached the hook below. x402 selects a\n // requirement before it runs any hook, so a request that failed without\n // getting here offered nothing this client can sign.\n const selected = new WeakSet<PaymentRequired>();\n\n // Selection applies scheme support and network preference before this hook.\n // Enforce the cap on the requirement that will actually be signed. We throw\n // rather than return `{ abort: true }` because @x402/core rewraps an abort in\n // a plain Error, which would lose the typed errors the catch below relies on.\n paymentClient.onBeforePaymentCreation(\n async ({ paymentRequired, selectedRequirements }) => {\n selected.add(paymentRequired);\n const { scheme, amount } = selectedRequirements;\n if (scheme !== \"exact\") throw new PaymentPassthroughError();\n let value: bigint;\n try {\n value = BigInt(amount);\n } catch {\n throw new PaymentPassthroughError(); // malformed amount\n }\n if (value < 0n) throw new PaymentPassthroughError();\n if (value > maxPaymentValue) {\n throw new PaymentCapError(\n `Payment exceeds client cap: ${value} > ${maxPaymentValue}`\n );\n }\n }\n );\n\n // If a preferred network is specified, register a policy to prefer it\n if (x402Config.network) {\n const preferredNetwork = normalizeNetwork(x402Config.network);\n paymentClient.registerPolicy((_version, reqs) => {\n const matching = reqs.filter((r) => r.network === preferredNetwork);\n return matching.length > 0 ? matching : reqs;\n });\n }\n\n const listTools = async (\n params?: Parameters<MCPClient[\"listTools\"]>[0],\n options?: Parameters<MCPClient[\"listTools\"]>[1]\n ) => {\n const toolsRes = await invoker.listTools(params, options);\n return {\n ...toolsRes,\n tools: toolsRes.tools.map((tool) => {\n let description = tool.description;\n // Check _meta for payment information (agents-x402/ is our extension for pre-advertising prices)\n if (tool._meta?.[\"agents-x402/paymentRequired\"]) {\n const cost = tool._meta?.[\"agents-x402/priceUSD\"]\n ? `$${tool._meta?.[\"agents-x402/priceUSD\"]}`\n : \"an unknown amount\";\n description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;\n }\n return {\n ...tool,\n description\n };\n })\n };\n };\n\n const callToolWithPayment = async (\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n ): ReturnType<MCPClient[\"callTool\"]> => {\n const invoke = (callParams: CallToolRequest[\"params\"]) =>\n invoker.callTool(callParams, schemaOrOptions, options);\n const res = await invoke(params);\n\n // Check for x402 payment required error in response metadata\n const maybeX402Error = res._meta?.[\"x402/error\"] as\n | (PaymentRequired & Record<string, unknown>)\n | undefined;\n\n if (\n res.isError &&\n maybeX402Error &&\n maybeX402Error.accepts &&\n Array.isArray(maybeX402Error.accepts) &&\n maybeX402Error.accepts.length > 0\n ) {\n // Snapshot the requirements: what is cap-checked and signed below is\n // this copy, not the server's result object or anything aliasing it.\n const accepts = structuredClone(\n maybeX402Error.accepts\n ) as PaymentRequirements[];\n const confirmationCallback =\n x402ConfirmationCallback ?? x402Config.confirmationCallback;\n\n // Use the confirmation callback if provided. It receives deep copies\n // so a retained reference cannot alter what is cap-checked and signed.\n if (\n confirmationCallback &&\n !(await confirmationCallback(\n accepts.map((req) => structuredClone(req))\n ))\n ) {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"User declined payment\" }]\n };\n }\n\n // Reconstruct the PaymentRequired response for the v2 x402 client\n const paymentRequiredResponse: PaymentRequired = {\n x402Version: (maybeX402Error.x402Version as number) ?? 2,\n resource: (maybeX402Error.resource as PaymentRequired[\"resource\"]) ?? {\n url: \"\",\n description: \"\",\n mimeType: \"application/json\"\n },\n accepts,\n extensions: maybeX402Error.extensions as\n | Record<string, unknown>\n | undefined\n };\n\n // Create the payment payload using the v2 x402 client\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = await paymentClient.createPaymentPayload(\n paymentRequiredResponse\n );\n } catch (error) {\n // Nothing this client can sign, or a selection it cannot cap-check:\n // return the server's 402 with its payment options, as before.\n if (\n error instanceof PaymentPassthroughError ||\n !selected.has(paymentRequiredResponse)\n ) {\n return res;\n }\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text:\n error instanceof PaymentCapError\n ? error.message\n : \"Failed to create payment payload\"\n }\n ]\n };\n }\n\n // Encode the payment payload as a base64 JSON token for MCP transport\n const token = btoa(JSON.stringify(paymentPayload));\n\n // Retry the tool call with the payment token\n return invoke({\n ...params,\n _meta: {\n ...params._meta,\n \"x402/payment\": token\n }\n });\n }\n\n return res;\n };\n\n const _client = client as X402AugmentedClient & T;\n Object.defineProperty(_client, \"listTools\", {\n value: listTools,\n writable: false,\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(_client, \"callTool\", {\n value: callToolWithPayment,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n return _client;\n}\n"],"mappings":";;;;;;;;;;AAuCA,SAAgB,cACd,QACuB;CAMvB,IAJE,oBAAoB,UACpB,OAAQ,OAAwC,mBAC9C,YAEM;EACR,MAAM,WAAW;EACjB,MAAM,YAAY,SAAS,UAAU,KAAK,QAAQ;EAClD,MAAM,WAAW,SAAS,SAAS,KAAK,QAAQ;EAChD,OAAO;GACL,YAAY,QAAQ,YAAY,UAAU,QAAQ,OAAO;GACzD,WAAW,QAAQ,iBAAiB,YAAY;IAC9C,MAAM,aAAa,2BAA2B,iBAAiB,OAAO;IAQtE,OAPgB,WAAW,SACvB,SAAS,QACP;KAAE,QAAQ;KAAc;IAAO,GAC/B,WAAW,QACX,WAAW,OACb,IACA,SAAS,QAAQ,WAAW,OAAO;GAEzC;EACF;CACF;CAEA,MAAM,SAAS;CACf,MAAM,YAAY,OAAO,UAAU,KAAK,MAAM;CAC9C,MAAM,WAAW,OAAO,SAAS,KAAK,MAAM;CAC5C,OAAO;EACL,YAAY,QAAQ,YAClB,UACE,QACA,OACF;EACF,WAAW,QAAQ,iBAAiB,YAAY;GAC9C,MAAM,aAAa,2BAA2B,iBAAiB,OAAO;GACtE,OAAO,SACL,QACA,WAAW,QACX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