@lovable.dev/mcp-js 0.30.0-rc.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.internal.md +3 -3
  2. package/README.md +2 -25
  3. package/dist/{cors-5P69YRDK.js → authorize-9wHgaqeQ.js} +28 -79
  4. package/dist/{authorize-DNUlPT7k.d.ts → authorize-CqYsQYfa.d.ts} +1 -1
  5. package/dist/{cors-DIQIXIHY.cjs → authorize-DBk5GkN_.cjs} +33 -90
  6. package/dist/{authorize-9hTTG-qJ.d.cts → authorize-DIYS7zBP.d.cts} +1 -1
  7. package/dist/cli/extract-manifest.cjs +12 -7
  8. package/dist/cli/extract-manifest.js +12 -7
  9. package/dist/{errors-Cr95rSkB.cjs → errors-CN6Da8iz.cjs} +8 -23
  10. package/dist/{errors-Bwd1L0Rf.js → errors-DSe96Ffd.js} +8 -23
  11. package/dist/forwarded-Bhwcj22u.cjs +48 -0
  12. package/dist/forwarded-BlLF3dfc.js +43 -0
  13. package/dist/index.cjs +1 -38
  14. package/dist/index.d.cts +3 -3
  15. package/dist/index.d.ts +3 -3
  16. package/dist/index.js +1 -38
  17. package/dist/{io-D_5cuaEL.d.ts → io-DP3icuxa.d.ts} +1 -1
  18. package/dist/{io-CDV3mud0.d.cts → io-Dx0nPc1-.d.cts} +1 -1
  19. package/dist/mcp-BDsG9I0t.js +174 -0
  20. package/dist/mcp-CS1MF39p.cjs +179 -0
  21. package/dist/{package-ZFJI6B7S.js → package-CLhOKbJP.js} +1 -1
  22. package/dist/{package-QViIguII.cjs → package-C_8WAZRS.cjs} +1 -1
  23. package/dist/protocols/mcp/index.cjs +1 -1
  24. package/dist/protocols/mcp/index.d.cts +33 -3
  25. package/dist/protocols/mcp/index.d.ts +33 -3
  26. package/dist/protocols/mcp/index.js +1 -1
  27. package/dist/protocols/oauth-metadata.cjs +10 -27
  28. package/dist/protocols/oauth-metadata.d.cts +3 -4
  29. package/dist/protocols/oauth-metadata.d.ts +3 -4
  30. package/dist/protocols/oauth-metadata.js +4 -21
  31. package/dist/stacks/supabase/index.cjs +6 -6
  32. package/dist/stacks/supabase/index.d.cts +1 -1
  33. package/dist/stacks/supabase/index.d.ts +1 -1
  34. package/dist/stacks/supabase/index.js +4 -4
  35. package/dist/stacks/supabase/vite.cjs +1 -1
  36. package/dist/stacks/supabase/vite.d.cts +1 -1
  37. package/dist/stacks/supabase/vite.d.ts +1 -1
  38. package/dist/stacks/supabase/vite.js +1 -1
  39. package/dist/stacks/tanstack/index.cjs +5 -5
  40. package/dist/stacks/tanstack/index.d.cts +2 -2
  41. package/dist/stacks/tanstack/index.d.ts +2 -2
  42. package/dist/stacks/tanstack/index.js +4 -4
  43. package/dist/stacks/tanstack/vite.cjs +4 -8
  44. package/dist/stacks/tanstack/vite.d.cts +1 -4
  45. package/dist/stacks/tanstack/vite.d.ts +1 -4
  46. package/dist/stacks/tanstack/vite.js +4 -8
  47. package/dist/{types-3CZPz364.d.cts → types-C0Wgm9zp.d.cts} +29 -65
  48. package/dist/{types-3CZPz364.d.ts → types-C0Wgm9zp.d.ts} +29 -65
  49. package/package.json +1 -5
  50. package/dist/base-7cq6HCPO.d.ts +0 -36
  51. package/dist/base-CHNFFrMG.d.cts +0 -36
  52. package/dist/forwarded-DG83ubwT.js +0 -26
  53. package/dist/forwarded-zNAIofM2.cjs +0 -31
  54. package/dist/mcp-Cb5SavFT.js +0 -348
  55. package/dist/mcp-Dq6dXUKT.cjs +0 -353
  56. package/dist/schema-CW1jKvio.js +0 -65
  57. package/dist/schema-D3vClxb7.cjs +0 -76
