trellis 3.2.2 → 3.2.4

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 (210) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +4 -0
  3. package/dist/better-sqlite-backend-CDYOAJDF.js +209 -0
  4. package/dist/boot-middleware-LBJX4N2S.js +9 -0
  5. package/dist/boot-middleware-PATBLD52.js +9 -0
  6. package/dist/bridge-G5DPW6TY.js +2361 -0
  7. package/dist/bridge-JSSPQPRH.js +2389 -0
  8. package/dist/bridge-LNXE4HAW.js +2389 -0
  9. package/dist/bridge-OAAXJWSA.js +2389 -0
  10. package/dist/bridge-SFS63RHC.js +2367 -0
  11. package/dist/bridge-U5TOUBVM.js +2389 -0
  12. package/dist/browser/index.js +9 -9
  13. package/dist/{chunk-KSU2GW22.js → chunk-276W52FK.js} +8 -0
  14. package/dist/{chunk-KFQGP6VL.js → chunk-2ESYSVXG.js} +15 -0
  15. package/dist/{chunk-L5N5PR2S.js → chunk-2WW2X2BR.js} +313 -77
  16. package/dist/chunk-3XCOAP6G.js +48 -0
  17. package/dist/chunk-53PDCTJ3.js +1856 -0
  18. package/dist/{chunk-N6MYZT4O.js → chunk-547FZFKO.js} +1 -1
  19. package/dist/{chunk-H6JB3PZ3.js → chunk-5KSGGKET.js} +1 -1
  20. package/dist/{chunk-J2TXUFCZ.js → chunk-6RWGFC3N.js} +134 -20
  21. package/dist/{chunk-QB5ISE47.js → chunk-7WVOPXJV.js} +3 -3
  22. package/dist/chunk-CMSFD6OV.js +11801 -0
  23. package/dist/{chunk-RSWUFTO2.js → chunk-CPUYCCLT.js} +2 -2
  24. package/dist/{chunk-4HYPLFJD.js → chunk-FA5TFVA5.js} +1 -1
  25. package/dist/{chunk-4XIVMVHC.js → chunk-G3XIHPSQ.js} +1 -1
  26. package/dist/{chunk-JHHEXEDM.js → chunk-GCQF75T4.js} +3 -3
  27. package/dist/{chunk-FKQO5A3H.js → chunk-GHG4H3AS.js} +2 -2
  28. package/dist/{chunk-GLM4HGN4.js → chunk-GRWQPKYK.js} +1 -1
  29. package/dist/{chunk-PZ4XYZ4J.js → chunk-GXA73CNC.js} +33 -8
  30. package/dist/{chunk-6GEZ6DN5.js → chunk-H6VTC5SS.js} +3 -3
  31. package/dist/{chunk-S3XLFZ27.js → chunk-IHHSOBJS.js} +1 -1
  32. package/dist/chunk-IJNC25UD.js +2243 -0
  33. package/dist/{chunk-VDAKEOML.js → chunk-J6OUIION.js} +1 -1
  34. package/dist/chunk-JAVAYMMS.js +6 -0
  35. package/dist/{chunk-S6GBJ2ZB.js → chunk-JCQQFLO5.js} +1 -1
  36. package/dist/{chunk-FWRS4CSC.js → chunk-KQG6ZYXP.js} +3 -3
  37. package/dist/chunk-KXAISKZT.js +119 -0
  38. package/dist/chunk-N3R74ZSR.js +7949 -0
  39. package/dist/{chunk-GU374KWZ.js → chunk-NLFRRGX6.js} +3 -3
  40. package/dist/{chunk-XMQ7G77X.js → chunk-OB4CMMX6.js} +1 -1
  41. package/dist/chunk-OKNASCZY.js +182 -0
  42. package/dist/chunk-ONOPPX5E.js +394 -0
  43. package/dist/chunk-QMSU2RAH.js +98 -0
  44. package/dist/{chunk-TCKXSOBP.js → chunk-RARKFVWU.js} +8 -1
  45. package/dist/{chunk-2W3MHTMG.js → chunk-SJWVDS5M.js} +835 -127
  46. package/dist/{chunk-SPSPV5BC.js → chunk-SZ3VAB5P.js} +159 -2
  47. package/dist/chunk-V2ASD6RQ.js +147 -0
  48. package/dist/{chunk-KQ4A2D2P.js → chunk-V4YCJDYL.js} +58 -38
  49. package/dist/{chunk-LNUIGRDZ.js → chunk-VWKLKLYB.js} +1 -1
  50. package/dist/chunk-W5PADCDF.js +1856 -0
  51. package/dist/{chunk-MLC5BUYO.js → chunk-WMERMSWI.js} +1 -1
  52. package/dist/{chunk-IZX2PLIB.js → chunk-WXAURJUD.js} +835 -127
  53. package/dist/chunk-YC5I32PS.js +147 -0
  54. package/dist/{chunk-VBYUTRXX.js → chunk-YKVB4LUQ.js} +3 -3
  55. package/dist/{chunk-7ZFRVCUE.js → chunk-YPT6XMS4.js} +48 -64
  56. package/dist/cli/deploy-cli.d.ts.map +1 -1
  57. package/dist/{deploy-cli-C35HTITO.js → cli/deploy-cli.js} +45 -6
  58. package/dist/cli/gateway-deploy-cli.d.ts +19 -0
  59. package/dist/cli/gateway-deploy-cli.d.ts.map +1 -0
  60. package/dist/cli/index.d.ts.map +1 -1
  61. package/dist/cli/index.js +1363 -884
  62. package/dist/cli/lane.d.ts.map +1 -1
  63. package/dist/cli/protocol.d.ts +6 -0
  64. package/dist/cli/protocol.d.ts.map +1 -0
  65. package/dist/client/index.browser.js +2 -2
  66. package/dist/client/index.js +11 -11
  67. package/dist/client/sdk.browser.d.ts +28 -1
  68. package/dist/client/sdk.browser.d.ts.map +1 -1
  69. package/dist/client/sdk.browser.js +2 -2
  70. package/dist/client/sdk.js +2 -2
  71. package/dist/cms/index.js +1 -1
  72. package/dist/config-KMY6RRK3.js +19 -0
  73. package/dist/core/index.js +17 -17
  74. package/dist/core/kernel/boot-middleware.d.ts +1 -1
  75. package/dist/core/kernel/boot-middleware.d.ts.map +1 -1
  76. package/dist/core/kernel/schema-middleware.d.ts +2 -1
  77. package/dist/core/kernel/schema-middleware.d.ts.map +1 -1
  78. package/dist/core/kernel/trellis-kernel.d.ts +10 -10
  79. package/dist/core/kernel/trellis-kernel.d.ts.map +1 -1
  80. package/dist/core/persist/factory.js +2 -2
  81. package/dist/core/persist/sqljs-backend.js +2 -2
  82. package/dist/db/index.js +32 -27
  83. package/dist/decisions/index.js +4 -4
  84. package/dist/embeddings/index.js +2 -2
  85. package/dist/engine.d.ts +24 -6
  86. package/dist/engine.d.ts.map +1 -1
  87. package/dist/gateway-deploy-cli-4TU4V3QI.js +312 -0
  88. package/dist/gateway-deploy-cli-A4ISTDHJ.js +298 -0
  89. package/dist/gateway-deploy-cli-D3XTKJQJ.js +312 -0
  90. package/dist/gateway-deploy-cli-ECV3OQCN.js +305 -0
  91. package/dist/gateway-deploy-cli-JUHKVIJE.js +296 -0
  92. package/dist/gateway-deploy-cli-NSDW2JLT.js +310 -0
  93. package/dist/gateway-serve-CM5EAZ52.js +113 -0
  94. package/dist/import-AJLYHFIA.js +10 -0
  95. package/dist/index.js +11 -11
  96. package/dist/launch-explorer-FVX6ZABW.js +95 -0
  97. package/dist/links/index.js +2 -2
  98. package/dist/mcp/bridge.d.ts +45 -0
  99. package/dist/mcp/bridge.d.ts.map +1 -0
  100. package/dist/mcp/discovery.d.ts +15 -0
  101. package/dist/mcp/discovery.d.ts.map +1 -0
  102. package/dist/mcp/gateway-config.d.ts +20 -0
  103. package/dist/mcp/gateway-config.d.ts.map +1 -0
  104. package/dist/mcp/gateway-serve.d.ts +19 -0
  105. package/dist/mcp/gateway-serve.d.ts.map +1 -0
  106. package/dist/mcp/gateway-serve.js +119 -0
  107. package/dist/mcp/graph-summary.d.ts +47 -0
  108. package/dist/mcp/graph-summary.d.ts.map +1 -0
  109. package/dist/mcp/room-audit.d.ts +14 -0
  110. package/dist/mcp/room-audit.d.ts.map +1 -0
  111. package/dist/mcp/room-helpers.d.ts +43 -0
  112. package/dist/mcp/room-helpers.d.ts.map +1 -0
  113. package/dist/mcp/room-registry.d.ts +32 -0
  114. package/dist/mcp/room-registry.d.ts.map +1 -0
  115. package/dist/mcp/room.d.ts +28 -0
  116. package/dist/mcp/room.d.ts.map +1 -0
  117. package/dist/plugins/agent-memory/index.js +1 -1
  118. package/dist/plugins/idea-garden/index.js +1 -1
  119. package/dist/plugins/plan-approval/index.js +1 -1
  120. package/dist/plugins/proactive-watcher/index.js +1 -1
  121. package/dist/protocol/envelope.d.ts +30 -0
  122. package/dist/protocol/envelope.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +3 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/whereami.d.ts +33 -0
  126. package/dist/protocol/whereami.d.ts.map +1 -0
  127. package/dist/query-KHDDIR5G.js +31 -0
  128. package/dist/react/index.js +3 -3
  129. package/dist/react/realtime.js +1 -1
  130. package/dist/react/schema-hooks.js +6 -6
  131. package/dist/realtime/index.js +3 -3
  132. package/dist/realtime/relay-server.d.ts.map +1 -1
  133. package/dist/realtime/room.d.ts.map +1 -1
  134. package/dist/realtime.bundle.js +2 -0
  135. package/dist/relay-server-BT6DCJ7F.js +12 -0
  136. package/dist/relay-server-MPQVGNQU.js +12 -0
  137. package/dist/relay-server-PAPW2EWC.js +12 -0
  138. package/dist/remote-manager-6ERQUBSL.js +224 -0
  139. package/dist/remote-manager-G665WWYY.js +224 -0
  140. package/dist/remote-manager-HJTEZ4OF.js +224 -0
  141. package/dist/remote-manager-NYP2Y5UR.js +224 -0
  142. package/dist/remote-manager-WGLCAMMC.js +224 -0
  143. package/dist/scaffold/write.d.ts.map +1 -1
  144. package/dist/schema/index.js +1 -1
  145. package/dist/server/cors.d.ts +13 -0
  146. package/dist/server/cors.d.ts.map +1 -0
  147. package/dist/server/deploy-gateway.d.ts +27 -0
  148. package/dist/server/deploy-gateway.d.ts.map +1 -0
  149. package/dist/server/deploy.d.ts +1 -1
  150. package/dist/server/deploy.d.ts.map +1 -1
  151. package/dist/server/deploy.js +10 -0
  152. package/dist/server/discovery-mcp-gateway.d.ts +13 -0
  153. package/dist/server/discovery-mcp-gateway.d.ts.map +1 -0
  154. package/dist/server/index.js +44 -37
  155. package/dist/server/mcp-gateway.d.ts +27 -0
  156. package/dist/server/mcp-gateway.d.ts.map +1 -0
  157. package/dist/server/mcp-oauth-metadata.d.ts +31 -0
  158. package/dist/server/mcp-oauth-metadata.d.ts.map +1 -0
  159. package/dist/server/node-adapter.d.ts +7 -0
  160. package/dist/server/node-adapter.d.ts.map +1 -1
  161. package/dist/server/node-adapter.js +2 -2
  162. package/dist/server/realtime.d.ts.map +1 -1
  163. package/dist/server/server.d.ts +8 -0
  164. package/dist/server/server.d.ts.map +1 -1
  165. package/dist/server/streamable-mcp-gateway.d.ts +12 -0
  166. package/dist/server/streamable-mcp-gateway.d.ts.map +1 -0
  167. package/dist/server/usage-meter.d.ts +11 -0
  168. package/dist/server/usage-meter.d.ts.map +1 -1
  169. package/dist/server-4VEZHXXS.js +23 -0
  170. package/dist/{server-ZVWGLLRF.js → server-556BMK4C.js} +1 -1
  171. package/dist/server-FQT2VYRE.js +23 -0
  172. package/dist/server-HGZE4ECC.js +23 -0
  173. package/dist/server-J4JKEAMH.js +23 -0
  174. package/dist/server-LXPM5TFR.js +23 -0
  175. package/dist/{server-MB3OPSPI.js → server-POB4NEUX.js} +2 -2
  176. package/dist/server-VJKAPGPG.js +23 -0
  177. package/dist/server-YHS3XIIG.js +23 -0
  178. package/dist/server-ZHTPWPXS.js +23 -0
  179. package/dist/sprites-NC6D7YZS.js +27 -0
  180. package/dist/svelte/index.js +3 -3
  181. package/dist/svelte/schema-hooks.js +4 -4
  182. package/dist/sync/index.js +4 -4
  183. package/dist/tenancy-2SZTP4UD.js +16 -0
  184. package/dist/tenancy-7MTSESMJ.js +16 -0
  185. package/dist/tenancy-U4E7ZEAG.js +16 -0
  186. package/dist/vcs/decompose.d.ts.map +1 -1
  187. package/dist/vcs/index.js +5 -5
  188. package/dist/vcs/lane-disk-materialize.d.ts +11 -0
  189. package/dist/vcs/lane-disk-materialize.d.ts.map +1 -0
  190. package/dist/vcs/lane-worktree.d.ts +21 -0
  191. package/dist/vcs/lane-worktree.d.ts.map +1 -0
  192. package/dist/vcs/store.d.ts +28 -0
  193. package/dist/vcs/store.d.ts.map +1 -0
  194. package/dist/vcs/types.d.ts +5 -0
  195. package/dist/vcs/types.d.ts.map +1 -1
  196. package/dist/vm-config-YZRJ3KUB.js +21 -0
  197. package/dist/vue/index.js +3 -3
  198. package/dist/vue/schema-hooks.js +4 -4
  199. package/package.json +4 -3
  200. package/dist/chunk-FF36CQHZ.js +0 -61
  201. package/dist/chunk-GFZCJ4EH.js +0 -108
  202. package/dist/chunk-KIJITUZB.js +0 -419
  203. package/dist/chunk-SGMDTWJJ.js +0 -149
  204. package/dist/chunk-UQISRW6T.js +0 -203
  205. package/dist/db/trellis.css +0 -1
  206. package/dist/deploy-LQ7GUGJ5.js +0 -9
  207. package/dist/deploy-YNVG5E4E.js +0 -9
  208. package/dist/deploy-cli-24BCHAXY.js +0 -67
  209. package/dist/sprites-RU3E4XQN.js +0 -15
  210. package/dist/tenancy-NBLLGCNJ.js +0 -14