@@ -1,348 +0,0 @@
1
- import { i as log, r as describeError } from "./logger-Ctv5xUSD.js";
2
- import { n as schemaFromDefinition, t as jsonSchemaFromDefinition } from "./schema-CW1jKvio.js";
3
- import { i as ToolContext, n as errorSummary, r as resolveToolErrorMessage } from "./errors-Bwd1L0Rf.js";
4
- import { f as finalizeWireResponse, i as normalizeHttpMethod, l as createNoopRecorder, n as createRequestAuthorizer, t as evaluateCors, u as nowMs } from "./cors-5P69YRDK.js";
5
- import { getParseErrorMessage, safeParseAsync } from "@modelcontextprotocol/sdk/server/zod-compat.js";
6
- import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, McpServer, createMcpHandler } from "@modelcontextprotocol/server";
7
- //#region src/core/content.ts
8
- /** Join the text of a result's `type: "text"` blocks into one string, dropping
9
- * binary/resource blocks. Used to surface a `tool_error` message in the local
10
- * log; never sent over the telemetry wire. Returns undefined when there is no
11
- * text to show. */
12
- function extractTextContent(content) {
13
- if (!content) return void 0;
14
- const text = content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
15
- return text.length > 0 ? text : void 0;
16
- }
17
- //#endregion
18
- //#region src/core/tool-result.ts
19
- function normalizeResourceLinkIcon(icon) {
20
- if (typeof icon.sizes !== "string") return icon;
21
- const { sizes, ...rest } = icon;
22
- const normalized = sizes.trim();
23
- return normalized === "" ? rest : {
24
- ...rest,
25
- sizes: normalized.split(/\s+/)
26
- };
27
- }
28
- function normalizeToolContent(content) {
29
- return (content ?? []).map((block) => {
30
- if (block.type !== "resource_link" || block.icons === void 0) return block;
31
- return {
32
- ...block,
33
- icons: block.icons.map(normalizeResourceLinkIcon)
34
- };
35
- });
36
- }
37
- function outputValidationError(text) {
38
- return {
39
- content: [{
40
- type: "text",
41
- text
42
- }],
43
- isError: true
44
- };
45
- }
46
- function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
47
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
48
- if (typeof value === "number") return Number.isFinite(value);
49
- if (typeof value !== "object" || ancestors.has(value)) return false;
50
- const prototype = Object.getPrototypeOf(value);
51
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;
52
- ancestors.add(value);
53
- const valid = (Array.isArray(value) ? value : Object.values(value).filter((entry) => entry !== void 0)).every((entry) => isJsonValue(entry, ancestors));
54
- ancestors.delete(value);
55
- return valid;
56
- }
57
- async function finalizeToolResult(tool, result) {
58
- const content = normalizeToolContent(result.content);
59
- let structuredContent = result.structuredContent;
60
- if (tool.outputSchema && !result.isError) {
61
- if (structuredContent === void 0) return outputValidationError(`Output validation error: Tool ${tool.name} has an output schema but no structured content was provided`);
62
- try {
63
- const parsed = await safeParseAsync(schemaFromDefinition(tool.outputSchema), structuredContent);
64
- if (!parsed.success) return outputValidationError(`Output validation error: Invalid structured content for tool ${tool.name}: ${getParseErrorMessage(parsed.error)}`);
65
- structuredContent = parsed.data;
66
- } catch {
67
- return outputValidationError(`Output validation error: Could not validate structured content for tool ${tool.name}`);
68
- }
69
- }
70
- if (structuredContent !== void 0 && !isJsonValue(structuredContent)) {
71
- if (!result.isError) return outputValidationError(`Output validation error: Tool ${tool.name} returned a non-JSON structured value`);
72
- structuredContent = void 0;
73
- }
74
- if (structuredContent !== void 0 && (structuredContent === null || typeof structuredContent !== "object" || Array.isArray(structuredContent)) && !content.some((block) => block.type === "text")) content.push({
75
- type: "text",
76
- text: JSON.stringify(structuredContent)
77
- });
78
- return {
79
- content,
80
- structuredContent,
81
- isError: result.isError
82
- };
83
- }
84
- //#endregion
85
- //#region src/protocols/gate.ts
86
- function createGatedHandler(gate) {
87
- const allow = [...gate.methods, "OPTIONS"].join(", ");
88
- const respond = async (request, recorder) => {
89
- const authResult = await gate.authorizer.authorize(request, recorder);
90
- if (!authResult.ok) return authResult.response;
91
- if (!gate.methods.includes(request.method)) return gate.methodNotAllowed(allow);
92
- return gate.handle(request, authResult, recorder);
93
- };
94
- return async (request, recorder = createNoopRecorder()) => {
95
- const cors = evaluateCors(request, gate.allowedOrigins);
96
- if (!cors.ok) {
97
- const httpMethod = normalizeHttpMethod(request.method);
98
- log.info("cors.origin_rejected", {
99
- origin: request.headers.get("Origin"),
100
- httpMethod
101
- });
102
- await recorder.emit({
103
- tool: null,
104
- method: "authorize",
105
- outcome: "origin_rejected",
106
- httpMethod,
107
- durationMs: 0
108
- });
109
- return finalizeWireResponse(request, cors.response);
110
- }
111
- if (request.method === "OPTIONS") return cors.preflight(allow);
112
- const final = finalizeWireResponse(request, cors.withHeaders(await respond(request, recorder)));
113
- if (!final.headers.has("Cache-Control")) final.headers.set("Cache-Control", "no-store");
114
- return final;
115
- };
116
- }
117
- //#endregion
118
- //#region src/protocols/mcp/protocol.ts
119
- const MODERN_PROTOCOL_VERSION = "2026-07-28";
120
- function statelessMethodNotAllowed(allow) {
121
- return Response.json({
122
- jsonrpc: "2.0",
123
- id: null,
124
- error: {
125
- code: -32e3,
126
- message: "Method not allowed: stateless server offers no standalone SSE stream (GET) or session (DELETE)."
127
- }
128
- }, {
129
- status: 405,
130
- headers: { Allow: allow }
131
- });
132
- }
133
- function zodIssues(error) {
134
- const issues = error?.issues;
135
- if (!Array.isArray(issues)) return [{ message: String(error) }];
136
- return issues.map((issue) => {
137
- const value = issue;
138
- return {
139
- message: typeof value.message === "string" ? value.message : String(value.message),
140
- ...Array.isArray(value.path) ? { path: value.path } : {}
141
- };
142
- });
143
- }
144
- function standardSchemaFromDefinition(definition) {
145
- const schema = schemaFromDefinition(definition);
146
- return { "~standard": {
147
- version: 1,
148
- vendor: "zod",
149
- validate: async (value) => {
150
- const parsed = await safeParseAsync(schema, value);
151
- return parsed.success ? { value: parsed.data } : { issues: zodIssues(parsed.error) };
152
- },
153
- jsonSchema: {
154
- input: () => jsonSchemaFromDefinition(definition, "input"),
155
- output: () => jsonSchemaFromDefinition(definition, "output")
156
- }
157
- } };
158
- }
159
- function isPlainObject(value) {
160
- return typeof value === "object" && value !== null && !Array.isArray(value);
161
- }
162
- function toolRequestContext(sdkCtx, protocol) {
163
- const mcpReq = sdkCtx?.mcpReq;
164
- const client = { protocol };
165
- const envelope = mcpReq?.envelope;
166
- const info = envelope?.[CLIENT_INFO_META_KEY];
167
- if (isPlainObject(info) && typeof info.name === "string" && typeof info.version === "string") client.info = info;
168
- const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
169
- if (isPlainObject(capabilities)) {
170
- client.capabilities = capabilities;
171
- if (isPlainObject(capabilities.extensions)) client.extensions = capabilities.extensions;
172
- }
173
- const progressToken = (mcpReq?._meta)?.progressToken;
174
- const notify = mcpReq?.notify;
175
- const sendProgress = progressToken !== void 0 && notify ? async (update) => {
176
- try {
177
- await notify({
178
- method: "notifications/progress",
179
- params: {
180
- progressToken,
181
- ...update
182
- }
183
- });
184
- } catch (err) {
185
- log.debug("mcp.progress_notify_failed", describeError(err));
186
- }
187
- } : void 0;
188
- return {
189
- signal: mcpReq?.signal,
190
- client,
191
- sendProgress
192
- };
193
- }
194
- async function invokeTool(tool, auth, recorder, args, protocol, sdkCtx) {
195
- const endUserId = auth?.principal.sub;
196
- const start = nowMs();
197
- let result;
198
- try {
199
- result = await tool.handler(args, new ToolContext(auth, toolRequestContext(sdkCtx, protocol)));
200
- } catch (err) {
201
- const callerMessage = resolveToolErrorMessage(err);
202
- if (callerMessage === void 0) {
203
- await recorder.emit({
204
- tool: tool.name,
205
- method: "tools/call",
206
- outcome: "handler_error",
207
- durationMs: nowMs() - start,
208
- errorText: errorSummary(err),
209
- endUserId,
210
- protocol
211
- });
212
- return finalizeToolResult(tool, {
213
- content: [{
214
- type: "text",
215
- text: "tool execution failed"
216
- }],
217
- isError: true
218
- });
219
- }
220
- result = {
221
- content: [{
222
- type: "text",
223
- text: callerMessage
224
- }],
225
- isError: true
226
- };
227
- }
228
- if (result == null) {
229
- await recorder.emit({
230
- tool: tool.name,
231
- method: "tools/call",
232
- outcome: "handler_error",
233
- durationMs: nowMs() - start,
234
- endUserId,
235
- protocol
236
- });
237
- return finalizeToolResult(tool, {
238
- content: [{
239
- type: "text",
240
- text: `tool "${tool.name}" returned no result`
241
- }],
242
- isError: true
243
- });
244
- }
245
- result = await finalizeToolResult(tool, result);
246
- await recorder.emit({
247
- tool: tool.name,
248
- method: "tools/call",
249
- outcome: result.isError ? "tool_error" : "ok",
250
- durationMs: nowMs() - start,
251
- errorText: result.isError ? extractTextContent(result.content) : void 0,
252
- endUserId,
253
- protocol
254
- });
255
- return result;
256
- }
257
- function adaptToolCallback(tool, auth, recorder, protocol) {
258
- return async (first, second) => {
259
- const sdkCtx = tool.inputSchema ? second : first;
260
- const result = await invokeTool(tool, auth, recorder, tool.inputSchema ? first ?? {} : {}, protocol, sdkCtx);
261
- return {
262
- content: result.content ?? [],
263
- structuredContent: result.structuredContent,
264
- isError: result.isError
265
- };
266
- };
267
- }
268
- function buildServer(mcp, auth, recorder, era) {
269
- const server = new McpServer({
270
- name: mcp.name,
271
- version: mcp.version,
272
- title: mcp.title
273
- }, {
274
- instructions: mcp.instructions,
275
- capabilities: { tools: { listChanged: false } }
276
- });
277
- for (const tool of mcp.tools) {
278
- const config = {
279
- title: tool.title,
280
- description: tool.description,
281
- annotations: tool.annotations,
282
- ...tool.outputSchema ? { outputSchema: standardSchemaFromDefinition(tool.outputSchema) } : {}
283
- };
284
- const callback = adaptToolCallback(tool, auth, recorder, era === "legacy" ? "legacy" : MODERN_PROTOCOL_VERSION);
285
- if (tool.inputSchema) server.registerTool(tool.name, {
286
- ...config,
287
- inputSchema: standardSchemaFromDefinition(tool.inputSchema)
288
- }, callback);
289
- else server.registerTool(tool.name, config, callback);
290
- }
291
- return server;
292
- }
293
- /**
294
- * Build a Web-Standard request handler that serves the MCP protocol over
295
- * streamable HTTP. A fresh `McpServer` + transport is constructed per
296
- * request — the transport is stateless, so this is cheap and there is no
297
- * cross-request state to leak. The per-request `recorder` is supplied by the
298
- * caller (the stack handler) so telemetry reads the runtime env in-flight.
299
- */
300
- function createMcpProtocolHandler(mcp, options = {}) {
301
- const authorizer = createRequestAuthorizer(mcp, options);
302
- const handle = async (request, authResult, recorder) => {
303
- let protocolError;
304
- const reportTransportError = async (error) => {
305
- await recorder.emit({
306
- tool: null,
307
- method: "transport",
308
- outcome: "transport_error",
309
- durationMs: 0,
310
- endUserId: authResult.auth?.principal.sub
311
- });
312
- log.error("mcp.transport_error", {
313
- ...error === void 0 ? {} : describeError(error),
314
- outcome: "500 internal error"
315
- });
316
- };
317
- try {
318
- const response = await createMcpHandler(({ era }) => buildServer(mcp, authResult.auth, recorder, era), {
319
- legacy: "stateless",
320
- maxSubscriptions: 0,
321
- onerror: (error) => {
322
- protocolError = error;
323
- }
324
- }).fetch(request);
325
- if (response.status >= 500) await reportTransportError(protocolError);
326
- return response;
327
- } catch (err) {
328
- await reportTransportError(err);
329
- return Response.json({
330
- jsonrpc: "2.0",
331
- id: null,
332
- error: {
333
- code: -32603,
334
- message: "internal error"
335
- }
336
- }, { status: 500 });
337
- }
338
- };
339
- return createGatedHandler({
340
- authorizer,
341
- allowedOrigins: mcp.allowedOrigins,
342
- methods: ["POST"],
343
- methodNotAllowed: statelessMethodNotAllowed,
344
- handle
345
- });
346
- }
347
- //#endregion
348
- export { createMcpProtocolHandler as t };
@@ -1,353 +0,0 @@
1
- const require_logger = require("./logger-CN1q-KNn.cjs");
2
- const require_schema = require("./schema-D3vClxb7.cjs");
3
- const require_errors = require("./errors-Cr95rSkB.cjs");
4
- const require_cors = require("./cors-DIQIXIHY.cjs");
5
- let _modelcontextprotocol_sdk_server_zod_compat_js = require("@modelcontextprotocol/sdk/server/zod-compat.js");
6
- let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
7
- //#region src/core/content.ts
8
- /** Join the text of a result's `type: "text"` blocks into one string, dropping
9
- * binary/resource blocks. Used to surface a `tool_error` message in the local
10
- * log; never sent over the telemetry wire. Returns undefined when there is no
11
- * text to show. */
12
- function extractTextContent(content) {
13
- if (!content) return void 0;
14
- const text = content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
15
- return text.length > 0 ? text : void 0;
16
- }
17
- //#endregion
18
- //#region src/core/tool-result.ts
19
- function normalizeResourceLinkIcon(icon) {
20
- if (typeof icon.sizes !== "string") return icon;
21
- const { sizes, ...rest } = icon;
22
- const normalized = sizes.trim();
23
- return normalized === "" ? rest : {
24
- ...rest,
25
- sizes: normalized.split(/\s+/)
26
- };
27
- }
28
- function normalizeToolContent(content) {
29
- return (content ?? []).map((block) => {
30
- if (block.type !== "resource_link" || block.icons === void 0) return block;
31
- return {
32
- ...block,
33
- icons: block.icons.map(normalizeResourceLinkIcon)
34
- };
35
- });
36
- }
37
- function outputValidationError(text) {
38
- return {
39
- content: [{
40
- type: "text",
41
- text
42
- }],
43
- isError: true
44
- };
45
- }
46
- function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
47
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
48
- if (typeof value === "number") return Number.isFinite(value);
49
- if (typeof value !== "object" || ancestors.has(value)) return false;
50
- const prototype = Object.getPrototypeOf(value);
51
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;
52
- ancestors.add(value);
53
- const valid = (Array.isArray(value) ? value : Object.values(value).filter((entry) => entry !== void 0)).every((entry) => isJsonValue(entry, ancestors));
54
- ancestors.delete(value);
55
- return valid;
56
- }
57
- async function finalizeToolResult(tool, result) {
58
- const content = normalizeToolContent(result.content);
59
- let structuredContent = result.structuredContent;
60
- if (tool.outputSchema && !result.isError) {
61
- if (structuredContent === void 0) return outputValidationError(`Output validation error: Tool ${tool.name} has an output schema but no structured content was provided`);
62
- try {
63
- const parsed = await (0, _modelcontextprotocol_sdk_server_zod_compat_js.safeParseAsync)(require_schema.schemaFromDefinition(tool.outputSchema), structuredContent);
64
- if (!parsed.success) return outputValidationError(`Output validation error: Invalid structured content for tool ${tool.name}: ${(0, _modelcontextprotocol_sdk_server_zod_compat_js.getParseErrorMessage)(parsed.error)}`);
65
- structuredContent = parsed.data;
66
- } catch {
67
- return outputValidationError(`Output validation error: Could not validate structured content for tool ${tool.name}`);
68
- }
69
- }
70
- if (structuredContent !== void 0 && !isJsonValue(structuredContent)) {
71
- if (!result.isError) return outputValidationError(`Output validation error: Tool ${tool.name} returned a non-JSON structured value`);
72
- structuredContent = void 0;
73
- }
74
- if (structuredContent !== void 0 && (structuredContent === null || typeof structuredContent !== "object" || Array.isArray(structuredContent)) && !content.some((block) => block.type === "text")) content.push({
75
- type: "text",
76
- text: JSON.stringify(structuredContent)
77
- });
78
- return {
79
- content,
80
- structuredContent,
81
- isError: result.isError
82
- };
83
- }
84
- //#endregion
85
- //#region src/protocols/gate.ts
86
- function createGatedHandler(gate) {
87
- const allow = [...gate.methods, "OPTIONS"].join(", ");
88
- const respond = async (request, recorder) => {
89
- const authResult = await gate.authorizer.authorize(request, recorder);
90
- if (!authResult.ok) return authResult.response;
91
- if (!gate.methods.includes(request.method)) return gate.methodNotAllowed(allow);
92
- return gate.handle(request, authResult, recorder);
93
- };
94
- return async (request, recorder = require_cors.createNoopRecorder()) => {
95
- const cors = require_cors.evaluateCors(request, gate.allowedOrigins);
96
- if (!cors.ok) {
97
- const httpMethod = require_cors.normalizeHttpMethod(request.method);
98
- require_logger.log.info("cors.origin_rejected", {
99
- origin: request.headers.get("Origin"),
100
- httpMethod
101
- });
102
- await recorder.emit({
103
- tool: null,
104
- method: "authorize",
105
- outcome: "origin_rejected",
106
- httpMethod,
107
- durationMs: 0
108
- });
109
- return require_cors.finalizeWireResponse(request, cors.response);
110
- }
111
- if (request.method === "OPTIONS") return cors.preflight(allow);
112
- const final = require_cors.finalizeWireResponse(request, cors.withHeaders(await respond(request, recorder)));
113
- if (!final.headers.has("Cache-Control")) final.headers.set("Cache-Control", "no-store");
114
- return final;
115
- };
116
- }
117
- //#endregion
118
- //#region src/protocols/mcp/protocol.ts
119
- const MODERN_PROTOCOL_VERSION = "2026-07-28";
120
- function statelessMethodNotAllowed(allow) {
121
- return Response.json({
122
- jsonrpc: "2.0",
123
- id: null,
124
- error: {
125
- code: -32e3,
126
- message: "Method not allowed: stateless server offers no standalone SSE stream (GET) or session (DELETE)."
127
- }
128
- }, {
129
- status: 405,
130
- headers: { Allow: allow }
131
- });
132
- }
133
- function zodIssues(error) {
134
- const issues = error?.issues;
135
- if (!Array.isArray(issues)) return [{ message: String(error) }];
136
- return issues.map((issue) => {
137
- const value = issue;
138
- return {
139
- message: typeof value.message === "string" ? value.message : String(value.message),
140
- ...Array.isArray(value.path) ? { path: value.path } : {}
141
- };
142
- });
143
- }
144
- function standardSchemaFromDefinition(definition) {
145
- const schema = require_schema.schemaFromDefinition(definition);
146
- return { "~standard": {
147
- version: 1,
148
- vendor: "zod",
149
- validate: async (value) => {
150
- const parsed = await (0, _modelcontextprotocol_sdk_server_zod_compat_js.safeParseAsync)(schema, value);
151
- return parsed.success ? { value: parsed.data } : { issues: zodIssues(parsed.error) };
152
- },
153
- jsonSchema: {
154
- input: () => require_schema.jsonSchemaFromDefinition(definition, "input"),
155
- output: () => require_schema.jsonSchemaFromDefinition(definition, "output")
156
- }
157
- } };
158
- }
159
- function isPlainObject(value) {
160
- return typeof value === "object" && value !== null && !Array.isArray(value);
161
- }
162
- function toolRequestContext(sdkCtx, protocol) {
163
- const mcpReq = sdkCtx?.mcpReq;
164
- const client = { protocol };
165
- const envelope = mcpReq?.envelope;
166
- const info = envelope?.[_modelcontextprotocol_server.CLIENT_INFO_META_KEY];
167
- if (isPlainObject(info) && typeof info.name === "string" && typeof info.version === "string") client.info = info;
168
- const capabilities = envelope?.[_modelcontextprotocol_server.CLIENT_CAPABILITIES_META_KEY];
169
- if (isPlainObject(capabilities)) {
170
- client.capabilities = capabilities;
171
- if (isPlainObject(capabilities.extensions)) client.extensions = capabilities.extensions;
172
- }
173
- const progressToken = (mcpReq?._meta)?.progressToken;
174
- const notify = mcpReq?.notify;
175
- const sendProgress = progressToken !== void 0 && notify ? async (update) => {
176
- try {
177
- await notify({
178
- method: "notifications/progress",
179
- params: {
180
- progressToken,
181
- ...update
182
- }
183
- });
184
- } catch (err) {
185
- require_logger.log.debug("mcp.progress_notify_failed", require_logger.describeError(err));
186
- }
187
- } : void 0;
188
- return {
189
- signal: mcpReq?.signal,
190
- client,
191
- sendProgress
192
- };
193
- }
194
- async function invokeTool(tool, auth, recorder, args, protocol, sdkCtx) {
195
- const endUserId = auth?.principal.sub;
196
- const start = require_cors.nowMs();
197
- let result;
198
- try {
199
- result = await tool.handler(args, new require_errors.ToolContext(auth, toolRequestContext(sdkCtx, protocol)));
200
- } catch (err) {
201
- const callerMessage = require_errors.resolveToolErrorMessage(err);
202
- if (callerMessage === void 0) {
203
- await recorder.emit({
204
- tool: tool.name,
205
- method: "tools/call",
206
- outcome: "handler_error",
207
- durationMs: require_cors.nowMs() - start,
208
- errorText: require_errors.errorSummary(err),
209
- endUserId,
210
- protocol
211
- });
212
- return finalizeToolResult(tool, {
213
- content: [{
214
- type: "text",
215
- text: "tool execution failed"
216
- }],
217
- isError: true
218
- });
219
- }
220
- result = {
221
- content: [{
222
- type: "text",
223
- text: callerMessage
224
- }],
225
- isError: true
226
- };
227
- }
228
- if (result == null) {
229
- await recorder.emit({
230
- tool: tool.name,
231
- method: "tools/call",
232
- outcome: "handler_error",
233
- durationMs: require_cors.nowMs() - start,
234
- endUserId,
235
- protocol
236
- });
237
- return finalizeToolResult(tool, {
238
- content: [{
239
- type: "text",
240
- text: `tool "${tool.name}" returned no result`
241
- }],
242
- isError: true
243
- });
244
- }
245
- result = await finalizeToolResult(tool, result);
246
- await recorder.emit({
247
- tool: tool.name,
248
- method: "tools/call",
249
- outcome: result.isError ? "tool_error" : "ok",
250
- durationMs: require_cors.nowMs() - start,
251
- errorText: result.isError ? extractTextContent(result.content) : void 0,
252
- endUserId,
253
- protocol
254
- });
255
- return result;
256
- }
257
- function adaptToolCallback(tool, auth, recorder, protocol) {
258
- return async (first, second) => {
259
- const sdkCtx = tool.inputSchema ? second : first;
260
- const result = await invokeTool(tool, auth, recorder, tool.inputSchema ? first ?? {} : {}, protocol, sdkCtx);
261
- return {
262
- content: result.content ?? [],
263
- structuredContent: result.structuredContent,
264
- isError: result.isError
265
- };
266
- };
267
- }
268
- function buildServer(mcp, auth, recorder, era) {
269
- const server = new _modelcontextprotocol_server.McpServer({
270
- name: mcp.name,
271
- version: mcp.version,
272
- title: mcp.title
273
- }, {
274
- instructions: mcp.instructions,
275
- capabilities: { tools: { listChanged: false } }
276
- });
277
- for (const tool of mcp.tools) {
278
- const config = {
279
- title: tool.title,
280
- description: tool.description,
281
- annotations: tool.annotations,
282
- ...tool.outputSchema ? { outputSchema: standardSchemaFromDefinition(tool.outputSchema) } : {}
283
- };
284
- const callback = adaptToolCallback(tool, auth, recorder, era === "legacy" ? "legacy" : MODERN_PROTOCOL_VERSION);
285
- if (tool.inputSchema) server.registerTool(tool.name, {
286
- ...config,
287
- inputSchema: standardSchemaFromDefinition(tool.inputSchema)
288
- }, callback);
289
- else server.registerTool(tool.name, config, callback);
290
- }
291
- return server;
292
- }
293
- /**
294
- * Build a Web-Standard request handler that serves the MCP protocol over
295
- * streamable HTTP. A fresh `McpServer` + transport is constructed per
296
- * request — the transport is stateless, so this is cheap and there is no
297
- * cross-request state to leak. The per-request `recorder` is supplied by the
298
- * caller (the stack handler) so telemetry reads the runtime env in-flight.
299
- */
300
- function createMcpProtocolHandler(mcp, options = {}) {
301
- const authorizer = require_cors.createRequestAuthorizer(mcp, options);
302
- const handle = async (request, authResult, recorder) => {
303
- let protocolError;
304
- const reportTransportError = async (error) => {
305
- await recorder.emit({
306
- tool: null,
307
- method: "transport",
308
- outcome: "transport_error",
309
- durationMs: 0,
310
- endUserId: authResult.auth?.principal.sub
311
- });
312
- require_logger.log.error("mcp.transport_error", {
313
- ...error === void 0 ? {} : require_logger.describeError(error),
314
- outcome: "500 internal error"
315
- });
316
- };
317
- try {
318
- const response = await (0, _modelcontextprotocol_server.createMcpHandler)(({ era }) => buildServer(mcp, authResult.auth, recorder, era), {
319
- legacy: "stateless",
320
- maxSubscriptions: 0,
321
- onerror: (error) => {
322
- protocolError = error;
323
- }
324
- }).fetch(request);
325
- if (response.status >= 500) await reportTransportError(protocolError);
326
- return response;
327
- } catch (err) {
328
- await reportTransportError(err);
329
- return Response.json({
330
- jsonrpc: "2.0",
331
- id: null,
332
- error: {
333
- code: -32603,
334
- message: "internal error"
335
- }
336
- }, { status: 500 });
337
- }
338
- };
339
- return createGatedHandler({
340
- authorizer,
341
- allowedOrigins: mcp.allowedOrigins,
342
- methods: ["POST"],
343
- methodNotAllowed: statelessMethodNotAllowed,
344
- handle
345
- });
346
- }
347
- //#endregion
348
- Object.defineProperty(exports, "createMcpProtocolHandler", {
349
- enumerable: true,
350
- get: function() {
351
- return createMcpProtocolHandler;
352
- }
353
- });