@@ -0,0 +1,2389 @@
1
+ import {
2
+ AjvJsonSchemaValidator,
3
+ CallToolRequestSchema,
4
+ CallToolResultSchema,
5
+ CompleteResultSchema,
6
+ CreateMessageRequestSchema,
7
+ CreateMessageResultSchema,
8
+ CreateMessageResultWithToolsSchema,
9
+ CreateTaskResultSchema,
10
+ ElicitRequestSchema,
11
+ ElicitResultSchema,
12
+ EmptyResultSchema,
13
+ ErrorCode,
14
+ GetPromptResultSchema,
15
+ InitializeResultSchema,
16
+ JSONRPCMessageSchema,
17
+ LATEST_PROTOCOL_VERSION,
18
+ ListChangedOptionsBaseSchema,
19
+ ListPromptsResultSchema,
20
+ ListResourceTemplatesResultSchema,
21
+ ListResourcesResultSchema,
22
+ ListToolsRequestSchema,
23
+ ListToolsResultSchema,
24
+ McpError,
25
+ PromptListChangedNotificationSchema,
26
+ Protocol,
27
+ ReadResourceResultSchema,
28
+ ResourceListChangedNotificationSchema,
29
+ SUPPORTED_PROTOCOL_VERSIONS,
30
+ Server,
31
+ ToolListChangedNotificationSchema,
32
+ assertClientRequestTaskCapability,
33
+ assertToolsCallTaskCapability,
34
+ getObjectShape,
35
+ isInitializedNotification,
36
+ isJSONRPCRequest,
37
+ isJSONRPCResultResponse,
38
+ isZ4Schema,
39
+ mergeCapabilities,
40
+ resolveMcpTenantId,
41
+ safeParse
42
+ } from "./chunk-4GPUIE7O.js";
43
+ import "./chunk-7M734RAO.js";
44
+ import {
45
+ roomMcpPathForUrl
46
+ } from "./chunk-V2ASD6RQ.js";
47
+ import "./chunk-UZRUP7QW.js";
48
+ import {
49
+ readConfig
50
+ } from "./chunk-JA7AIHRK.js";
51
+ import "./chunk-SZ3VAB5P.js";
52
+ import "./chunk-OB4CMMX6.js";
53
+ import "./chunk-QS7J732Q.js";
54
+ import "./chunk-6CTA6MCE.js";
55
+ import "./chunk-G3XIHPSQ.js";
56
+ import "./chunk-2ESYSVXG.js";
57
+
58
+ // src/mcp/bridge.ts
59
+ import process2 from "node:process";
60
+
61
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
62
+ var ExperimentalClientTasks = class {
63
+ constructor(_client) {
64
+ this._client = _client;
65
+ }
66
+ /**
67
+ * Calls a tool and returns an AsyncGenerator that yields response messages.
68
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
69
+ *
70
+ * This method provides streaming access to tool execution, allowing you to
71
+ * observe intermediate task status updates for long-running tool calls.
72
+ * Automatically validates structured output if the tool has an outputSchema.
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
77
+ * for await (const message of stream) {
78
+ * switch (message.type) {
79
+ * case 'taskCreated':
80
+ * console.log('Tool execution started:', message.task.taskId);
81
+ * break;
82
+ * case 'taskStatus':
83
+ * console.log('Tool status:', message.task.status);
84
+ * break;
85
+ * case 'result':
86
+ * console.log('Tool result:', message.result);
87
+ * break;
88
+ * case 'error':
89
+ * console.error('Tool error:', message.error);
90
+ * break;
91
+ * }
92
+ * }
93
+ * ```
94
+ *
95
+ * @param params - Tool call parameters (name and arguments)
96
+ * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
97
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
98
+ * @returns AsyncGenerator that yields ResponseMessage objects
99
+ *
100
+ * @experimental
101
+ */
102
+ async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
103
+ const clientInternal = this._client;
104
+ const optionsWithTask = {
105
+ ...options,
106
+ // We check if the tool is known to be a task during auto-configuration, but assume
107
+ // the caller knows what they're doing if they pass this explicitly
108
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
109
+ };
110
+ const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
111
+ const validator = clientInternal.getToolOutputValidator(params.name);
112
+ for await (const message of stream) {
113
+ if (message.type === "result" && validator) {
114
+ const result = message.result;
115
+ if (!result.structuredContent && !result.isError) {
116
+ yield {
117
+ type: "error",
118
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
119
+ };
120
+ return;
121
+ }
122
+ if (result.structuredContent) {
123
+ try {
124
+ const validationResult = validator(result.structuredContent);
125
+ if (!validationResult.valid) {
126
+ yield {
127
+ type: "error",
128
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
129
+ };
130
+ return;
131
+ }
132
+ } catch (error) {
133
+ if (error instanceof McpError) {
134
+ yield { type: "error", error };
135
+ return;
136
+ }
137
+ yield {
138
+ type: "error",
139
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
140
+ };
141
+ return;
142
+ }
143
+ }
144
+ }
145
+ yield message;
146
+ }
147
+ }
148
+ /**
149
+ * Gets the current status of a task.
150
+ *
151
+ * @param taskId - The task identifier
152
+ * @param options - Optional request options
153
+ * @returns The task status
154
+ *
155
+ * @experimental
156
+ */
157
+ async getTask(taskId, options) {
158
+ return this._client.getTask({ taskId }, options);
159
+ }
160
+ /**
161
+ * Retrieves the result of a completed task.
162
+ *
163
+ * @param taskId - The task identifier
164
+ * @param resultSchema - Zod schema for validating the result
165
+ * @param options - Optional request options
166
+ * @returns The task result
167
+ *
168
+ * @experimental
169
+ */
170
+ async getTaskResult(taskId, resultSchema, options) {
171
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
172
+ }
173
+ /**
174
+ * Lists tasks with optional pagination.
175
+ *
176
+ * @param cursor - Optional pagination cursor
177
+ * @param options - Optional request options
178
+ * @returns List of tasks with optional next cursor
179
+ *
180
+ * @experimental
181
+ */
182
+ async listTasks(cursor, options) {
183
+ return this._client.listTasks(cursor ? { cursor } : void 0, options);
184
+ }
185
+ /**
186
+ * Cancels a running task.
187
+ *
188
+ * @param taskId - The task identifier
189
+ * @param options - Optional request options
190
+ *
191
+ * @experimental
192
+ */
193
+ async cancelTask(taskId, options) {
194
+ return this._client.cancelTask({ taskId }, options);
195
+ }
196
+ /**
197
+ * Sends a request and returns an AsyncGenerator that yields response messages.
198
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
199
+ *
200
+ * This method provides streaming access to request processing, allowing you to
201
+ * observe intermediate task status updates for task-augmented requests.
202
+ *
203
+ * @param request - The request to send
204
+ * @param resultSchema - Zod schema for validating the result
205
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
206
+ * @returns AsyncGenerator that yields ResponseMessage objects
207
+ *
208
+ * @experimental
209
+ */
210
+ requestStream(request, resultSchema, options) {
211
+ return this._client.requestStream(request, resultSchema, options);
212
+ }
213
+ };
214
+
215
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
216
+ function applyElicitationDefaults(schema, data) {
217
+ if (!schema || data === null || typeof data !== "object")
218
+ return;
219
+ if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
220
+ const obj = data;
221
+ const props = schema.properties;
222
+ for (const key of Object.keys(props)) {
223
+ const propSchema = props[key];
224
+ if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
225
+ obj[key] = propSchema.default;
226
+ }
227
+ if (obj[key] !== void 0) {
228
+ applyElicitationDefaults(propSchema, obj[key]);
229
+ }
230
+ }
231
+ }
232
+ if (Array.isArray(schema.anyOf)) {
233
+ for (const sub of schema.anyOf) {
234
+ if (typeof sub !== "boolean") {
235
+ applyElicitationDefaults(sub, data);
236
+ }
237
+ }
238
+ }
239
+ if (Array.isArray(schema.oneOf)) {
240
+ for (const sub of schema.oneOf) {
241
+ if (typeof sub !== "boolean") {
242
+ applyElicitationDefaults(sub, data);
243
+ }
244
+ }
245
+ }
246
+ }
247
+ function getSupportedElicitationModes(capabilities) {
248
+ if (!capabilities) {
249
+ return { supportsFormMode: false, supportsUrlMode: false };
250
+ }
251
+ const hasFormCapability = capabilities.form !== void 0;
252
+ const hasUrlCapability = capabilities.url !== void 0;
253
+ const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
254
+ const supportsUrlMode = hasUrlCapability;
255
+ return { supportsFormMode, supportsUrlMode };
256
+ }
257
+ var Client = class extends Protocol {
258
+ /**
259
+ * Initializes this client with the given name and version information.
260
+ */
261
+ constructor(_clientInfo, options) {
262
+ super(options);
263
+ this._clientInfo = _clientInfo;
264
+ this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
265
+ this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
266
+ this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
267
+ this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
268
+ this._capabilities = options?.capabilities ?? {};
269
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
270
+ if (options?.listChanged) {
271
+ this._pendingListChangedConfig = options.listChanged;
272
+ }
273
+ }
274
+ /**
275
+ * Set up handlers for list changed notifications based on config and server capabilities.
276
+ * This should only be called after initialization when server capabilities are known.
277
+ * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
278
+ * @internal
279
+ */
280
+ _setupListChangedHandlers(config) {
281
+ if (config.tools && this._serverCapabilities?.tools?.listChanged) {
282
+ this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
283
+ const result = await this.listTools();
284
+ return result.tools;
285
+ });
286
+ }
287
+ if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
288
+ this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
289
+ const result = await this.listPrompts();
290
+ return result.prompts;
291
+ });
292
+ }
293
+ if (config.resources && this._serverCapabilities?.resources?.listChanged) {
294
+ this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
295
+ const result = await this.listResources();
296
+ return result.resources;
297
+ });
298
+ }
299
+ }
300
+ /**
301
+ * Access experimental features.
302
+ *
303
+ * WARNING: These APIs are experimental and may change without notice.
304
+ *
305
+ * @experimental
306
+ */
307
+ get experimental() {
308
+ if (!this._experimental) {
309
+ this._experimental = {
310
+ tasks: new ExperimentalClientTasks(this)
311
+ };
312
+ }
313
+ return this._experimental;
314
+ }
315
+ /**
316
+ * Registers new capabilities. This can only be called before connecting to a transport.
317
+ *
318
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
319
+ */
320
+ registerCapabilities(capabilities) {
321
+ if (this.transport) {
322
+ throw new Error("Cannot register capabilities after connecting to transport");
323
+ }
324
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
325
+ }
326
+ /**
327
+ * Override request handler registration to enforce client-side validation for elicitation.
328
+ */
329
+ setRequestHandler(requestSchema, handler) {
330
+ const shape = getObjectShape(requestSchema);
331
+ const methodSchema = shape?.method;
332
+ if (!methodSchema) {
333
+ throw new Error("Schema is missing a method literal");
334
+ }
335
+ let methodValue;
336
+ if (isZ4Schema(methodSchema)) {
337
+ const v4Schema = methodSchema;
338
+ const v4Def = v4Schema._zod?.def;
339
+ methodValue = v4Def?.value ?? v4Schema.value;
340
+ } else {
341
+ const v3Schema = methodSchema;
342
+ const legacyDef = v3Schema._def;
343
+ methodValue = legacyDef?.value ?? v3Schema.value;
344
+ }
345
+ if (typeof methodValue !== "string") {
346
+ throw new Error("Schema method literal must be a string");
347
+ }
348
+ const method = methodValue;
349
+ if (method === "elicitation/create") {
350
+ const wrappedHandler = async (request, extra) => {
351
+ const validatedRequest = safeParse(ElicitRequestSchema, request);
352
+ if (!validatedRequest.success) {
353
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
354
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
355
+ }
356
+ const { params } = validatedRequest.data;
357
+ params.mode = params.mode ?? "form";
358
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
359
+ if (params.mode === "form" && !supportsFormMode) {
360
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
361
+ }
362
+ if (params.mode === "url" && !supportsUrlMode) {
363
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
364
+ }
365
+ const result = await Promise.resolve(handler(request, extra));
366
+ if (params.task) {
367
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
368
+ if (!taskValidationResult.success) {
369
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
370
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
371
+ }
372
+ return taskValidationResult.data;
373
+ }
374
+ const validationResult = safeParse(ElicitResultSchema, result);
375
+ if (!validationResult.success) {
376
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
377
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
378
+ }
379
+ const validatedResult = validationResult.data;
380
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
381
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
382
+ if (this._capabilities.elicitation?.form?.applyDefaults) {
383
+ try {
384
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
385
+ } catch {
386
+ }
387
+ }
388
+ }
389
+ return validatedResult;
390
+ };
391
+ return super.setRequestHandler(requestSchema, wrappedHandler);
392
+ }
393
+ if (method === "sampling/createMessage") {
394
+ const wrappedHandler = async (request, extra) => {
395
+ const validatedRequest = safeParse(CreateMessageRequestSchema, request);
396
+ if (!validatedRequest.success) {
397
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
398
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
399
+ }
400
+ const { params } = validatedRequest.data;
401
+ const result = await Promise.resolve(handler(request, extra));
402
+ if (params.task) {
403
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
404
+ if (!taskValidationResult.success) {
405
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
406
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
407
+ }
408
+ return taskValidationResult.data;
409
+ }
410
+ const hasTools = params.tools || params.toolChoice;
411
+ const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
412
+ const validationResult = safeParse(resultSchema, result);
413
+ if (!validationResult.success) {
414
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
415
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
416
+ }
417
+ return validationResult.data;
418
+ };
419
+ return super.setRequestHandler(requestSchema, wrappedHandler);
420
+ }
421
+ return super.setRequestHandler(requestSchema, handler);
422
+ }
423
+ assertCapability(capability, method) {
424
+ if (!this._serverCapabilities?.[capability]) {
425
+ throw new Error(`Server does not support ${capability} (required for ${method})`);
426
+ }
427
+ }
428
+ async connect(transport, options) {
429
+ await super.connect(transport);
430
+ if (transport.sessionId !== void 0) {
431
+ return;
432
+ }
433
+ try {
434
+ const result = await this.request({
435
+ method: "initialize",
436
+ params: {
437
+ protocolVersion: LATEST_PROTOCOL_VERSION,
438
+ capabilities: this._capabilities,
439
+ clientInfo: this._clientInfo
440
+ }
441
+ }, InitializeResultSchema, options);
442
+ if (result === void 0) {
443
+ throw new Error(`Server sent invalid initialize result: ${result}`);
444
+ }
445
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
446
+ throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
447
+ }
448
+ this._serverCapabilities = result.capabilities;
449
+ this._serverVersion = result.serverInfo;
450
+ if (transport.setProtocolVersion) {
451
+ transport.setProtocolVersion(result.protocolVersion);
452
+ }
453
+ this._instructions = result.instructions;
454
+ await this.notification({
455
+ method: "notifications/initialized"
456
+ });
457
+ if (this._pendingListChangedConfig) {
458
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
459
+ this._pendingListChangedConfig = void 0;
460
+ }
461
+ } catch (error) {
462
+ void this.close();
463
+ throw error;
464
+ }
465
+ }
466
+ /**
467
+ * After initialization has completed, this will be populated with the server's reported capabilities.
468
+ */
469
+ getServerCapabilities() {
470
+ return this._serverCapabilities;
471
+ }
472
+ /**
473
+ * After initialization has completed, this will be populated with information about the server's name and version.
474
+ */
475
+ getServerVersion() {
476
+ return this._serverVersion;
477
+ }
478
+ /**
479
+ * After initialization has completed, this may be populated with information about the server's instructions.
480
+ */
481
+ getInstructions() {
482
+ return this._instructions;
483
+ }
484
+ assertCapabilityForMethod(method) {
485
+ switch (method) {
486
+ case "logging/setLevel":
487
+ if (!this._serverCapabilities?.logging) {
488
+ throw new Error(`Server does not support logging (required for ${method})`);
489
+ }
490
+ break;
491
+ case "prompts/get":
492
+ case "prompts/list":
493
+ if (!this._serverCapabilities?.prompts) {
494
+ throw new Error(`Server does not support prompts (required for ${method})`);
495
+ }
496
+ break;
497
+ case "resources/list":
498
+ case "resources/templates/list":
499
+ case "resources/read":
500
+ case "resources/subscribe":
501
+ case "resources/unsubscribe":
502
+ if (!this._serverCapabilities?.resources) {
503
+ throw new Error(`Server does not support resources (required for ${method})`);
504
+ }
505
+ if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
506
+ throw new Error(`Server does not support resource subscriptions (required for ${method})`);
507
+ }
508
+ break;
509
+ case "tools/call":
510
+ case "tools/list":
511
+ if (!this._serverCapabilities?.tools) {
512
+ throw new Error(`Server does not support tools (required for ${method})`);
513
+ }
514
+ break;
515
+ case "completion/complete":
516
+ if (!this._serverCapabilities?.completions) {
517
+ throw new Error(`Server does not support completions (required for ${method})`);
518
+ }
519
+ break;
520
+ case "initialize":
521
+ break;
522
+ case "ping":
523
+ break;
524
+ }
525
+ }
526
+ assertNotificationCapability(method) {
527
+ switch (method) {
528
+ case "notifications/roots/list_changed":
529
+ if (!this._capabilities.roots?.listChanged) {
530
+ throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
531
+ }
532
+ break;
533
+ case "notifications/initialized":
534
+ break;
535
+ case "notifications/cancelled":
536
+ break;
537
+ case "notifications/progress":
538
+ break;
539
+ }
540
+ }
541
+ assertRequestHandlerCapability(method) {
542
+ if (!this._capabilities) {
543
+ return;
544
+ }
545
+ switch (method) {
546
+ case "sampling/createMessage":
547
+ if (!this._capabilities.sampling) {
548
+ throw new Error(`Client does not support sampling capability (required for ${method})`);
549
+ }
550
+ break;
551
+ case "elicitation/create":
552
+ if (!this._capabilities.elicitation) {
553
+ throw new Error(`Client does not support elicitation capability (required for ${method})`);
554
+ }
555
+ break;
556
+ case "roots/list":
557
+ if (!this._capabilities.roots) {
558
+ throw new Error(`Client does not support roots capability (required for ${method})`);
559
+ }
560
+ break;
561
+ case "tasks/get":
562
+ case "tasks/list":
563
+ case "tasks/result":
564
+ case "tasks/cancel":
565
+ if (!this._capabilities.tasks) {
566
+ throw new Error(`Client does not support tasks capability (required for ${method})`);
567
+ }
568
+ break;
569
+ case "ping":
570
+ break;
571
+ }
572
+ }
573
+ assertTaskCapability(method) {
574
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
575
+ }
576
+ assertTaskHandlerCapability(method) {
577
+ if (!this._capabilities) {
578
+ return;
579
+ }
580
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
581
+ }
582
+ async ping(options) {
583
+ return this.request({ method: "ping" }, EmptyResultSchema, options);
584
+ }
585
+ async complete(params, options) {
586
+ return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
587
+ }
588
+ async setLoggingLevel(level, options) {
589
+ return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
590
+ }
591
+ async getPrompt(params, options) {
592
+ return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
593
+ }
594
+ async listPrompts(params, options) {
595
+ return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
596
+ }
597
+ async listResources(params, options) {
598
+ return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
599
+ }
600
+ async listResourceTemplates(params, options) {
601
+ return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
602
+ }
603
+ async readResource(params, options) {
604
+ return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
605
+ }
606
+ async subscribeResource(params, options) {
607
+ return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
608
+ }
609
+ async unsubscribeResource(params, options) {
610
+ return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
611
+ }
612
+ /**
613
+ * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
614
+ *
615
+ * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
616
+ */
617
+ async callTool(params, resultSchema = CallToolResultSchema, options) {
618
+ if (this.isToolTaskRequired(params.name)) {
619
+ throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
620
+ }
621
+ const result = await this.request({ method: "tools/call", params }, resultSchema, options);
622
+ const validator = this.getToolOutputValidator(params.name);
623
+ if (validator) {
624
+ if (!result.structuredContent && !result.isError) {
625
+ throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
626
+ }
627
+ if (result.structuredContent) {
628
+ try {
629
+ const validationResult = validator(result.structuredContent);
630
+ if (!validationResult.valid) {
631
+ throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
632
+ }
633
+ } catch (error) {
634
+ if (error instanceof McpError) {
635
+ throw error;
636
+ }
637
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
638
+ }
639
+ }
640
+ }
641
+ return result;
642
+ }
643
+ isToolTask(toolName) {
644
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
645
+ return false;
646
+ }
647
+ return this._cachedKnownTaskTools.has(toolName);
648
+ }
649
+ /**
650
+ * Check if a tool requires task-based execution.
651
+ * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
652
+ */
653
+ isToolTaskRequired(toolName) {
654
+ return this._cachedRequiredTaskTools.has(toolName);
655
+ }
656
+ /**
657
+ * Cache validators for tool output schemas.
658
+ * Called after listTools() to pre-compile validators for better performance.
659
+ */
660
+ cacheToolMetadata(tools) {
661
+ this._cachedToolOutputValidators.clear();
662
+ this._cachedKnownTaskTools.clear();
663
+ this._cachedRequiredTaskTools.clear();
664
+ for (const tool of tools) {
665
+ if (tool.outputSchema) {
666
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
667
+ this._cachedToolOutputValidators.set(tool.name, toolValidator);
668
+ }
669
+ const taskSupport = tool.execution?.taskSupport;
670
+ if (taskSupport === "required" || taskSupport === "optional") {
671
+ this._cachedKnownTaskTools.add(tool.name);
672
+ }
673
+ if (taskSupport === "required") {
674
+ this._cachedRequiredTaskTools.add(tool.name);
675
+ }
676
+ }
677
+ }
678
+ /**
679
+ * Get cached validator for a tool
680
+ */
681
+ getToolOutputValidator(toolName) {
682
+ return this._cachedToolOutputValidators.get(toolName);
683
+ }
684
+ async listTools(params, options) {
685
+ const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
686
+ this.cacheToolMetadata(result.tools);
687
+ return result;
688
+ }
689
+ /**
690
+ * Set up a single list changed handler.
691
+ * @internal
692
+ */
693
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
694
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
695
+ if (!parseResult.success) {
696
+ throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
697
+ }
698
+ if (typeof options.onChanged !== "function") {
699
+ throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
700
+ }
701
+ const { autoRefresh, debounceMs } = parseResult.data;
702
+ const { onChanged } = options;
703
+ const refresh = async () => {
704
+ if (!autoRefresh) {
705
+ onChanged(null, null);
706
+ return;
707
+ }
708
+ try {
709
+ const items = await fetcher();
710
+ onChanged(null, items);
711
+ } catch (e) {
712
+ const error = e instanceof Error ? e : new Error(String(e));
713
+ onChanged(error, null);
714
+ }
715
+ };
716
+ const handler = () => {
717
+ if (debounceMs) {
718
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
719
+ if (existingTimer) {
720
+ clearTimeout(existingTimer);
721
+ }
722
+ const timer = setTimeout(refresh, debounceMs);
723
+ this._listChangedDebounceTimers.set(listType, timer);
724
+ } else {
725
+ refresh();
726
+ }
727
+ };
728
+ this.setNotificationHandler(notificationSchema, handler);
729
+ }
730
+ async sendRootsListChanged() {
731
+ return this.notification({ method: "notifications/roots/list_changed" });
732
+ }
733
+ };
734
+
735
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
736
+ function normalizeHeaders(headers) {
737
+ if (!headers)
738
+ return {};
739
+ if (headers instanceof Headers) {
740
+ return Object.fromEntries(headers.entries());
741
+ }
742
+ if (Array.isArray(headers)) {
743
+ return Object.fromEntries(headers);
744
+ }
745
+ return { ...headers };
746
+ }
747
+ function createFetchWithInit(baseFetch = fetch, baseInit) {
748
+ if (!baseInit) {
749
+ return baseFetch;
750
+ }
751
+ return async (url2, init) => {
752
+ const mergedInit = {
753
+ ...baseInit,
754
+ ...init,
755
+ // Headers need special handling - merge instead of replace
756
+ headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
757
+ };
758
+ return baseFetch(url2, mergedInit);
759
+ };
760
+ }
761
+
762
+ // node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
763
+ var crypto;
764
+ crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
765
+ globalThis.crypto ?? // Node.js >18
766
+ import("node:crypto").then((m) => m.webcrypto);
767
+ async function getRandomValues(size) {
768
+ return (await crypto).getRandomValues(new Uint8Array(size));
769
+ }
770
+ async function random(size) {
771
+ const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
772
+ const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
773
+ let result = "";
774
+ while (result.length < size) {
775
+ const randomBytes = await getRandomValues(size - result.length);
776
+ for (const randomByte of randomBytes) {
777
+ if (randomByte < evenDistCutoff) {
778
+ result += mask[randomByte % mask.length];
779
+ }
780
+ }
781
+ }
782
+ return result;
783
+ }
784
+ async function generateVerifier(length) {
785
+ return await random(length);
786
+ }
787
+ async function generateChallenge(code_verifier) {
788
+ const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
789
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
790
+ }
791
+ async function pkceChallenge(length) {
792
+ if (!length)
793
+ length = 43;
794
+ if (length < 43 || length > 128) {
795
+ throw `Expected a length between 43 and 128. Received ${length}.`;
796
+ }
797
+ const verifier = await generateVerifier(length);
798
+ const challenge = await generateChallenge(verifier);
799
+ return {
800
+ code_verifier: verifier,
801
+ code_challenge: challenge
802
+ };
803
+ }
804
+
805
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
806
+ import * as z from "zod/v4";
807
+ var SafeUrlSchema = z.url().superRefine((val, ctx) => {
808
+ if (!URL.canParse(val)) {
809
+ ctx.addIssue({
810
+ code: z.ZodIssueCode.custom,
811
+ message: "URL must be parseable",
812
+ fatal: true
813
+ });
814
+ return z.NEVER;
815
+ }
816
+ }).refine((url2) => {
817
+ const u = new URL(url2);
818
+ return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
819
+ }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
820
+ var OAuthProtectedResourceMetadataSchema = z.looseObject({
821
+ resource: z.string().url(),
822
+ authorization_servers: z.array(SafeUrlSchema).optional(),
823
+ jwks_uri: z.string().url().optional(),
824
+ scopes_supported: z.array(z.string()).optional(),
825
+ bearer_methods_supported: z.array(z.string()).optional(),
826
+ resource_signing_alg_values_supported: z.array(z.string()).optional(),
827
+ resource_name: z.string().optional(),
828
+ resource_documentation: z.string().optional(),
829
+ resource_policy_uri: z.string().url().optional(),
830
+ resource_tos_uri: z.string().url().optional(),
831
+ tls_client_certificate_bound_access_tokens: z.boolean().optional(),
832
+ authorization_details_types_supported: z.array(z.string()).optional(),
833
+ dpop_signing_alg_values_supported: z.array(z.string()).optional(),
834
+ dpop_bound_access_tokens_required: z.boolean().optional()
835
+ });
836
+ var OAuthMetadataSchema = z.looseObject({
837
+ issuer: z.string(),
838
+ authorization_endpoint: SafeUrlSchema,
839
+ token_endpoint: SafeUrlSchema,
840
+ registration_endpoint: SafeUrlSchema.optional(),
841
+ scopes_supported: z.array(z.string()).optional(),
842
+ response_types_supported: z.array(z.string()),
843
+ response_modes_supported: z.array(z.string()).optional(),
844
+ grant_types_supported: z.array(z.string()).optional(),
845
+ token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
846
+ token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
847
+ service_documentation: SafeUrlSchema.optional(),
848
+ revocation_endpoint: SafeUrlSchema.optional(),
849
+ revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),
850
+ revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
851
+ introspection_endpoint: z.string().optional(),
852
+ introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),
853
+ introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
854
+ code_challenge_methods_supported: z.array(z.string()).optional(),
855
+ client_id_metadata_document_supported: z.boolean().optional()
856
+ });
857
+ var OpenIdProviderMetadataSchema = z.looseObject({
858
+ issuer: z.string(),
859
+ authorization_endpoint: SafeUrlSchema,
860
+ token_endpoint: SafeUrlSchema,
861
+ userinfo_endpoint: SafeUrlSchema.optional(),
862
+ jwks_uri: SafeUrlSchema,
863
+ registration_endpoint: SafeUrlSchema.optional(),
864
+ scopes_supported: z.array(z.string()).optional(),
865
+ response_types_supported: z.array(z.string()),
866
+ response_modes_supported: z.array(z.string()).optional(),
867
+ grant_types_supported: z.array(z.string()).optional(),
868
+ acr_values_supported: z.array(z.string()).optional(),
869
+ subject_types_supported: z.array(z.string()),
870
+ id_token_signing_alg_values_supported: z.array(z.string()),
871
+ id_token_encryption_alg_values_supported: z.array(z.string()).optional(),
872
+ id_token_encryption_enc_values_supported: z.array(z.string()).optional(),
873
+ userinfo_signing_alg_values_supported: z.array(z.string()).optional(),
874
+ userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),
875
+ userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),
876
+ request_object_signing_alg_values_supported: z.array(z.string()).optional(),
877
+ request_object_encryption_alg_values_supported: z.array(z.string()).optional(),
878
+ request_object_encryption_enc_values_supported: z.array(z.string()).optional(),
879
+ token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
880
+ token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
881
+ display_values_supported: z.array(z.string()).optional(),
882
+ claim_types_supported: z.array(z.string()).optional(),
883
+ claims_supported: z.array(z.string()).optional(),
884
+ service_documentation: z.string().optional(),
885
+ claims_locales_supported: z.array(z.string()).optional(),
886
+ ui_locales_supported: z.array(z.string()).optional(),
887
+ claims_parameter_supported: z.boolean().optional(),
888
+ request_parameter_supported: z.boolean().optional(),
889
+ request_uri_parameter_supported: z.boolean().optional(),
890
+ require_request_uri_registration: z.boolean().optional(),
891
+ op_policy_uri: SafeUrlSchema.optional(),
892
+ op_tos_uri: SafeUrlSchema.optional(),
893
+ client_id_metadata_document_supported: z.boolean().optional()
894
+ });
895
+ var OpenIdProviderDiscoveryMetadataSchema = z.object({
896
+ ...OpenIdProviderMetadataSchema.shape,
897
+ ...OAuthMetadataSchema.pick({
898
+ code_challenge_methods_supported: true
899
+ }).shape
900
+ });
901
+ var OAuthTokensSchema = z.object({
902
+ access_token: z.string(),
903
+ id_token: z.string().optional(),
904
+ // Optional for OAuth 2.1, but necessary in OpenID Connect
905
+ token_type: z.string(),
906
+ expires_in: z.coerce.number().optional(),
907
+ scope: z.string().optional(),
908
+ refresh_token: z.string().optional()
909
+ }).strip();
910
+ var OAuthErrorResponseSchema = z.object({
911
+ error: z.string(),
912
+ error_description: z.string().optional(),
913
+ error_uri: z.string().optional()
914
+ });
915
+ var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal("").transform(() => void 0));
916
+ var OAuthClientMetadataSchema = z.object({
917
+ redirect_uris: z.array(SafeUrlSchema),
918
+ token_endpoint_auth_method: z.string().optional(),
919
+ grant_types: z.array(z.string()).optional(),
920
+ response_types: z.array(z.string()).optional(),
921
+ client_name: z.string().optional(),
922
+ client_uri: SafeUrlSchema.optional(),
923
+ logo_uri: OptionalSafeUrlSchema,
924
+ scope: z.string().optional(),
925
+ contacts: z.array(z.string()).optional(),
926
+ tos_uri: OptionalSafeUrlSchema,
927
+ policy_uri: z.string().optional(),
928
+ jwks_uri: SafeUrlSchema.optional(),
929
+ jwks: z.any().optional(),
930
+ software_id: z.string().optional(),
931
+ software_version: z.string().optional(),
932
+ software_statement: z.string().optional()
933
+ }).strip();
934
+ var OAuthClientInformationSchema = z.object({
935
+ client_id: z.string(),
936
+ client_secret: z.string().optional(),
937
+ client_id_issued_at: z.number().optional(),
938
+ client_secret_expires_at: z.number().optional()
939
+ }).strip();
940
+ var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
941
+ var OAuthClientRegistrationErrorSchema = z.object({
942
+ error: z.string(),
943
+ error_description: z.string().optional()
944
+ }).strip();
945
+ var OAuthTokenRevocationRequestSchema = z.object({
946
+ token: z.string(),
947
+ token_type_hint: z.string().optional()
948
+ }).strip();
949
+
950
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
951
+ function resourceUrlFromServerUrl(url2) {
952
+ const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
953
+ resourceURL.hash = "";
954
+ return resourceURL;
955
+ }
956
+ function checkResourceAllowed({ requestedResource, configuredResource }) {
957
+ const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
958
+ const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
959
+ if (requested.origin !== configured.origin) {
960
+ return false;
961
+ }
962
+ if (requested.pathname.length < configured.pathname.length) {
963
+ return false;
964
+ }
965
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
966
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
967
+ return requestedPath.startsWith(configuredPath);
968
+ }
969
+
970
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
971
+ var OAuthError = class extends Error {
972
+ constructor(message, errorUri) {
973
+ super(message);
974
+ this.errorUri = errorUri;
975
+ this.name = this.constructor.name;
976
+ }
977
+ /**
978
+ * Converts the error to a standard OAuth error response object
979
+ */
980
+ toResponseObject() {
981
+ const response = {
982
+ error: this.errorCode,
983
+ error_description: this.message
984
+ };
985
+ if (this.errorUri) {
986
+ response.error_uri = this.errorUri;
987
+ }
988
+ return response;
989
+ }
990
+ get errorCode() {
991
+ return this.constructor.errorCode;
992
+ }
993
+ };
994
+ var InvalidRequestError = class extends OAuthError {
995
+ };
996
+ InvalidRequestError.errorCode = "invalid_request";
997
+ var InvalidClientError = class extends OAuthError {
998
+ };
999
+ InvalidClientError.errorCode = "invalid_client";
1000
+ var InvalidGrantError = class extends OAuthError {
1001
+ };
1002
+ InvalidGrantError.errorCode = "invalid_grant";
1003
+ var UnauthorizedClientError = class extends OAuthError {
1004
+ };
1005
+ UnauthorizedClientError.errorCode = "unauthorized_client";
1006
+ var UnsupportedGrantTypeError = class extends OAuthError {
1007
+ };
1008
+ UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
1009
+ var InvalidScopeError = class extends OAuthError {
1010
+ };
1011
+ InvalidScopeError.errorCode = "invalid_scope";
1012
+ var AccessDeniedError = class extends OAuthError {
1013
+ };
1014
+ AccessDeniedError.errorCode = "access_denied";
1015
+ var ServerError = class extends OAuthError {
1016
+ };
1017
+ ServerError.errorCode = "server_error";
1018
+ var TemporarilyUnavailableError = class extends OAuthError {
1019
+ };
1020
+ TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
1021
+ var UnsupportedResponseTypeError = class extends OAuthError {
1022
+ };
1023
+ UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
1024
+ var UnsupportedTokenTypeError = class extends OAuthError {
1025
+ };
1026
+ UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
1027
+ var InvalidTokenError = class extends OAuthError {
1028
+ };
1029
+ InvalidTokenError.errorCode = "invalid_token";
1030
+ var MethodNotAllowedError = class extends OAuthError {
1031
+ };
1032
+ MethodNotAllowedError.errorCode = "method_not_allowed";
1033
+ var TooManyRequestsError = class extends OAuthError {
1034
+ };
1035
+ TooManyRequestsError.errorCode = "too_many_requests";
1036
+ var InvalidClientMetadataError = class extends OAuthError {
1037
+ };
1038
+ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
1039
+ var InsufficientScopeError = class extends OAuthError {
1040
+ };
1041
+ InsufficientScopeError.errorCode = "insufficient_scope";
1042
+ var InvalidTargetError = class extends OAuthError {
1043
+ };
1044
+ InvalidTargetError.errorCode = "invalid_target";
1045
+ var OAUTH_ERRORS = {
1046
+ [InvalidRequestError.errorCode]: InvalidRequestError,
1047
+ [InvalidClientError.errorCode]: InvalidClientError,
1048
+ [InvalidGrantError.errorCode]: InvalidGrantError,
1049
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
1050
+ [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
1051
+ [InvalidScopeError.errorCode]: InvalidScopeError,
1052
+ [AccessDeniedError.errorCode]: AccessDeniedError,
1053
+ [ServerError.errorCode]: ServerError,
1054
+ [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
1055
+ [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
1056
+ [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
1057
+ [InvalidTokenError.errorCode]: InvalidTokenError,
1058
+ [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
1059
+ [TooManyRequestsError.errorCode]: TooManyRequestsError,
1060
+ [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
1061
+ [InsufficientScopeError.errorCode]: InsufficientScopeError,
1062
+ [InvalidTargetError.errorCode]: InvalidTargetError
1063
+ };
1064
+
1065
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
1066
+ var UnauthorizedError = class extends Error {
1067
+ constructor(message) {
1068
+ super(message ?? "Unauthorized");
1069
+ }
1070
+ };
1071
+ function isClientAuthMethod(method) {
1072
+ return ["client_secret_basic", "client_secret_post", "none"].includes(method);
1073
+ }
1074
+ var AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
1075
+ var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
1076
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
1077
+ const hasClientSecret = clientInformation.client_secret !== void 0;
1078
+ if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
1079
+ return clientInformation.token_endpoint_auth_method;
1080
+ }
1081
+ if (supportedMethods.length === 0) {
1082
+ return hasClientSecret ? "client_secret_basic" : "none";
1083
+ }
1084
+ if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
1085
+ return "client_secret_basic";
1086
+ }
1087
+ if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
1088
+ return "client_secret_post";
1089
+ }
1090
+ if (supportedMethods.includes("none")) {
1091
+ return "none";
1092
+ }
1093
+ return hasClientSecret ? "client_secret_post" : "none";
1094
+ }
1095
+ function applyClientAuthentication(method, clientInformation, headers, params) {
1096
+ const { client_id, client_secret } = clientInformation;
1097
+ switch (method) {
1098
+ case "client_secret_basic":
1099
+ applyBasicAuth(client_id, client_secret, headers);
1100
+ return;
1101
+ case "client_secret_post":
1102
+ applyPostAuth(client_id, client_secret, params);
1103
+ return;
1104
+ case "none":
1105
+ applyPublicAuth(client_id, params);
1106
+ return;
1107
+ default:
1108
+ throw new Error(`Unsupported client authentication method: ${method}`);
1109
+ }
1110
+ }
1111
+ function applyBasicAuth(clientId, clientSecret, headers) {
1112
+ if (!clientSecret) {
1113
+ throw new Error("client_secret_basic authentication requires a client_secret");
1114
+ }
1115
+ const credentials = btoa(`${clientId}:${clientSecret}`);
1116
+ headers.set("Authorization", `Basic ${credentials}`);
1117
+ }
1118
+ function applyPostAuth(clientId, clientSecret, params) {
1119
+ params.set("client_id", clientId);
1120
+ if (clientSecret) {
1121
+ params.set("client_secret", clientSecret);
1122
+ }
1123
+ }
1124
+ function applyPublicAuth(clientId, params) {
1125
+ params.set("client_id", clientId);
1126
+ }
1127
+ async function parseErrorResponse(input) {
1128
+ const statusCode = input instanceof Response ? input.status : void 0;
1129
+ const body = input instanceof Response ? await input.text() : input;
1130
+ try {
1131
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
1132
+ const { error, error_description, error_uri } = result;
1133
+ const errorClass = OAUTH_ERRORS[error] || ServerError;
1134
+ return new errorClass(error_description || "", error_uri);
1135
+ } catch (error) {
1136
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
1137
+ return new ServerError(errorMessage);
1138
+ }
1139
+ }
1140
+ async function auth(provider, options) {
1141
+ try {
1142
+ return await authInternal(provider, options);
1143
+ } catch (error) {
1144
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
1145
+ await provider.invalidateCredentials?.("all");
1146
+ return await authInternal(provider, options);
1147
+ } else if (error instanceof InvalidGrantError) {
1148
+ await provider.invalidateCredentials?.("tokens");
1149
+ return await authInternal(provider, options);
1150
+ }
1151
+ throw error;
1152
+ }
1153
+ }
1154
+ async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
1155
+ const cachedState = await provider.discoveryState?.();
1156
+ let resourceMetadata;
1157
+ let authorizationServerUrl;
1158
+ let metadata;
1159
+ let effectiveResourceMetadataUrl = resourceMetadataUrl;
1160
+ if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
1161
+ effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
1162
+ }
1163
+ if (cachedState?.authorizationServerUrl) {
1164
+ authorizationServerUrl = cachedState.authorizationServerUrl;
1165
+ resourceMetadata = cachedState.resourceMetadata;
1166
+ metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
1167
+ if (!resourceMetadata) {
1168
+ try {
1169
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
1170
+ } catch {
1171
+ }
1172
+ }
1173
+ if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
1174
+ await provider.saveDiscoveryState?.({
1175
+ authorizationServerUrl: String(authorizationServerUrl),
1176
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
1177
+ resourceMetadata,
1178
+ authorizationServerMetadata: metadata
1179
+ });
1180
+ }
1181
+ } else {
1182
+ const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
1183
+ authorizationServerUrl = serverInfo.authorizationServerUrl;
1184
+ metadata = serverInfo.authorizationServerMetadata;
1185
+ resourceMetadata = serverInfo.resourceMetadata;
1186
+ await provider.saveDiscoveryState?.({
1187
+ authorizationServerUrl: String(authorizationServerUrl),
1188
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
1189
+ resourceMetadata,
1190
+ authorizationServerMetadata: metadata
1191
+ });
1192
+ }
1193
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
1194
+ const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
1195
+ let clientInformation = await Promise.resolve(provider.clientInformation());
1196
+ if (!clientInformation) {
1197
+ if (authorizationCode !== void 0) {
1198
+ throw new Error("Existing OAuth client information is required when exchanging an authorization code");
1199
+ }
1200
+ const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
1201
+ const clientMetadataUrl = provider.clientMetadataUrl;
1202
+ if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
1203
+ throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
1204
+ }
1205
+ const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
1206
+ if (shouldUseUrlBasedClientId) {
1207
+ clientInformation = {
1208
+ client_id: clientMetadataUrl
1209
+ };
1210
+ await provider.saveClientInformation?.(clientInformation);
1211
+ } else {
1212
+ if (!provider.saveClientInformation) {
1213
+ throw new Error("OAuth client information must be saveable for dynamic registration");
1214
+ }
1215
+ const fullInformation = await registerClient(authorizationServerUrl, {
1216
+ metadata,
1217
+ clientMetadata: provider.clientMetadata,
1218
+ scope: resolvedScope,
1219
+ fetchFn
1220
+ });
1221
+ await provider.saveClientInformation(fullInformation);
1222
+ clientInformation = fullInformation;
1223
+ }
1224
+ }
1225
+ const nonInteractiveFlow = !provider.redirectUrl;
1226
+ if (authorizationCode !== void 0 || nonInteractiveFlow) {
1227
+ const tokens2 = await fetchToken(provider, authorizationServerUrl, {
1228
+ metadata,
1229
+ resource,
1230
+ authorizationCode,
1231
+ fetchFn
1232
+ });
1233
+ await provider.saveTokens(tokens2);
1234
+ return "AUTHORIZED";
1235
+ }
1236
+ const tokens = await provider.tokens();
1237
+ if (tokens?.refresh_token) {
1238
+ try {
1239
+ const newTokens = await refreshAuthorization(authorizationServerUrl, {
1240
+ metadata,
1241
+ clientInformation,
1242
+ refreshToken: tokens.refresh_token,
1243
+ resource,
1244
+ addClientAuthentication: provider.addClientAuthentication,
1245
+ fetchFn
1246
+ });
1247
+ await provider.saveTokens(newTokens);
1248
+ return "AUTHORIZED";
1249
+ } catch (error) {
1250
+ if (!(error instanceof OAuthError) || error instanceof ServerError) {
1251
+ } else {
1252
+ throw error;
1253
+ }
1254
+ }
1255
+ }
1256
+ const state = provider.state ? await provider.state() : void 0;
1257
+ const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
1258
+ metadata,
1259
+ clientInformation,
1260
+ state,
1261
+ redirectUrl: provider.redirectUrl,
1262
+ scope: resolvedScope,
1263
+ resource
1264
+ });
1265
+ await provider.saveCodeVerifier(codeVerifier);
1266
+ await provider.redirectToAuthorization(authorizationUrl);
1267
+ return "REDIRECT";
1268
+ }
1269
+ function isHttpsUrl(value) {
1270
+ if (!value)
1271
+ return false;
1272
+ try {
1273
+ const url2 = new URL(value);
1274
+ return url2.protocol === "https:" && url2.pathname !== "/";
1275
+ } catch {
1276
+ return false;
1277
+ }
1278
+ }
1279
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
1280
+ const defaultResource = resourceUrlFromServerUrl(serverUrl);
1281
+ if (provider.validateResourceURL) {
1282
+ return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
1283
+ }
1284
+ if (!resourceMetadata) {
1285
+ return void 0;
1286
+ }
1287
+ if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
1288
+ throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
1289
+ }
1290
+ return new URL(resourceMetadata.resource);
1291
+ }
1292
+ function extractWWWAuthenticateParams(res) {
1293
+ const authenticateHeader = res.headers.get("WWW-Authenticate");
1294
+ if (!authenticateHeader) {
1295
+ return {};
1296
+ }
1297
+ const [type, scheme] = authenticateHeader.split(" ");
1298
+ if (type.toLowerCase() !== "bearer" || !scheme) {
1299
+ return {};
1300
+ }
1301
+ const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
1302
+ let resourceMetadataUrl;
1303
+ if (resourceMetadataMatch) {
1304
+ try {
1305
+ resourceMetadataUrl = new URL(resourceMetadataMatch);
1306
+ } catch {
1307
+ }
1308
+ }
1309
+ const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
1310
+ const error = extractFieldFromWwwAuth(res, "error") || void 0;
1311
+ return {
1312
+ resourceMetadataUrl,
1313
+ scope,
1314
+ error
1315
+ };
1316
+ }
1317
+ function extractFieldFromWwwAuth(response, fieldName) {
1318
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
1319
+ if (!wwwAuthHeader) {
1320
+ return null;
1321
+ }
1322
+ const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
1323
+ const match = wwwAuthHeader.match(pattern);
1324
+ if (match) {
1325
+ return match[1] || match[2];
1326
+ }
1327
+ return null;
1328
+ }
1329
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
1330
+ const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
1331
+ protocolVersion: opts?.protocolVersion,
1332
+ metadataUrl: opts?.resourceMetadataUrl
1333
+ });
1334
+ if (!response || response.status === 404) {
1335
+ await response?.body?.cancel();
1336
+ throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
1337
+ }
1338
+ if (!response.ok) {
1339
+ await response.body?.cancel();
1340
+ throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
1341
+ }
1342
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
1343
+ }
1344
+ async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
1345
+ try {
1346
+ return await fetchFn(url2, { headers });
1347
+ } catch (error) {
1348
+ if (error instanceof TypeError) {
1349
+ if (headers) {
1350
+ return fetchWithCorsRetry(url2, void 0, fetchFn);
1351
+ } else {
1352
+ return void 0;
1353
+ }
1354
+ }
1355
+ throw error;
1356
+ }
1357
+ }
1358
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
1359
+ if (pathname.endsWith("/")) {
1360
+ pathname = pathname.slice(0, -1);
1361
+ }
1362
+ return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
1363
+ }
1364
+ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
1365
+ const headers = {
1366
+ "MCP-Protocol-Version": protocolVersion
1367
+ };
1368
+ return await fetchWithCorsRetry(url2, headers, fetchFn);
1369
+ }
1370
+ function shouldAttemptFallback(response, pathname) {
1371
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
1372
+ }
1373
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
1374
+ const issuer = new URL(serverUrl);
1375
+ const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
1376
+ let url2;
1377
+ if (opts?.metadataUrl) {
1378
+ url2 = new URL(opts.metadataUrl);
1379
+ } else {
1380
+ const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
1381
+ url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
1382
+ url2.search = issuer.search;
1383
+ }
1384
+ let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
1385
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
1386
+ const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
1387
+ response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
1388
+ }
1389
+ return response;
1390
+ }
1391
+ function buildDiscoveryUrls(authorizationServerUrl) {
1392
+ const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
1393
+ const hasPath = url2.pathname !== "/";
1394
+ const urlsToTry = [];
1395
+ if (!hasPath) {
1396
+ urlsToTry.push({
1397
+ url: new URL("/.well-known/oauth-authorization-server", url2.origin),
1398
+ type: "oauth"
1399
+ });
1400
+ urlsToTry.push({
1401
+ url: new URL(`/.well-known/openid-configuration`, url2.origin),
1402
+ type: "oidc"
1403
+ });
1404
+ return urlsToTry;
1405
+ }
1406
+ let pathname = url2.pathname;
1407
+ if (pathname.endsWith("/")) {
1408
+ pathname = pathname.slice(0, -1);
1409
+ }
1410
+ urlsToTry.push({
1411
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
1412
+ type: "oauth"
1413
+ });
1414
+ urlsToTry.push({
1415
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
1416
+ type: "oidc"
1417
+ });
1418
+ urlsToTry.push({
1419
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
1420
+ type: "oidc"
1421
+ });
1422
+ return urlsToTry;
1423
+ }
1424
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
1425
+ const headers = {
1426
+ "MCP-Protocol-Version": protocolVersion,
1427
+ Accept: "application/json"
1428
+ };
1429
+ const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
1430
+ for (const { url: endpointUrl, type } of urlsToTry) {
1431
+ const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
1432
+ if (!response) {
1433
+ continue;
1434
+ }
1435
+ if (!response.ok) {
1436
+ await response.body?.cancel();
1437
+ if (response.status >= 400 && response.status < 500) {
1438
+ continue;
1439
+ }
1440
+ throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
1441
+ }
1442
+ if (type === "oauth") {
1443
+ return OAuthMetadataSchema.parse(await response.json());
1444
+ } else {
1445
+ return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
1446
+ }
1447
+ }
1448
+ return void 0;
1449
+ }
1450
+ async function discoverOAuthServerInfo(serverUrl, opts) {
1451
+ let resourceMetadata;
1452
+ let authorizationServerUrl;
1453
+ try {
1454
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
1455
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
1456
+ authorizationServerUrl = resourceMetadata.authorization_servers[0];
1457
+ }
1458
+ } catch {
1459
+ }
1460
+ if (!authorizationServerUrl) {
1461
+ authorizationServerUrl = String(new URL("/", serverUrl));
1462
+ }
1463
+ const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
1464
+ return {
1465
+ authorizationServerUrl,
1466
+ authorizationServerMetadata,
1467
+ resourceMetadata
1468
+ };
1469
+ }
1470
+ async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
1471
+ let authorizationUrl;
1472
+ if (metadata) {
1473
+ authorizationUrl = new URL(metadata.authorization_endpoint);
1474
+ if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
1475
+ throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
1476
+ }
1477
+ if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
1478
+ throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
1479
+ }
1480
+ } else {
1481
+ authorizationUrl = new URL("/authorize", authorizationServerUrl);
1482
+ }
1483
+ const challenge = await pkceChallenge();
1484
+ const codeVerifier = challenge.code_verifier;
1485
+ const codeChallenge = challenge.code_challenge;
1486
+ authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
1487
+ authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
1488
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1489
+ authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
1490
+ authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
1491
+ if (state) {
1492
+ authorizationUrl.searchParams.set("state", state);
1493
+ }
1494
+ if (scope) {
1495
+ authorizationUrl.searchParams.set("scope", scope);
1496
+ }
1497
+ if (scope?.includes("offline_access")) {
1498
+ authorizationUrl.searchParams.append("prompt", "consent");
1499
+ }
1500
+ if (resource) {
1501
+ authorizationUrl.searchParams.set("resource", resource.href);
1502
+ }
1503
+ return { authorizationUrl, codeVerifier };
1504
+ }
1505
+ function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
1506
+ return new URLSearchParams({
1507
+ grant_type: "authorization_code",
1508
+ code: authorizationCode,
1509
+ code_verifier: codeVerifier,
1510
+ redirect_uri: String(redirectUri)
1511
+ });
1512
+ }
1513
+ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
1514
+ const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
1515
+ const headers = new Headers({
1516
+ "Content-Type": "application/x-www-form-urlencoded",
1517
+ Accept: "application/json"
1518
+ });
1519
+ if (resource) {
1520
+ tokenRequestParams.set("resource", resource.href);
1521
+ }
1522
+ if (addClientAuthentication) {
1523
+ await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
1524
+ } else if (clientInformation) {
1525
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
1526
+ const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
1527
+ applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
1528
+ }
1529
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
1530
+ method: "POST",
1531
+ headers,
1532
+ body: tokenRequestParams
1533
+ });
1534
+ if (!response.ok) {
1535
+ throw await parseErrorResponse(response);
1536
+ }
1537
+ return OAuthTokensSchema.parse(await response.json());
1538
+ }
1539
+ async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
1540
+ const tokenRequestParams = new URLSearchParams({
1541
+ grant_type: "refresh_token",
1542
+ refresh_token: refreshToken
1543
+ });
1544
+ const tokens = await executeTokenRequest(authorizationServerUrl, {
1545
+ metadata,
1546
+ tokenRequestParams,
1547
+ clientInformation,
1548
+ addClientAuthentication,
1549
+ resource,
1550
+ fetchFn
1551
+ });
1552
+ return { refresh_token: refreshToken, ...tokens };
1553
+ }
1554
+ async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
1555
+ const scope = provider.clientMetadata.scope;
1556
+ let tokenRequestParams;
1557
+ if (provider.prepareTokenRequest) {
1558
+ tokenRequestParams = await provider.prepareTokenRequest(scope);
1559
+ }
1560
+ if (!tokenRequestParams) {
1561
+ if (!authorizationCode) {
1562
+ throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
1563
+ }
1564
+ if (!provider.redirectUrl) {
1565
+ throw new Error("redirectUrl is required for authorization_code flow");
1566
+ }
1567
+ const codeVerifier = await provider.codeVerifier();
1568
+ tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
1569
+ }
1570
+ const clientInformation = await provider.clientInformation();
1571
+ return executeTokenRequest(authorizationServerUrl, {
1572
+ metadata,
1573
+ tokenRequestParams,
1574
+ clientInformation: clientInformation ?? void 0,
1575
+ addClientAuthentication: provider.addClientAuthentication,
1576
+ resource,
1577
+ fetchFn
1578
+ });
1579
+ }
1580
+ async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
1581
+ let registrationUrl;
1582
+ if (metadata) {
1583
+ if (!metadata.registration_endpoint) {
1584
+ throw new Error("Incompatible auth server: does not support dynamic client registration");
1585
+ }
1586
+ registrationUrl = new URL(metadata.registration_endpoint);
1587
+ } else {
1588
+ registrationUrl = new URL("/register", authorizationServerUrl);
1589
+ }
1590
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
1591
+ method: "POST",
1592
+ headers: {
1593
+ "Content-Type": "application/json"
1594
+ },
1595
+ body: JSON.stringify({
1596
+ ...clientMetadata,
1597
+ ...scope !== void 0 ? { scope } : {}
1598
+ })
1599
+ });
1600
+ if (!response.ok) {
1601
+ throw await parseErrorResponse(response);
1602
+ }
1603
+ return OAuthClientInformationFullSchema.parse(await response.json());
1604
+ }
1605
+
1606
+ // node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js
1607
+ var ParseError = class extends Error {
1608
+ constructor(message, options) {
1609
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
1610
+ }
1611
+ };
1612
+ var LF = 10;
1613
+ var CR = 13;
1614
+ var SPACE = 32;
1615
+ function noop(_arg) {
1616
+ }
1617
+ function createParser(config) {
1618
+ if (typeof config == "function")
1619
+ throw new TypeError(
1620
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
1621
+ );
1622
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
1623
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
1624
+ function feed(chunk) {
1625
+ if (terminated)
1626
+ throw new Error(
1627
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
1628
+ );
1629
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
1630
+ const trailing2 = processLines(chunk);
1631
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
1632
+ return;
1633
+ }
1634
+ if (chunk.indexOf(`
1635
+ `) === -1 && chunk.indexOf("\r") === -1) {
1636
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
1637
+ return;
1638
+ }
1639
+ pendingFragments.push(chunk);
1640
+ const input = pendingFragments.join("");
1641
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
1642
+ const trailing = processLines(input);
1643
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
1644
+ }
1645
+ function checkBufferSize() {
1646
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
1647
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
1648
+ type: "max-buffer-size-exceeded"
1649
+ })
1650
+ )));
1651
+ }
1652
+ function processLines(chunk) {
1653
+ let searchIndex = 0;
1654
+ if (chunk.indexOf("\r") === -1) {
1655
+ let lfIndex = chunk.indexOf(`
1656
+ `, searchIndex);
1657
+ for (; lfIndex !== -1; ) {
1658
+ if (searchIndex === lfIndex) {
1659
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
1660
+ `, searchIndex);
1661
+ continue;
1662
+ }
1663
+ const firstCharCode = chunk.charCodeAt(searchIndex);
1664
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
1665
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
1666
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
1667
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
1668
+ `, searchIndex);
1669
+ continue;
1670
+ }
1671
+ data = dataLines === 0 ? value : `${data}
1672
+ ${value}`, dataLines++;
1673
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
1674
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
1675
+ lfIndex
1676
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
1677
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
1678
+ `, searchIndex);
1679
+ }
1680
+ return chunk.slice(searchIndex);
1681
+ }
1682
+ for (; searchIndex < chunk.length; ) {
1683
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
1684
+ `, searchIndex);
1685
+ let lineEnd = -1;
1686
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
1687
+ break;
1688
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
1689
+ }
1690
+ return chunk.slice(searchIndex);
1691
+ }
1692
+ function parseLine(chunk, start, end) {
1693
+ if (start === end) {
1694
+ dispatchEvent();
1695
+ return;
1696
+ }
1697
+ const firstCharCode = chunk.charCodeAt(start);
1698
+ if (isDataPrefix(chunk, start, firstCharCode)) {
1699
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
1700
+ data = dataLines === 0 ? value2 : `${data}
1701
+ ${value2}`, dataLines++;
1702
+ return;
1703
+ }
1704
+ if (isEventPrefix(chunk, start, firstCharCode)) {
1705
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
1706
+ return;
1707
+ }
1708
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
1709
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
1710
+ id = value2.includes("\0") ? void 0 : value2;
1711
+ return;
1712
+ }
1713
+ if (firstCharCode === 58) {
1714
+ if (onComment) {
1715
+ const line2 = chunk.slice(start, end);
1716
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
1717
+ }
1718
+ return;
1719
+ }
1720
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
1721
+ if (fieldSeparatorIndex === -1) {
1722
+ processField(line, "", line);
1723
+ return;
1724
+ }
1725
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
1726
+ processField(field, value, line);
1727
+ }
1728
+ function processField(field, value, line) {
1729
+ switch (field) {
1730
+ case "event":
1731
+ eventType = value || void 0;
1732
+ break;
1733
+ case "data":
1734
+ data = dataLines === 0 ? value : `${data}
1735
+ ${value}`, dataLines++;
1736
+ break;
1737
+ case "id":
1738
+ id = value.includes("\0") ? void 0 : value;
1739
+ break;
1740
+ case "retry":
1741
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
1742
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
1743
+ type: "invalid-retry",
1744
+ value,
1745
+ line
1746
+ })
1747
+ );
1748
+ break;
1749
+ default:
1750
+ onError(
1751
+ new ParseError(
1752
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
1753
+ { type: "unknown-field", field, value, line }
1754
+ )
1755
+ );
1756
+ break;
1757
+ }
1758
+ }
1759
+ function dispatchEvent() {
1760
+ dataLines > 0 && onEvent({
1761
+ id,
1762
+ event: eventType,
1763
+ data
1764
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
1765
+ }
1766
+ function reset(options = {}) {
1767
+ if (options.consume && pendingFragments.length > 0) {
1768
+ const incompleteLine = pendingFragments.join("");
1769
+ parseLine(incompleteLine, 0, incompleteLine.length);
1770
+ }
1771
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
1772
+ }
1773
+ return { feed, reset };
1774
+ }
1775
+ function isDataPrefix(chunk, i, firstCharCode) {
1776
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
1777
+ }
1778
+ function isEventPrefix(chunk, i, firstCharCode) {
1779
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
1780
+ }
1781
+
1782
+ // node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/stream.js
1783
+ var EventSourceParserStream = class extends TransformStream {
1784
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
1785
+ let parser;
1786
+ super({
1787
+ start(controller) {
1788
+ parser = createParser({
1789
+ onEvent: (event) => {
1790
+ controller.enqueue(event);
1791
+ },
1792
+ onError(error) {
1793
+ typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
1794
+ },
1795
+ onRetry,
1796
+ onComment,
1797
+ maxBufferSize
1798
+ });
1799
+ },
1800
+ transform(chunk) {
1801
+ parser.feed(chunk);
1802
+ }
1803
+ });
1804
+ }
1805
+ };
1806
+
1807
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
1808
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
1809
+ initialReconnectionDelay: 1e3,
1810
+ maxReconnectionDelay: 3e4,
1811
+ reconnectionDelayGrowFactor: 1.5,
1812
+ maxRetries: 2
1813
+ };
1814
+ var StreamableHTTPError = class extends Error {
1815
+ constructor(code, message) {
1816
+ super(`Streamable HTTP error: ${message}`);
1817
+ this.code = code;
1818
+ }
1819
+ };
1820
+ var StreamableHTTPClientTransport = class {
1821
+ constructor(url2, opts) {
1822
+ this._hasCompletedAuthFlow = false;
1823
+ this._url = url2;
1824
+ this._resourceMetadataUrl = void 0;
1825
+ this._scope = void 0;
1826
+ this._requestInit = opts?.requestInit;
1827
+ this._authProvider = opts?.authProvider;
1828
+ this._fetch = opts?.fetch;
1829
+ this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
1830
+ this._sessionId = opts?.sessionId;
1831
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
1832
+ }
1833
+ async _authThenStart() {
1834
+ if (!this._authProvider) {
1835
+ throw new UnauthorizedError("No auth provider");
1836
+ }
1837
+ let result;
1838
+ try {
1839
+ result = await auth(this._authProvider, {
1840
+ serverUrl: this._url,
1841
+ resourceMetadataUrl: this._resourceMetadataUrl,
1842
+ scope: this._scope,
1843
+ fetchFn: this._fetchWithInit
1844
+ });
1845
+ } catch (error) {
1846
+ this.onerror?.(error);
1847
+ throw error;
1848
+ }
1849
+ if (result !== "AUTHORIZED") {
1850
+ throw new UnauthorizedError();
1851
+ }
1852
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
1853
+ }
1854
+ async _commonHeaders() {
1855
+ const headers = {};
1856
+ if (this._authProvider) {
1857
+ const tokens = await this._authProvider.tokens();
1858
+ if (tokens) {
1859
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
1860
+ }
1861
+ }
1862
+ if (this._sessionId) {
1863
+ headers["mcp-session-id"] = this._sessionId;
1864
+ }
1865
+ if (this._protocolVersion) {
1866
+ headers["mcp-protocol-version"] = this._protocolVersion;
1867
+ }
1868
+ const extraHeaders = normalizeHeaders(this._requestInit?.headers);
1869
+ return new Headers({
1870
+ ...headers,
1871
+ ...extraHeaders
1872
+ });
1873
+ }
1874
+ async _startOrAuthSse(options) {
1875
+ const { resumptionToken } = options;
1876
+ try {
1877
+ const headers = await this._commonHeaders();
1878
+ headers.set("Accept", "text/event-stream");
1879
+ if (resumptionToken) {
1880
+ headers.set("last-event-id", resumptionToken);
1881
+ }
1882
+ const response = await (this._fetch ?? fetch)(this._url, {
1883
+ method: "GET",
1884
+ headers,
1885
+ signal: this._abortController?.signal
1886
+ });
1887
+ if (!response.ok) {
1888
+ await response.body?.cancel();
1889
+ if (response.status === 401 && this._authProvider) {
1890
+ return await this._authThenStart();
1891
+ }
1892
+ if (response.status === 405) {
1893
+ return;
1894
+ }
1895
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
1896
+ }
1897
+ this._handleSseStream(response.body, options, true);
1898
+ } catch (error) {
1899
+ this.onerror?.(error);
1900
+ throw error;
1901
+ }
1902
+ }
1903
+ /**
1904
+ * Calculates the next reconnection delay using backoff algorithm
1905
+ *
1906
+ * @param attempt Current reconnection attempt count for the specific stream
1907
+ * @returns Time to wait in milliseconds before next reconnection attempt
1908
+ */
1909
+ _getNextReconnectionDelay(attempt) {
1910
+ if (this._serverRetryMs !== void 0) {
1911
+ return this._serverRetryMs;
1912
+ }
1913
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
1914
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
1915
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
1916
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
1917
+ }
1918
+ /**
1919
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
1920
+ *
1921
+ * @param lastEventId The ID of the last received event for resumability
1922
+ * @param attemptCount Current reconnection attempt count for this specific stream
1923
+ */
1924
+ _scheduleReconnection(options, attemptCount = 0) {
1925
+ const maxRetries = this._reconnectionOptions.maxRetries;
1926
+ if (attemptCount >= maxRetries) {
1927
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
1928
+ return;
1929
+ }
1930
+ const delay = this._getNextReconnectionDelay(attemptCount);
1931
+ this._reconnectionTimeout = setTimeout(() => {
1932
+ this._startOrAuthSse(options).catch((error) => {
1933
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
1934
+ this._scheduleReconnection(options, attemptCount + 1);
1935
+ });
1936
+ }, delay);
1937
+ }
1938
+ _handleSseStream(stream, options, isReconnectable) {
1939
+ if (!stream) {
1940
+ return;
1941
+ }
1942
+ const { onresumptiontoken, replayMessageId } = options;
1943
+ let lastEventId;
1944
+ let hasPrimingEvent = false;
1945
+ let receivedResponse = false;
1946
+ const processStream = async () => {
1947
+ try {
1948
+ const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
1949
+ onRetry: (retryMs) => {
1950
+ this._serverRetryMs = retryMs;
1951
+ }
1952
+ })).getReader();
1953
+ while (true) {
1954
+ const { value: event, done } = await reader.read();
1955
+ if (done) {
1956
+ break;
1957
+ }
1958
+ if (event.id) {
1959
+ lastEventId = event.id;
1960
+ hasPrimingEvent = true;
1961
+ onresumptiontoken?.(event.id);
1962
+ }
1963
+ if (!event.data) {
1964
+ continue;
1965
+ }
1966
+ if (!event.event || event.event === "message") {
1967
+ try {
1968
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
1969
+ if (isJSONRPCResultResponse(message)) {
1970
+ receivedResponse = true;
1971
+ if (replayMessageId !== void 0) {
1972
+ message.id = replayMessageId;
1973
+ }
1974
+ }
1975
+ this.onmessage?.(message);
1976
+ } catch (error) {
1977
+ this.onerror?.(error);
1978
+ }
1979
+ }
1980
+ }
1981
+ const canResume = isReconnectable || hasPrimingEvent;
1982
+ const needsReconnect = canResume && !receivedResponse;
1983
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
1984
+ this._scheduleReconnection({
1985
+ resumptionToken: lastEventId,
1986
+ onresumptiontoken,
1987
+ replayMessageId
1988
+ }, 0);
1989
+ }
1990
+ } catch (error) {
1991
+ this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
1992
+ const canResume = isReconnectable || hasPrimingEvent;
1993
+ const needsReconnect = canResume && !receivedResponse;
1994
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
1995
+ try {
1996
+ this._scheduleReconnection({
1997
+ resumptionToken: lastEventId,
1998
+ onresumptiontoken,
1999
+ replayMessageId
2000
+ }, 0);
2001
+ } catch (error2) {
2002
+ this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
2003
+ }
2004
+ }
2005
+ }
2006
+ };
2007
+ processStream();
2008
+ }
2009
+ async start() {
2010
+ if (this._abortController) {
2011
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
2012
+ }
2013
+ this._abortController = new AbortController();
2014
+ }
2015
+ /**
2016
+ * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
2017
+ */
2018
+ async finishAuth(authorizationCode) {
2019
+ if (!this._authProvider) {
2020
+ throw new UnauthorizedError("No auth provider");
2021
+ }
2022
+ const result = await auth(this._authProvider, {
2023
+ serverUrl: this._url,
2024
+ authorizationCode,
2025
+ resourceMetadataUrl: this._resourceMetadataUrl,
2026
+ scope: this._scope,
2027
+ fetchFn: this._fetchWithInit
2028
+ });
2029
+ if (result !== "AUTHORIZED") {
2030
+ throw new UnauthorizedError("Failed to authorize");
2031
+ }
2032
+ }
2033
+ async close() {
2034
+ if (this._reconnectionTimeout) {
2035
+ clearTimeout(this._reconnectionTimeout);
2036
+ this._reconnectionTimeout = void 0;
2037
+ }
2038
+ this._abortController?.abort();
2039
+ this.onclose?.();
2040
+ }
2041
+ async send(message, options) {
2042
+ try {
2043
+ const { resumptionToken, onresumptiontoken } = options || {};
2044
+ if (resumptionToken) {
2045
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
2046
+ return;
2047
+ }
2048
+ const headers = await this._commonHeaders();
2049
+ headers.set("content-type", "application/json");
2050
+ headers.set("accept", "application/json, text/event-stream");
2051
+ const init = {
2052
+ ...this._requestInit,
2053
+ method: "POST",
2054
+ headers,
2055
+ body: JSON.stringify(message),
2056
+ signal: this._abortController?.signal
2057
+ };
2058
+ const response = await (this._fetch ?? fetch)(this._url, init);
2059
+ const sessionId = response.headers.get("mcp-session-id");
2060
+ if (sessionId) {
2061
+ this._sessionId = sessionId;
2062
+ }
2063
+ if (!response.ok) {
2064
+ const text = await response.text().catch(() => null);
2065
+ if (response.status === 401 && this._authProvider) {
2066
+ if (this._hasCompletedAuthFlow) {
2067
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
2068
+ }
2069
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
2070
+ this._resourceMetadataUrl = resourceMetadataUrl;
2071
+ this._scope = scope;
2072
+ const result = await auth(this._authProvider, {
2073
+ serverUrl: this._url,
2074
+ resourceMetadataUrl: this._resourceMetadataUrl,
2075
+ scope: this._scope,
2076
+ fetchFn: this._fetchWithInit
2077
+ });
2078
+ if (result !== "AUTHORIZED") {
2079
+ throw new UnauthorizedError();
2080
+ }
2081
+ this._hasCompletedAuthFlow = true;
2082
+ return this.send(message);
2083
+ }
2084
+ if (response.status === 403 && this._authProvider) {
2085
+ const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
2086
+ if (error === "insufficient_scope") {
2087
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
2088
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
2089
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
2090
+ }
2091
+ if (scope) {
2092
+ this._scope = scope;
2093
+ }
2094
+ if (resourceMetadataUrl) {
2095
+ this._resourceMetadataUrl = resourceMetadataUrl;
2096
+ }
2097
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
2098
+ const result = await auth(this._authProvider, {
2099
+ serverUrl: this._url,
2100
+ resourceMetadataUrl: this._resourceMetadataUrl,
2101
+ scope: this._scope,
2102
+ fetchFn: this._fetch
2103
+ });
2104
+ if (result !== "AUTHORIZED") {
2105
+ throw new UnauthorizedError();
2106
+ }
2107
+ return this.send(message);
2108
+ }
2109
+ }
2110
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
2111
+ }
2112
+ this._hasCompletedAuthFlow = false;
2113
+ this._lastUpscopingHeader = void 0;
2114
+ if (response.status === 202) {
2115
+ await response.body?.cancel();
2116
+ if (isInitializedNotification(message)) {
2117
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
2118
+ }
2119
+ return;
2120
+ }
2121
+ const messages = Array.isArray(message) ? message : [message];
2122
+ const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
2123
+ const contentType = response.headers.get("content-type");
2124
+ if (hasRequests) {
2125
+ if (contentType?.includes("text/event-stream")) {
2126
+ this._handleSseStream(response.body, { onresumptiontoken }, false);
2127
+ } else if (contentType?.includes("application/json")) {
2128
+ const data = await response.json();
2129
+ const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
2130
+ for (const msg of responseMessages) {
2131
+ this.onmessage?.(msg);
2132
+ }
2133
+ } else {
2134
+ await response.body?.cancel();
2135
+ throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
2136
+ }
2137
+ } else {
2138
+ await response.body?.cancel();
2139
+ }
2140
+ } catch (error) {
2141
+ this.onerror?.(error);
2142
+ throw error;
2143
+ }
2144
+ }
2145
+ get sessionId() {
2146
+ return this._sessionId;
2147
+ }
2148
+ /**
2149
+ * Terminates the current session by sending a DELETE request to the server.
2150
+ *
2151
+ * Clients that no longer need a particular session
2152
+ * (e.g., because the user is leaving the client application) SHOULD send an
2153
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
2154
+ * terminate the session.
2155
+ *
2156
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
2157
+ * the server does not allow clients to terminate sessions.
2158
+ */
2159
+ async terminateSession() {
2160
+ if (!this._sessionId) {
2161
+ return;
2162
+ }
2163
+ try {
2164
+ const headers = await this._commonHeaders();
2165
+ const init = {
2166
+ ...this._requestInit,
2167
+ method: "DELETE",
2168
+ headers,
2169
+ signal: this._abortController?.signal
2170
+ };
2171
+ const response = await (this._fetch ?? fetch)(this._url, init);
2172
+ await response.body?.cancel();
2173
+ if (!response.ok && response.status !== 405) {
2174
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
2175
+ }
2176
+ this._sessionId = void 0;
2177
+ } catch (error) {
2178
+ this.onerror?.(error);
2179
+ throw error;
2180
+ }
2181
+ }
2182
+ setProtocolVersion(version) {
2183
+ this._protocolVersion = version;
2184
+ }
2185
+ get protocolVersion() {
2186
+ return this._protocolVersion;
2187
+ }
2188
+ /**
2189
+ * Resume an SSE stream from a previous event ID.
2190
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
2191
+ *
2192
+ * @param lastEventId The event ID to resume from
2193
+ * @param options Optional callback to receive new resumption tokens
2194
+ */
2195
+ async resumeStream(lastEventId, options) {
2196
+ await this._startOrAuthSse({
2197
+ resumptionToken: lastEventId,
2198
+ onresumptiontoken: options?.onresumptiontoken
2199
+ });
2200
+ }
2201
+ };
2202
+
2203
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
2204
+ import process from "node:process";
2205
+
2206
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
2207
+ var ReadBuffer = class {
2208
+ append(chunk) {
2209
+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
2210
+ }
2211
+ readMessage() {
2212
+ if (!this._buffer) {
2213
+ return null;
2214
+ }
2215
+ const index = this._buffer.indexOf("\n");
2216
+ if (index === -1) {
2217
+ return null;
2218
+ }
2219
+ const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
2220
+ this._buffer = this._buffer.subarray(index + 1);
2221
+ return deserializeMessage(line);
2222
+ }
2223
+ clear() {
2224
+ this._buffer = void 0;
2225
+ }
2226
+ };
2227
+ function deserializeMessage(line) {
2228
+ return JSONRPCMessageSchema.parse(JSON.parse(line));
2229
+ }
2230
+ function serializeMessage(message) {
2231
+ return JSON.stringify(message) + "\n";
2232
+ }
2233
+
2234
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
2235
+ var StdioServerTransport = class {
2236
+ constructor(_stdin = process.stdin, _stdout = process.stdout) {
2237
+ this._stdin = _stdin;
2238
+ this._stdout = _stdout;
2239
+ this._readBuffer = new ReadBuffer();
2240
+ this._started = false;
2241
+ this._ondata = (chunk) => {
2242
+ this._readBuffer.append(chunk);
2243
+ this.processReadBuffer();
2244
+ };
2245
+ this._onerror = (error) => {
2246
+ this.onerror?.(error);
2247
+ };
2248
+ }
2249
+ /**
2250
+ * Starts listening for messages on stdin.
2251
+ */
2252
+ async start() {
2253
+ if (this._started) {
2254
+ throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
2255
+ }
2256
+ this._started = true;
2257
+ this._stdin.on("data", this._ondata);
2258
+ this._stdin.on("error", this._onerror);
2259
+ }
2260
+ processReadBuffer() {
2261
+ while (true) {
2262
+ try {
2263
+ const message = this._readBuffer.readMessage();
2264
+ if (message === null) {
2265
+ break;
2266
+ }
2267
+ this.onmessage?.(message);
2268
+ } catch (error) {
2269
+ this.onerror?.(error);
2270
+ }
2271
+ }
2272
+ }
2273
+ async close() {
2274
+ this._stdin.off("data", this._ondata);
2275
+ this._stdin.off("error", this._onerror);
2276
+ const remainingDataListeners = this._stdin.listenerCount("data");
2277
+ if (remainingDataListeners === 0) {
2278
+ this._stdin.pause();
2279
+ }
2280
+ this._readBuffer.clear();
2281
+ this.onclose?.();
2282
+ }
2283
+ send(message) {
2284
+ return new Promise((resolve) => {
2285
+ const json = serializeMessage(message);
2286
+ if (this._stdout.write(json)) {
2287
+ resolve();
2288
+ } else {
2289
+ this._stdout.once("drain", resolve);
2290
+ }
2291
+ });
2292
+ }
2293
+ };
2294
+
2295
+ // src/mcp/bridge.ts
2296
+ function resolveRoomMcpUrl(baseUrl) {
2297
+ const trimmed = baseUrl.replace(/\/$/, "");
2298
+ if (trimmed.endsWith("/mcp") || trimmed.endsWith("/trellis/mcp")) {
2299
+ return trimmed;
2300
+ }
2301
+ return `${trimmed}${roomMcpPathForUrl(trimmed)}`;
2302
+ }
2303
+ function resolveBridgeConfig(opts) {
2304
+ const configDir = opts.configDir ?? ".";
2305
+ const fileConfig = readConfig(configDir);
2306
+ const room = opts.room ?? process2.env.TRELLIS_ROOM_URL?.trim() ?? fileConfig?.url ?? (fileConfig?.mode === "local" && fileConfig.port ? `http://localhost:${fileConfig.port}` : void 0);
2307
+ if (!room) {
2308
+ throw new Error(
2309
+ "Room URL required. Pass --room <url> or run from a directory with remote .trellis-db.json"
2310
+ );
2311
+ }
2312
+ const apiKey = opts.apiKey ?? fileConfig?.apiKey;
2313
+ const tenantId = resolveMcpTenantId({
2314
+ toolTenantId: opts.tenant?.trim() || process2.env.TRELLIS_TENANT_ID?.trim() || void 0,
2315
+ roomSlug: opts.playgroundRoom?.trim() || process2.env.TRELLIS_PLAYGROUND_ROOM?.trim() || void 0
2316
+ });
2317
+ let url2 = resolveRoomMcpUrl(room);
2318
+ if (tenantId) {
2319
+ const parsed = new URL(url2);
2320
+ parsed.searchParams.set("tenantId", tenantId);
2321
+ url2 = parsed.toString();
2322
+ }
2323
+ return {
2324
+ url: url2,
2325
+ apiKey,
2326
+ tenantId
2327
+ };
2328
+ }
2329
+ async function connectRemoteRoomClient(config) {
2330
+ const headers = {};
2331
+ if (config.apiKey) {
2332
+ headers.Authorization = `Bearer ${config.apiKey}`;
2333
+ }
2334
+ if (config.tenantId) {
2335
+ headers["X-Trellis-Tenant"] = config.tenantId;
2336
+ }
2337
+ const client = new Client({
2338
+ name: "trellis-room-bridge",
2339
+ version: "0.1.0"
2340
+ });
2341
+ const transport = new StreamableHTTPClientTransport(new URL(config.url), {
2342
+ requestInit: Object.keys(headers).length ? { headers } : void 0
2343
+ });
2344
+ await client.connect(transport);
2345
+ return { client, transport };
2346
+ }
2347
+ function createRoomMcpProxyServer(remote) {
2348
+ const server = new Server(
2349
+ { name: "trellis-room-bridge", version: "0.1.0" },
2350
+ { capabilities: { tools: {} } }
2351
+ );
2352
+ server.setRequestHandler(ListToolsRequestSchema, async () => remote.listTools());
2353
+ server.setRequestHandler(
2354
+ CallToolRequestSchema,
2355
+ async (request) => remote.callTool(request.params)
2356
+ );
2357
+ return server;
2358
+ }
2359
+ async function runRoomMcpBridge(opts) {
2360
+ const config = resolveBridgeConfig(opts);
2361
+ const { client, transport } = await connectRemoteRoomClient(config);
2362
+ const server = createRoomMcpProxyServer(client);
2363
+ const stdio = new StdioServerTransport();
2364
+ let closing = false;
2365
+ const shutdown = async (code = 0) => {
2366
+ if (closing) return;
2367
+ closing = true;
2368
+ try {
2369
+ await transport.close();
2370
+ } catch {
2371
+ }
2372
+ process2.exit(code);
2373
+ };
2374
+ process2.on("SIGINT", () => void shutdown(0));
2375
+ process2.on("SIGTERM", () => void shutdown(0));
2376
+ process2.stdin.on("end", () => void shutdown(0));
2377
+ if (!opts.quiet) {
2378
+ const tenant = config.tenantId != null ? ` tenant=${config.tenantId}` : "";
2379
+ console.error(`Trellis Room MCP bridge \u2192 ${config.url}${tenant}`);
2380
+ }
2381
+ await server.connect(stdio);
2382
+ }
2383
+ export {
2384
+ connectRemoteRoomClient,
2385
+ createRoomMcpProxyServer,
2386
+ resolveBridgeConfig,
2387
+ resolveRoomMcpUrl,
2388
+ runRoomMcpBridge
2389
+ };