@vitemcp/server 1.9.5 → 1.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ViteMCP.cjs +2 -2
- package/dist/ViteMCP.js +1 -1
- package/dist/{chunk-2GDWFXWP.js → chunk-FAONEXUK.js} +47 -3
- package/dist/chunk-FAONEXUK.js.map +1 -0
- package/dist/{chunk-IBZFPUBF.cjs → chunk-R7AFGJBR.cjs} +76 -32
- package/dist/chunk-R7AFGJBR.cjs.map +1 -0
- package/dist/edge/index.cjs +7 -0
- package/dist/edge/index.cjs.map +1 -1
- package/dist/edge/index.js +7 -0
- package/dist/edge/index.js.map +1 -1
- package/dist/openapi/index.cjs +41 -40
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.js +22 -21
- package/dist/openapi/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2GDWFXWP.js.map +0 -1
- package/dist/chunk-IBZFPUBF.cjs.map +0 -1
package/dist/edge/index.cjs
CHANGED
|
@@ -79,17 +79,24 @@ var EdgeViteMCP = class {
|
|
|
79
79
|
this.#maxBodySize = _nullishCoalesce(options.maxBodySize, () => ( DEFAULT_MAX_BODY_SIZE));
|
|
80
80
|
this.#mcpPath = _nullishCoalesce(options.mcpPath, () => ( "/mcp"));
|
|
81
81
|
}
|
|
82
|
+
// As on `ViteMCP`, an entry added under a key already in use replaces the
|
|
83
|
+
// one there, since the SDK refuses to register a key twice and a duplicate
|
|
84
|
+
// failed every request. A resource's key is its URI, a prompt's or tool's
|
|
85
|
+
// its name.
|
|
82
86
|
addPrompt(prompt) {
|
|
87
|
+
this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);
|
|
83
88
|
this.#prompts.push(prompt);
|
|
84
89
|
this.#handler = null;
|
|
85
90
|
return this;
|
|
86
91
|
}
|
|
87
92
|
addResource(resource) {
|
|
93
|
+
this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);
|
|
88
94
|
this.#resources.push(resource);
|
|
89
95
|
this.#handler = null;
|
|
90
96
|
return this;
|
|
91
97
|
}
|
|
92
98
|
addTool(tool) {
|
|
99
|
+
this.#tools = this.#tools.filter((t) => t.name !== tool.name);
|
|
93
100
|
this.#tools.push(tool);
|
|
94
101
|
this.#handler = null;
|
|
95
102
|
return this;
|
package/dist/edge/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/server/server/dist/edge/index.cjs","../../src/edge/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACDA,sDAA4C;AAE5C,4BAAqB;AACrB,0BAAkB;AA6FlB,IAAM,oBAAA,EAA2C,MAAA,CAAO,MAAA,EAAQ,EAAA,EAAA,GAAO;AACrE,EAAA,MAAM,EAAE,OAAO,EAAA,EAAI,MAAA,CAAO,WAAW,CAAA;AAErC,EAAA,GAAA,CAAI,OAAA,IAAW,SAAA,EAAW;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,4HAAA;AAAA,IAC3B,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,mDAAA,MAAoB,EAAQ,EAAE,CAAA;AACvC,CAAA;AAWA,IAAM,kBAAA,EAAoB,MAAA,CACxB,OAAA,EACA,QAAA,EAAA,GAC4B;AAC5B,EAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,IAAA,EAAM;AACjB,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,MAAA,kBAAO,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA,UAAK,GAAC,EAAA,EAAI,QAAA,EAAU;AACjE,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,EAAS,OAAA,CAAQ,IAAA,CAAK,SAAA,CAAU,CAAA;AACtC,EAAA,MAAM,OAAA,EAAuB,CAAC,CAAA;AAC9B,E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B,UAAA;AACE,QAAA;AACtB;AAAA;AAAA;AAAA,QAAA;AAIiD,MAAA;AACnD,IAAA;AAGF,IAAA;AACE,MAAA;AAAO,QAAA;AACI,QAAA;AACA,QAAA;AACwD,QAAA;AAE/D,UAAA;AACA,UAAA;AACA,UAAA;AAAO,YAAA;AACK,cAAA;AACR,gBAAA;AACK,gBAAA;AACiC,gBAAA;AAClB,cAAA;AACpB,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AAGF,IAAA;AACE,MAAA;AACA,MAAA;AACE,QAAA;AAAkE,MAAA;AAGpE,MAAA;AAIA,MAAA;AACE,QAAA;AACA,QAAA;AAAO,UAAA;AACK,YAAA;AACiD,UAAA;AAC3D,QAAA;AACF,MAAA;AAGF,MAAA;AAAO,QAAA;AACE,QAAA;AACuC;AAAA;AAAA,QAAA;AAGd,MAAA;AAClC,IAAA;AAGF,IAAA;AAEA,IAAA;AAAO,EAAA;AACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAAA;AAUE,IAAA;AAEA,IAAA;AACE,MAAA;AAAoE,QAAA;AAClC,QAAA;AAE9B,UAAA;AAAa,YAAA;AACqB,YAAA;AAChC,UAAA;AAGF,UAAA;AAAO,QAAA;AACT,MAAA;AAEF,MAAA;AAAkC,IAAA;AAGpC,IAAA;AAAO,EAAA;AAEX;ADnKA;AACA;AACA","file":"/home/runner/work/server/server/dist/edge/index.cjs","sourcesContent":[null,"/**\n * Edge-compatible ViteMCP server for Cloudflare Workers, Deno, and Bun.\n *\n * Web-standard APIs only. `createMcpHandler` already exposes the\n * `(Request) => Response` shape edge runtimes want; this is a thin wrapper.\n */\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { Hono } from \"hono\";\nimport { z } from \"zod\";\n\nimport { formatBytes } from \"../formatBytes.js\";\nimport { ownKeysOnly } from \"../ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"../toSdkSchema.js\";\n\nexport type EdgeFetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * Logger interface for edge environments\n */\nexport interface EdgeLogger {\n debug(...args: unknown[]): void;\n error(...args: unknown[]): void;\n info(...args: unknown[]): void;\n log(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\n/**\n * Prompt definition for EdgeViteMCP\n */\nexport interface EdgePrompt {\n arguments?: Array<{ description?: string; name: string; required?: boolean }>;\n description?: string;\n load: (args: Record<string, string>) => Promise<string>;\n name: string;\n}\n\n/**\n * Resource definition for EdgeViteMCP\n */\nexport interface EdgeResource {\n description?: string;\n load: () => Promise<\n { blob?: string; mimeType?: string; text?: string } | string\n >;\n mimeType?: string;\n name: string;\n uri: string;\n}\n\n/**\n * Tool definition for EdgeViteMCP\n */\nexport interface EdgeTool<TParams = unknown> {\n description: string;\n execute: (params: TParams) => Promise<\n | {\n content: Array<{\n data?: string;\n mimeType?: string;\n text?: string;\n type: string;\n }>;\n }\n | string\n >;\n name: string;\n parameters?: StandardSchemaV1<TParams> | z.ZodType<TParams>;\n}\n\n/**\n * Options for EdgeViteMCP\n */\nexport interface EdgeViteMCPOptions {\n description?: string;\n logger?: EdgeLogger;\n /**\n * Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,\n * as on the Node transport). A larger one is refused without being held in\n * memory. Routes added through `getApp()` are not covered.\n */\n maxBodySize?: number;\n /**\n * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\n/**\n * JSON Schema for a schema that carries none, from the one converter this\n * entry point can afford. `ViteMCP` hands every other library to xsschema,\n * which reaches each converter through an `import()` a bundler has to resolve:\n * an edge bundle would then fail to build for want of Effect or Sury, whichever\n * library the server was actually written in.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) => {\n const { vendor } = schema[\"~standard\"];\n\n if (vendor !== \"valibot\") {\n throw new Error(\n `Schema library \"${vendor}\" carries no JSON Schema (\\`~standard.jsonSchema\\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`,\n );\n }\n\n return valibotToJsonSchema(schema, io);\n};\n\n/**\n * The request with its body read under a hard cap, or `null` when the body is\n * larger than that.\n *\n * The SDK reads whatever it is handed in full, so the cap has to be applied\n * before it sees the request — and while reading, not after: a declared\n * `Content-Length` over the cap is refused before a byte is read, and a body\n * that declares none is abandoned at the first chunk past it.\n */\nconst readCappedRequest = async (\n request: Request,\n maxBytes: number,\n): Promise<null | Request> => {\n if (!request.body) {\n return request;\n }\n\n if (Number(request.headers.get(\"content-length\") ?? 0) > maxBytes) {\n return null;\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > maxBytes) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n\n const body = new Uint8Array(size);\n let offset = 0;\n\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n // Rebuilt rather than cloned: the original's body is spent.\n return new Request(request.url, {\n body,\n headers: request.headers,\n method: request.method,\n signal: request.signal,\n });\n};\n\n/** The Node transport's default for `httpStream.maxBodySize`. */\nconst DEFAULT_MAX_BODY_SIZE = 1024 * 1024;\n\n/** A refusal in the shape the Node transport gives a body it will not take. */\nconst invalidRequest = (description: string): Response =>\n Response.json(\n { error: \"invalid_request\", error_description: description },\n { status: 400 },\n );\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\n /** Each tool's input schema, as `#sdkSchemaFor` converted it. */\n #toolSchemas = new WeakMap<\n EdgeTool,\n Promise<{ inputSchema: unknown } | undefined>\n >();\n #version: string;\n\n constructor(options: EdgeViteMCPOptions) {\n this.#name = options.name;\n this.#version = options.version;\n this.#logger = options.logger ?? console;\n this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;\n this.#mcpPath = options.mcpPath ?? \"/mcp\";\n }\n\n addPrompt(prompt: EdgePrompt): this {\n this.#prompts.push(prompt);\n this.#handler = null;\n return this;\n }\n\n addResource(resource: EdgeResource): this {\n this.#resources.push(resource);\n this.#handler = null;\n return this;\n }\n\n addTool<TParams>(tool: EdgeTool<TParams>): this {\n this.#tools.push(tool as EdgeTool);\n this.#handler = null;\n return this;\n }\n\n /** Main entry point for edge runtimes. */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n\n if (url.pathname === this.#mcpPath) {\n let capped: null | Request;\n\n try {\n capped = await readCappedRequest(request, this.#maxBodySize);\n } catch (error) {\n // A body that aborts mid-stream rejects here. Answer it, as the Node\n // transport does, rather than let the rejection escape the handler.\n this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);\n\n return invalidRequest(\"Request body could not be read\");\n }\n\n if (!capped) {\n return invalidRequest(\n `Request body exceeds ${formatBytes(this.#maxBodySize)}`,\n );\n }\n\n this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(capped);\n }\n\n return this.#honoApp.fetch(request);\n }\n\n /** The Hono app, for adding custom routes alongside the MCP endpoint. */\n getApp(): Hono {\n return this.#honoApp;\n }\n\n async #buildServer(): Promise<McpServer> {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n // A tool whose schema cannot be advertised is left out rather than allowed\n // to fail the request: `tools/list` describes every tool at once, so one\n // such tool took the list down for all of them.\n const tools = (\n await Promise.all(\n this.#tools.map(async (tool) => {\n const schema = await this.#sdkSchemaFor(tool);\n\n return schema && { schema, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n\n for (const { schema, tool } of tools) {\n const call = async (args: unknown) => {\n const result = await tool.execute(args as never);\n return typeof result === \"string\"\n ? { content: [{ text: result, type: \"text\" }] }\n : result;\n };\n\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: schema.inputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone,\n // which must not reach `execute` as its parameters.\n (schema.inputSchema ? call : () => call(undefined)) as never,\n );\n }\n\n for (const resource of this.#resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n (async (uri: URL) => {\n const loaded = await resource.load();\n const body = typeof loaded === \"string\" ? { text: loaded } : loaded;\n return {\n contents: [\n {\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: uri.toString(),\n },\n ],\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of prompt.arguments ?? []) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n\n const argsSchema = prompt.arguments?.length\n ? ownKeysOnly(z.object(shape))\n : undefined;\n\n const load = async (args?: Record<string, string>) => {\n const text = await prompt.load(args ?? {});\n return {\n messages: [\n { content: { text, type: \"text\" }, role: \"user\" as const },\n ],\n };\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : () => load()) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\n }\n\n /**\n * A tool's input schema in the form the SDK registers it, or `undefined` for\n * a tool whose schema cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemaFor(tool: EdgeTool): Promise<{ inputSchema: unknown } | undefined> {\n let schema = this.#toolSchemas.get(tool);\n\n if (!schema) {\n schema = toSdkSchema(tool.parameters, \"input\", convertToJsonSchema).then(\n (inputSchema) => ({ inputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[EdgeViteMCP] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schema);\n }\n\n return schema;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/server/server/dist/edge/index.cjs","../../src/edge/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACDA,sDAA4C;AAE5C,4BAAqB;AACrB,0BAAkB;AA6FlB,IAAM,oBAAA,EAA2C,MAAA,CAAO,MAAA,EAAQ,EAAA,EAAA,GAAO;AACrE,EAAA,MAAM,EAAE,OAAO,EAAA,EAAI,MAAA,CAAO,WAAW,CAAA;AAErC,EAAA,GAAA,CAAI,OAAA,IAAW,SAAA,EAAW;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,MAAM,CAAA,4HAAA;AAAA,IAC3B,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,mDAAA,MAAoB,EAAQ,EAAE,CAAA;AACvC,CAAA;AAWA,IAAM,kBAAA,EAAoB,MAAA,CACxB,OAAA,EACA,QAAA,EAAA,GAC4B;AAC5B,EAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,IAAA,EAAM;AACjB,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,MAAA,kBAAO,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA,UAAK,GAAC,EAAA,EAAI,QAAA,EAAU;AACjE,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,EAAS,OAAA,CAAQ,IAAA,CAAK,SAAA,CAAU,CAAA;AACtC,EAAA,MAAM,OAAA,EAAuB,CAAC,CAAA;AAC9B,EAAA,IAAI,KAAA,EAAO,CAAA;AAEX,EAAA,IAAA,CAAA,EAAA,EAAA,EAAS;AACP,IAAA,MAAM,EAAE,IAAA,EAAM,MAAM,EAAA,E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ACA","file":"/home/runner/work/server/server/dist/edge/index.cjs","sourcesContent":[null,"/**\n * Edge-compatible ViteMCP server for Cloudflare Workers, Deno, and Bun.\n *\n * Web-standard APIs only. `createMcpHandler` already exposes the\n * `(Request) => Response` shape edge runtimes want; this is a thin wrapper.\n */\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { Hono } from \"hono\";\nimport { z } from \"zod\";\n\nimport { formatBytes } from \"../formatBytes.js\";\nimport { ownKeysOnly } from \"../ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"../toSdkSchema.js\";\n\nexport type EdgeFetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * Logger interface for edge environments\n */\nexport interface EdgeLogger {\n debug(...args: unknown[]): void;\n error(...args: unknown[]): void;\n info(...args: unknown[]): void;\n log(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\n/**\n * Prompt definition for EdgeViteMCP\n */\nexport interface EdgePrompt {\n arguments?: Array<{ description?: string; name: string; required?: boolean }>;\n description?: string;\n load: (args: Record<string, string>) => Promise<string>;\n name: string;\n}\n\n/**\n * Resource definition for EdgeViteMCP\n */\nexport interface EdgeResource {\n description?: string;\n load: () => Promise<\n { blob?: string; mimeType?: string; text?: string } | string\n >;\n mimeType?: string;\n name: string;\n uri: string;\n}\n\n/**\n * Tool definition for EdgeViteMCP\n */\nexport interface EdgeTool<TParams = unknown> {\n description: string;\n execute: (params: TParams) => Promise<\n | {\n content: Array<{\n data?: string;\n mimeType?: string;\n text?: string;\n type: string;\n }>;\n }\n | string\n >;\n name: string;\n parameters?: StandardSchemaV1<TParams> | z.ZodType<TParams>;\n}\n\n/**\n * Options for EdgeViteMCP\n */\nexport interface EdgeViteMCPOptions {\n description?: string;\n logger?: EdgeLogger;\n /**\n * Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,\n * as on the Node transport). A larger one is refused without being held in\n * memory. Routes added through `getApp()` are not covered.\n */\n maxBodySize?: number;\n /**\n * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\n/**\n * JSON Schema for a schema that carries none, from the one converter this\n * entry point can afford. `ViteMCP` hands every other library to xsschema,\n * which reaches each converter through an `import()` a bundler has to resolve:\n * an edge bundle would then fail to build for want of Effect or Sury, whichever\n * library the server was actually written in.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) => {\n const { vendor } = schema[\"~standard\"];\n\n if (vendor !== \"valibot\") {\n throw new Error(\n `Schema library \"${vendor}\" carries no JSON Schema (\\`~standard.jsonSchema\\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`,\n );\n }\n\n return valibotToJsonSchema(schema, io);\n};\n\n/**\n * The request with its body read under a hard cap, or `null` when the body is\n * larger than that.\n *\n * The SDK reads whatever it is handed in full, so the cap has to be applied\n * before it sees the request — and while reading, not after: a declared\n * `Content-Length` over the cap is refused before a byte is read, and a body\n * that declares none is abandoned at the first chunk past it.\n */\nconst readCappedRequest = async (\n request: Request,\n maxBytes: number,\n): Promise<null | Request> => {\n if (!request.body) {\n return request;\n }\n\n if (Number(request.headers.get(\"content-length\") ?? 0) > maxBytes) {\n return null;\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > maxBytes) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n\n const body = new Uint8Array(size);\n let offset = 0;\n\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n // Rebuilt rather than cloned: the original's body is spent.\n return new Request(request.url, {\n body,\n headers: request.headers,\n method: request.method,\n signal: request.signal,\n });\n};\n\n/** The Node transport's default for `httpStream.maxBodySize`. */\nconst DEFAULT_MAX_BODY_SIZE = 1024 * 1024;\n\n/** A refusal in the shape the Node transport gives a body it will not take. */\nconst invalidRequest = (description: string): Response =>\n Response.json(\n { error: \"invalid_request\", error_description: description },\n { status: 400 },\n );\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\n /** Each tool's input schema, as `#sdkSchemaFor` converted it. */\n #toolSchemas = new WeakMap<\n EdgeTool,\n Promise<{ inputSchema: unknown } | undefined>\n >();\n #version: string;\n\n constructor(options: EdgeViteMCPOptions) {\n this.#name = options.name;\n this.#version = options.version;\n this.#logger = options.logger ?? console;\n this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;\n this.#mcpPath = options.mcpPath ?? \"/mcp\";\n }\n\n // As on `ViteMCP`, an entry added under a key already in use replaces the\n // one there, since the SDK refuses to register a key twice and a duplicate\n // failed every request. A resource's key is its URI, a prompt's or tool's\n // its name.\n addPrompt(prompt: EdgePrompt): this {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n this.#handler = null;\n return this;\n }\n\n addResource(resource: EdgeResource): this {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n this.#handler = null;\n return this;\n }\n\n addTool<TParams>(tool: EdgeTool<TParams>): this {\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as EdgeTool);\n this.#handler = null;\n return this;\n }\n\n /** Main entry point for edge runtimes. */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n\n if (url.pathname === this.#mcpPath) {\n let capped: null | Request;\n\n try {\n capped = await readCappedRequest(request, this.#maxBodySize);\n } catch (error) {\n // A body that aborts mid-stream rejects here. Answer it, as the Node\n // transport does, rather than let the rejection escape the handler.\n this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);\n\n return invalidRequest(\"Request body could not be read\");\n }\n\n if (!capped) {\n return invalidRequest(\n `Request body exceeds ${formatBytes(this.#maxBodySize)}`,\n );\n }\n\n this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(capped);\n }\n\n return this.#honoApp.fetch(request);\n }\n\n /** The Hono app, for adding custom routes alongside the MCP endpoint. */\n getApp(): Hono {\n return this.#honoApp;\n }\n\n async #buildServer(): Promise<McpServer> {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n // A tool whose schema cannot be advertised is left out rather than allowed\n // to fail the request: `tools/list` describes every tool at once, so one\n // such tool took the list down for all of them.\n const tools = (\n await Promise.all(\n this.#tools.map(async (tool) => {\n const schema = await this.#sdkSchemaFor(tool);\n\n return schema && { schema, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n\n for (const { schema, tool } of tools) {\n const call = async (args: unknown) => {\n const result = await tool.execute(args as never);\n return typeof result === \"string\"\n ? { content: [{ text: result, type: \"text\" }] }\n : result;\n };\n\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: schema.inputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone,\n // which must not reach `execute` as its parameters.\n (schema.inputSchema ? call : () => call(undefined)) as never,\n );\n }\n\n for (const resource of this.#resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n (async (uri: URL) => {\n const loaded = await resource.load();\n const body = typeof loaded === \"string\" ? { text: loaded } : loaded;\n return {\n contents: [\n {\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: uri.toString(),\n },\n ],\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of prompt.arguments ?? []) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n\n const argsSchema = prompt.arguments?.length\n ? ownKeysOnly(z.object(shape))\n : undefined;\n\n const load = async (args?: Record<string, string>) => {\n const text = await prompt.load(args ?? {});\n return {\n messages: [\n { content: { text, type: \"text\" }, role: \"user\" as const },\n ],\n };\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : () => load()) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\n }\n\n /**\n * A tool's input schema in the form the SDK registers it, or `undefined` for\n * a tool whose schema cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemaFor(tool: EdgeTool): Promise<{ inputSchema: unknown } | undefined> {\n let schema = this.#toolSchemas.get(tool);\n\n if (!schema) {\n schema = toSdkSchema(tool.parameters, \"input\", convertToJsonSchema).then(\n (inputSchema) => ({ inputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[EdgeViteMCP] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schema);\n }\n\n return schema;\n }\n}\n"]}
|
package/dist/edge/index.js
CHANGED
|
@@ -79,17 +79,24 @@ var EdgeViteMCP = class {
|
|
|
79
79
|
this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
|
|
80
80
|
this.#mcpPath = options.mcpPath ?? "/mcp";
|
|
81
81
|
}
|
|
82
|
+
// As on `ViteMCP`, an entry added under a key already in use replaces the
|
|
83
|
+
// one there, since the SDK refuses to register a key twice and a duplicate
|
|
84
|
+
// failed every request. A resource's key is its URI, a prompt's or tool's
|
|
85
|
+
// its name.
|
|
82
86
|
addPrompt(prompt) {
|
|
87
|
+
this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);
|
|
83
88
|
this.#prompts.push(prompt);
|
|
84
89
|
this.#handler = null;
|
|
85
90
|
return this;
|
|
86
91
|
}
|
|
87
92
|
addResource(resource) {
|
|
93
|
+
this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);
|
|
88
94
|
this.#resources.push(resource);
|
|
89
95
|
this.#handler = null;
|
|
90
96
|
return this;
|
|
91
97
|
}
|
|
92
98
|
addTool(tool) {
|
|
99
|
+
this.#tools = this.#tools.filter((t) => t.name !== tool.name);
|
|
93
100
|
this.#tools.push(tool);
|
|
94
101
|
this.#handler = null;
|
|
95
102
|
return this;
|
package/dist/edge/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/edge/index.ts"],"sourcesContent":["/**\n * Edge-compatible ViteMCP server for Cloudflare Workers, Deno, and Bun.\n *\n * Web-standard APIs only. `createMcpHandler` already exposes the\n * `(Request) => Response` shape edge runtimes want; this is a thin wrapper.\n */\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { Hono } from \"hono\";\nimport { z } from \"zod\";\n\nimport { formatBytes } from \"../formatBytes.js\";\nimport { ownKeysOnly } from \"../ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"../toSdkSchema.js\";\n\nexport type EdgeFetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * Logger interface for edge environments\n */\nexport interface EdgeLogger {\n debug(...args: unknown[]): void;\n error(...args: unknown[]): void;\n info(...args: unknown[]): void;\n log(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\n/**\n * Prompt definition for EdgeViteMCP\n */\nexport interface EdgePrompt {\n arguments?: Array<{ description?: string; name: string; required?: boolean }>;\n description?: string;\n load: (args: Record<string, string>) => Promise<string>;\n name: string;\n}\n\n/**\n * Resource definition for EdgeViteMCP\n */\nexport interface EdgeResource {\n description?: string;\n load: () => Promise<\n { blob?: string; mimeType?: string; text?: string } | string\n >;\n mimeType?: string;\n name: string;\n uri: string;\n}\n\n/**\n * Tool definition for EdgeViteMCP\n */\nexport interface EdgeTool<TParams = unknown> {\n description: string;\n execute: (params: TParams) => Promise<\n | {\n content: Array<{\n data?: string;\n mimeType?: string;\n text?: string;\n type: string;\n }>;\n }\n | string\n >;\n name: string;\n parameters?: StandardSchemaV1<TParams> | z.ZodType<TParams>;\n}\n\n/**\n * Options for EdgeViteMCP\n */\nexport interface EdgeViteMCPOptions {\n description?: string;\n logger?: EdgeLogger;\n /**\n * Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,\n * as on the Node transport). A larger one is refused without being held in\n * memory. Routes added through `getApp()` are not covered.\n */\n maxBodySize?: number;\n /**\n * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\n/**\n * JSON Schema for a schema that carries none, from the one converter this\n * entry point can afford. `ViteMCP` hands every other library to xsschema,\n * which reaches each converter through an `import()` a bundler has to resolve:\n * an edge bundle would then fail to build for want of Effect or Sury, whichever\n * library the server was actually written in.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) => {\n const { vendor } = schema[\"~standard\"];\n\n if (vendor !== \"valibot\") {\n throw new Error(\n `Schema library \"${vendor}\" carries no JSON Schema (\\`~standard.jsonSchema\\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`,\n );\n }\n\n return valibotToJsonSchema(schema, io);\n};\n\n/**\n * The request with its body read under a hard cap, or `null` when the body is\n * larger than that.\n *\n * The SDK reads whatever it is handed in full, so the cap has to be applied\n * before it sees the request — and while reading, not after: a declared\n * `Content-Length` over the cap is refused before a byte is read, and a body\n * that declares none is abandoned at the first chunk past it.\n */\nconst readCappedRequest = async (\n request: Request,\n maxBytes: number,\n): Promise<null | Request> => {\n if (!request.body) {\n return request;\n }\n\n if (Number(request.headers.get(\"content-length\") ?? 0) > maxBytes) {\n return null;\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > maxBytes) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n\n const body = new Uint8Array(size);\n let offset = 0;\n\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n // Rebuilt rather than cloned: the original's body is spent.\n return new Request(request.url, {\n body,\n headers: request.headers,\n method: request.method,\n signal: request.signal,\n });\n};\n\n/** The Node transport's default for `httpStream.maxBodySize`. */\nconst DEFAULT_MAX_BODY_SIZE = 1024 * 1024;\n\n/** A refusal in the shape the Node transport gives a body it will not take. */\nconst invalidRequest = (description: string): Response =>\n Response.json(\n { error: \"invalid_request\", error_description: description },\n { status: 400 },\n );\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\n /** Each tool's input schema, as `#sdkSchemaFor` converted it. */\n #toolSchemas = new WeakMap<\n EdgeTool,\n Promise<{ inputSchema: unknown } | undefined>\n >();\n #version: string;\n\n constructor(options: EdgeViteMCPOptions) {\n this.#name = options.name;\n this.#version = options.version;\n this.#logger = options.logger ?? console;\n this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;\n this.#mcpPath = options.mcpPath ?? \"/mcp\";\n }\n\n addPrompt(prompt: EdgePrompt): this {\n this.#prompts.push(prompt);\n this.#handler = null;\n return this;\n }\n\n addResource(resource: EdgeResource): this {\n this.#resources.push(resource);\n this.#handler = null;\n return this;\n }\n\n addTool<TParams>(tool: EdgeTool<TParams>): this {\n this.#tools.push(tool as EdgeTool);\n this.#handler = null;\n return this;\n }\n\n /** Main entry point for edge runtimes. */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n\n if (url.pathname === this.#mcpPath) {\n let capped: null | Request;\n\n try {\n capped = await readCappedRequest(request, this.#maxBodySize);\n } catch (error) {\n // A body that aborts mid-stream rejects here. Answer it, as the Node\n // transport does, rather than let the rejection escape the handler.\n this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);\n\n return invalidRequest(\"Request body could not be read\");\n }\n\n if (!capped) {\n return invalidRequest(\n `Request body exceeds ${formatBytes(this.#maxBodySize)}`,\n );\n }\n\n this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(capped);\n }\n\n return this.#honoApp.fetch(request);\n }\n\n /** The Hono app, for adding custom routes alongside the MCP endpoint. */\n getApp(): Hono {\n return this.#honoApp;\n }\n\n async #buildServer(): Promise<McpServer> {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n // A tool whose schema cannot be advertised is left out rather than allowed\n // to fail the request: `tools/list` describes every tool at once, so one\n // such tool took the list down for all of them.\n const tools = (\n await Promise.all(\n this.#tools.map(async (tool) => {\n const schema = await this.#sdkSchemaFor(tool);\n\n return schema && { schema, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n\n for (const { schema, tool } of tools) {\n const call = async (args: unknown) => {\n const result = await tool.execute(args as never);\n return typeof result === \"string\"\n ? { content: [{ text: result, type: \"text\" }] }\n : result;\n };\n\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: schema.inputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone,\n // which must not reach `execute` as its parameters.\n (schema.inputSchema ? call : () => call(undefined)) as never,\n );\n }\n\n for (const resource of this.#resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n (async (uri: URL) => {\n const loaded = await resource.load();\n const body = typeof loaded === \"string\" ? { text: loaded } : loaded;\n return {\n contents: [\n {\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: uri.toString(),\n },\n ],\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of prompt.arguments ?? []) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n\n const argsSchema = prompt.arguments?.length\n ? ownKeysOnly(z.object(shape))\n : undefined;\n\n const load = async (args?: Record<string, string>) => {\n const text = await prompt.load(args ?? {});\n return {\n messages: [\n { content: { text, type: \"text\" }, role: \"user\" as const },\n ],\n };\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : () => load()) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\n }\n\n /**\n * A tool's input schema in the form the SDK registers it, or `undefined` for\n * a tool whose schema cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemaFor(tool: EdgeTool): Promise<{ inputSchema: unknown } | undefined> {\n let schema = this.#toolSchemas.get(tool);\n\n if (!schema) {\n schema = toSdkSchema(tool.parameters, \"input\", convertToJsonSchema).then(\n (inputSchema) => ({ inputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[EdgeViteMCP] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schema);\n }\n\n return schema;\n }\n}\n"],"mappings":";;;;;;;;AAMA,SAAS,kBAAkB,iBAAiB;AAE5C,SAAS,YAAY;AACrB,SAAS,SAAS;AA6FlB,IAAM,sBAA2C,OAAO,QAAQ,OAAO;AACrE,QAAM,EAAE,OAAO,IAAI,OAAO,WAAW;AAErC,MAAI,WAAW,WAAW;AACxB,UAAM,IAAI;AAAA,MACR,mBAAmB,MAAM;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO,oBAAoB,QAAQ,EAAE;AACvC;AAWA,IAAM,oBAAoB,OACxB,SACA,aAC4B;AAC5B,MAAI,CAAC,QAAQ,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,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cAAM,OAAO,MAAM,OAAO,KAAK,QAAQ,CAAC,CAAC;AACzC,eAAO;AAAA,UACL,UAAU;AAAA,YACR,EAAE,SAAS,EAAE,MAAM,MAAM,OAAO,GAAG,MAAM,OAAgB;AAAA,UAC3D;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,QACL,OAAO;AAAA,QACP,EAAE,YAAY,aAAa,OAAO,YAAY;AAAA;AAAA;AAAA,QAG7C,aAAa,OAAO,MAAM,KAAK;AAAA,MAClC;AAAA,IACF;AAEA,SAAK,QAAQ,MAAM,8BAA8B,KAAK,KAAK,EAAE;AAE7D,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,cAAc,MAA+D;AAC3E,QAAI,SAAS,KAAK,aAAa,IAAI,IAAI;AAEvC,QAAI,CAAC,QAAQ;AACX,eAAS,YAAY,KAAK,YAAY,SAAS,mBAAmB,EAAE;AAAA,QAClE,CAAC,iBAAiB,EAAE,YAAY;AAAA,QAChC,CAAC,UAAmB;AAClB,eAAK,QAAQ;AAAA,YACX,uBAAuB,KAAK,IAAI;AAAA,YAChC;AAAA,UACF;AAEA,iBAAO;AAAA,QACT;AAAA,MACF;AACA,WAAK,aAAa,IAAI,MAAM,MAAM;AAAA,IACpC;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/edge/index.ts"],"sourcesContent":["/**\n * Edge-compatible ViteMCP server for Cloudflare Workers, Deno, and Bun.\n *\n * Web-standard APIs only. `createMcpHandler` already exposes the\n * `(Request) => Response` shape edge runtimes want; this is a thin wrapper.\n */\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { Hono } from \"hono\";\nimport { z } from \"zod\";\n\nimport { formatBytes } from \"../formatBytes.js\";\nimport { ownKeysOnly } from \"../ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"../toSdkSchema.js\";\n\nexport type EdgeFetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * Logger interface for edge environments\n */\nexport interface EdgeLogger {\n debug(...args: unknown[]): void;\n error(...args: unknown[]): void;\n info(...args: unknown[]): void;\n log(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\n/**\n * Prompt definition for EdgeViteMCP\n */\nexport interface EdgePrompt {\n arguments?: Array<{ description?: string; name: string; required?: boolean }>;\n description?: string;\n load: (args: Record<string, string>) => Promise<string>;\n name: string;\n}\n\n/**\n * Resource definition for EdgeViteMCP\n */\nexport interface EdgeResource {\n description?: string;\n load: () => Promise<\n { blob?: string; mimeType?: string; text?: string } | string\n >;\n mimeType?: string;\n name: string;\n uri: string;\n}\n\n/**\n * Tool definition for EdgeViteMCP\n */\nexport interface EdgeTool<TParams = unknown> {\n description: string;\n execute: (params: TParams) => Promise<\n | {\n content: Array<{\n data?: string;\n mimeType?: string;\n text?: string;\n type: string;\n }>;\n }\n | string\n >;\n name: string;\n parameters?: StandardSchemaV1<TParams> | z.ZodType<TParams>;\n}\n\n/**\n * Options for EdgeViteMCP\n */\nexport interface EdgeViteMCPOptions {\n description?: string;\n logger?: EdgeLogger;\n /**\n * Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,\n * as on the Node transport). A larger one is refused without being held in\n * memory. Routes added through `getApp()` are not covered.\n */\n maxBodySize?: number;\n /**\n * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\n/**\n * JSON Schema for a schema that carries none, from the one converter this\n * entry point can afford. `ViteMCP` hands every other library to xsschema,\n * which reaches each converter through an `import()` a bundler has to resolve:\n * an edge bundle would then fail to build for want of Effect or Sury, whichever\n * library the server was actually written in.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) => {\n const { vendor } = schema[\"~standard\"];\n\n if (vendor !== \"valibot\") {\n throw new Error(\n `Schema library \"${vendor}\" carries no JSON Schema (\\`~standard.jsonSchema\\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`,\n );\n }\n\n return valibotToJsonSchema(schema, io);\n};\n\n/**\n * The request with its body read under a hard cap, or `null` when the body is\n * larger than that.\n *\n * The SDK reads whatever it is handed in full, so the cap has to be applied\n * before it sees the request — and while reading, not after: a declared\n * `Content-Length` over the cap is refused before a byte is read, and a body\n * that declares none is abandoned at the first chunk past it.\n */\nconst readCappedRequest = async (\n request: Request,\n maxBytes: number,\n): Promise<null | Request> => {\n if (!request.body) {\n return request;\n }\n\n if (Number(request.headers.get(\"content-length\") ?? 0) > maxBytes) {\n return null;\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > maxBytes) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n\n const body = new Uint8Array(size);\n let offset = 0;\n\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n // Rebuilt rather than cloned: the original's body is spent.\n return new Request(request.url, {\n body,\n headers: request.headers,\n method: request.method,\n signal: request.signal,\n });\n};\n\n/** The Node transport's default for `httpStream.maxBodySize`. */\nconst DEFAULT_MAX_BODY_SIZE = 1024 * 1024;\n\n/** A refusal in the shape the Node transport gives a body it will not take. */\nconst invalidRequest = (description: string): Response =>\n Response.json(\n { error: \"invalid_request\", error_description: description },\n { status: 400 },\n );\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\n /** Each tool's input schema, as `#sdkSchemaFor` converted it. */\n #toolSchemas = new WeakMap<\n EdgeTool,\n Promise<{ inputSchema: unknown } | undefined>\n >();\n #version: string;\n\n constructor(options: EdgeViteMCPOptions) {\n this.#name = options.name;\n this.#version = options.version;\n this.#logger = options.logger ?? console;\n this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;\n this.#mcpPath = options.mcpPath ?? \"/mcp\";\n }\n\n // As on `ViteMCP`, an entry added under a key already in use replaces the\n // one there, since the SDK refuses to register a key twice and a duplicate\n // failed every request. A resource's key is its URI, a prompt's or tool's\n // its name.\n addPrompt(prompt: EdgePrompt): this {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n this.#handler = null;\n return this;\n }\n\n addResource(resource: EdgeResource): this {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n this.#handler = null;\n return this;\n }\n\n addTool<TParams>(tool: EdgeTool<TParams>): this {\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as EdgeTool);\n this.#handler = null;\n return this;\n }\n\n /** Main entry point for edge runtimes. */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n\n if (url.pathname === this.#mcpPath) {\n let capped: null | Request;\n\n try {\n capped = await readCappedRequest(request, this.#maxBodySize);\n } catch (error) {\n // A body that aborts mid-stream rejects here. Answer it, as the Node\n // transport does, rather than let the rejection escape the handler.\n this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);\n\n return invalidRequest(\"Request body could not be read\");\n }\n\n if (!capped) {\n return invalidRequest(\n `Request body exceeds ${formatBytes(this.#maxBodySize)}`,\n );\n }\n\n this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(capped);\n }\n\n return this.#honoApp.fetch(request);\n }\n\n /** The Hono app, for adding custom routes alongside the MCP endpoint. */\n getApp(): Hono {\n return this.#honoApp;\n }\n\n async #buildServer(): Promise<McpServer> {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n // A tool whose schema cannot be advertised is left out rather than allowed\n // to fail the request: `tools/list` describes every tool at once, so one\n // such tool took the list down for all of them.\n const tools = (\n await Promise.all(\n this.#tools.map(async (tool) => {\n const schema = await this.#sdkSchemaFor(tool);\n\n return schema && { schema, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n\n for (const { schema, tool } of tools) {\n const call = async (args: unknown) => {\n const result = await tool.execute(args as never);\n return typeof result === \"string\"\n ? { content: [{ text: result, type: \"text\" }] }\n : result;\n };\n\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: schema.inputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone,\n // which must not reach `execute` as its parameters.\n (schema.inputSchema ? call : () => call(undefined)) as never,\n );\n }\n\n for (const resource of this.#resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n (async (uri: URL) => {\n const loaded = await resource.load();\n const body = typeof loaded === \"string\" ? { text: loaded } : loaded;\n return {\n contents: [\n {\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: uri.toString(),\n },\n ],\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of prompt.arguments ?? []) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n\n const argsSchema = prompt.arguments?.length\n ? ownKeysOnly(z.object(shape))\n : undefined;\n\n const load = async (args?: Record<string, string>) => {\n const text = await prompt.load(args ?? {});\n return {\n messages: [\n { content: { text, type: \"text\" }, role: \"user\" as const },\n ],\n };\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : () => load()) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\n }\n\n /**\n * A tool's input schema in the form the SDK registers it, or `undefined` for\n * a tool whose schema cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemaFor(tool: EdgeTool): Promise<{ inputSchema: unknown } | undefined> {\n let schema = this.#toolSchemas.get(tool);\n\n if (!schema) {\n schema = toSdkSchema(tool.parameters, \"input\", convertToJsonSchema).then(\n (inputSchema) => ({ inputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[EdgeViteMCP] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schema);\n }\n\n return schema;\n }\n}\n"],"mappings":";;;;;;;;AAMA,SAAS,kBAAkB,iBAAiB;AAE5C,SAAS,YAAY;AACrB,SAAS,SAAS;AA6FlB,IAAM,sBAA2C,OAAO,QAAQ,OAAO;AACrE,QAAM,EAAE,OAAO,IAAI,OAAO,WAAW;AAErC,MAAI,WAAW,WAAW;AACxB,UAAM,IAAI;AAAA,MACR,mBAAmB,MAAM;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO,oBAAoB,QAAQ,EAAE;AACvC;AAWA,IAAM,oBAAoB,OACxB,SACA,aAC4B;AAC5B,MAAI,CAAC,QAAQ,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,QAAQ,QAAQ,IAAI,gBAAgB,KAAK,CAAC,IAAI,UAAU;AACjE,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,QAAQ,KAAK,UAAU;AACtC,QAAM,SAAuB,CAAC;AAC9B,MAAI,OAAO;AAEX,aAAS;AACP,UAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,QAAI,MAAM;AACR;AAAA,IACF;AAEA,YAAQ,MAAM;AAEd,QAAI,OAAO,UAAU;AACnB,YAAM,OAAO,OAAO,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AACpC,aAAO;AAAA,IACT;AAEA,WAAO,KAAK,KAAK;AAAA,EACnB;AAEA,QAAM,OAAO,IAAI,WAAW,IAAI;AAChC,MAAI,SAAS;AAEb,aAAW,SAAS,QA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AA;AAAA;AAAA,QAG7C,aAAa,OAAO,MAAM,KAAK;AAAA,MAClC;AAAA,IACF;AAEA,SAAK,QAAQ,MAAM,8BAA8B,KAAK,KAAK,EAAE;AAE7D,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,cAAc,MAA+D;AAC3E,QAAI,SAAS,KAAK,aAAa,IAAI,IAAI;AAEvC,QAAI,CAAC,QAAQ;AACX,eAAS,YAAY,KAAK,YAAY,SAAS,mBAAmB,EAAE;AAAA,QAClE,CAAC,iBAAiB,EAAE,YAAY;AAAA,QAChC,CAAC,UAAmB;AAClB,eAAK,QAAQ;AAAA,YACX,uBAAuB,KAAK,IAAI;AAAA,YAChC;AAAA,UACF;AAEA,iBAAO;AAAA,QACT;AAAA,MACF;AACA,WAAK,aAAa,IAAI,MAAM,MAAM;AAAA,IACpC;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/openapi/index.cjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkR7AFGJBRcjs = require('../chunk-R7AFGJBR.cjs');
|
|
7
7
|
require('../chunk-NSHLX6PZ.cjs');
|
|
8
8
|
require('../chunk-ZVA6Y7EO.cjs');
|
|
9
9
|
|
|
@@ -111,7 +111,7 @@ var serializeSimple = (value, explode, name, style) => {
|
|
|
111
111
|
([, entry]) => entry !== void 0
|
|
112
112
|
);
|
|
113
113
|
if (style === "matrix" && explode) {
|
|
114
|
-
return entries.map(([key, entry]) => `;${key}=${encode(entry)}`).join("");
|
|
114
|
+
return entries.map(([key, entry]) => `;${encodeURIComponent(key)}=${encode(entry)}`).join("");
|
|
115
115
|
}
|
|
116
116
|
if (explode) {
|
|
117
117
|
return entries.map(([key, entry]) => `${encodeURIComponent(key)}=${encode(entry)}`).join(style === "label" ? "." : ",");
|
|
@@ -130,7 +130,7 @@ var executeRequest = async (options) => {
|
|
|
130
130
|
const query = new URLSearchParams();
|
|
131
131
|
const cookies = [];
|
|
132
132
|
const headers = new Headers();
|
|
133
|
-
const bodyValues =
|
|
133
|
+
const bodyValues = /* @__PURE__ */ Object.create(null);
|
|
134
134
|
for (const [key, value] of Object.entries(args)) {
|
|
135
135
|
const binder = binding.parameters[key];
|
|
136
136
|
if (!binder || value === void 0) {
|
|
@@ -206,7 +206,7 @@ var resolveBaseUrl = (servers, origin, override) => {
|
|
|
206
206
|
}
|
|
207
207
|
let url = server.url;
|
|
208
208
|
for (const [name, variable] of Object.entries(_nullishCoalesce(server.variables, () => ( {})))) {
|
|
209
|
-
url = url.replaceAll(`{${name}}`, variable.default);
|
|
209
|
+
url = url.replaceAll(`{${name}}`, () => variable.default);
|
|
210
210
|
}
|
|
211
211
|
try {
|
|
212
212
|
return trimSlash(new URL(url).toString());
|
|
@@ -271,18 +271,18 @@ var buildBody = (binding, values, headers) => {
|
|
|
271
271
|
var buildPath = (route, values) => {
|
|
272
272
|
const unfilled = [...route.path.matchAll(/\{([^{}]*)\}/g)].filter(([, name]) => !values.has(name)).map(([placeholder]) => placeholder);
|
|
273
273
|
if (unfilled.length > 0) {
|
|
274
|
-
throw new (0,
|
|
274
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
275
275
|
`${route.method.toUpperCase()} ${route.path} cannot be called: the OpenAPI document declares no path parameter for ${unfilled.join(", ")}.`
|
|
276
276
|
);
|
|
277
277
|
}
|
|
278
278
|
let path = route.path;
|
|
279
279
|
for (const [name, value] of values) {
|
|
280
|
-
path = path.replaceAll(`{${name}}`, value);
|
|
280
|
+
path = path.replaceAll(`{${name}}`, () => value);
|
|
281
281
|
}
|
|
282
282
|
const written = new Set(route.path.split("/").filter(isDotSegment));
|
|
283
283
|
const introduced = path.split("/").find((segment) => isDotSegment(segment) && !written.has(segment));
|
|
284
284
|
if (introduced !== void 0) {
|
|
285
|
-
throw new (0,
|
|
285
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
286
286
|
`${route.method.toUpperCase()} ${route.path} cannot be called with a path segment of "${introduced}": a URL resolves it as a step through the path, so the request would reach a different endpoint.`
|
|
287
287
|
);
|
|
288
288
|
}
|
|
@@ -300,7 +300,7 @@ var readResponse = async (response, options) => {
|
|
|
300
300
|
const mediaType = contentType.split(";")[0].trim().toLowerCase();
|
|
301
301
|
const label = `${route.method.toUpperCase()} ${route.path}`;
|
|
302
302
|
if (!response.ok) {
|
|
303
|
-
throw new (0,
|
|
303
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
304
304
|
`${label} failed with ${response.status} ${response.statusText}: ${truncate(
|
|
305
305
|
await response.text(),
|
|
306
306
|
2e3
|
|
@@ -312,7 +312,7 @@ var readResponse = async (response, options) => {
|
|
|
312
312
|
if (bytes.byteLength <= MAX_INLINE_MEDIA_BYTES) {
|
|
313
313
|
return mediaType.startsWith("image/") ? { data: toBase64(bytes), mimeType: mediaType, type: "image" } : { data: toBase64(bytes), mimeType: mediaType, type: "audio" };
|
|
314
314
|
}
|
|
315
|
-
throw new (0,
|
|
315
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
316
316
|
`${label} returned ${bytes.byteLength} bytes of ${contentType}, too large to return inline.`
|
|
317
317
|
);
|
|
318
318
|
}
|
|
@@ -322,7 +322,7 @@ var readResponse = async (response, options) => {
|
|
|
322
322
|
return { structuredContent: parsed };
|
|
323
323
|
}
|
|
324
324
|
if (binding.outputSchema) {
|
|
325
|
-
throw new (0,
|
|
325
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
326
326
|
`${label} declares a JSON object response but returned ${contentType || "an untyped body"}. Set \`outputSchema: false\` if this document's response schemas do not match the API.`
|
|
327
327
|
);
|
|
328
328
|
}
|
|
@@ -344,7 +344,7 @@ var setHeader = (headers, name, value) => {
|
|
|
344
344
|
try {
|
|
345
345
|
headers.set(name, value);
|
|
346
346
|
} catch (e2) {
|
|
347
|
-
throw new (0,
|
|
347
|
+
throw new (0, _chunkR7AFGJBRcjs.UserError)(
|
|
348
348
|
`"${name}" is not a valid header name, or the value given for it is not a valid header value.`
|
|
349
349
|
);
|
|
350
350
|
}
|
|
@@ -436,7 +436,7 @@ var hasExternalRef = (root) => {
|
|
|
436
436
|
}
|
|
437
437
|
return false;
|
|
438
438
|
};
|
|
439
|
-
var isHttpUrl = (value) =>
|
|
439
|
+
var isHttpUrl = (value) => /^https?:\/\//i.test(value);
|
|
440
440
|
var parseJson = (text) => {
|
|
441
441
|
try {
|
|
442
442
|
const value = JSON.parse(text);
|
|
@@ -451,7 +451,7 @@ var readSpecText = async (spec) => {
|
|
|
451
451
|
headers: { accept: "application/json, text/yaml, */*" }
|
|
452
452
|
});
|
|
453
453
|
if (!response.ok) {
|
|
454
|
-
await
|
|
454
|
+
await _chunkR7AFGJBRcjs.cancelResponseBody.call(void 0, response);
|
|
455
455
|
throw new Error(
|
|
456
456
|
`Failed to fetch the OpenAPI document from ${spec}: ${response.status} ${response.statusText}`
|
|
457
457
|
);
|
|
@@ -603,7 +603,7 @@ var generateToolNames = (routes, override) => {
|
|
|
603
603
|
return names;
|
|
604
604
|
};
|
|
605
605
|
var baseNameFor = (route, override) => {
|
|
606
|
-
const explicit = typeof override === "function" ? override(toOperationSummary(route)) : route.operationId
|
|
606
|
+
const explicit = typeof override === "function" ? override(toOperationSummary(route)) : route.operationId && override && Object.hasOwn(override, route.operationId) ? override[route.operationId] : void 0;
|
|
607
607
|
if (explicit) {
|
|
608
608
|
return explicit;
|
|
609
609
|
}
|
|
@@ -770,7 +770,7 @@ var readPointer2 = (root, pointer) => {
|
|
|
770
770
|
}
|
|
771
771
|
let node = root;
|
|
772
772
|
for (const segment of pointer.split("/").slice(1)) {
|
|
773
|
-
node = _optionalChain([node, 'optionalAccess',
|
|
773
|
+
node = _optionalChain([node, 'optionalAccess', _11 => _11[decodeSegment2(segment)]]);
|
|
774
774
|
}
|
|
775
775
|
return node;
|
|
776
776
|
};
|
|
@@ -798,24 +798,24 @@ var buildToolBinding = (route, normalizer, withOutputSchema) => {
|
|
|
798
798
|
parameter
|
|
799
799
|
]);
|
|
800
800
|
}
|
|
801
|
-
const collides = (name, occurrences) => occurrences.length > 1 || body.properties.has(name);
|
|
801
|
+
const collides = (name, occurrences) => name === "__proto__" || occurrences.length > 1 || body.properties.has(name);
|
|
802
802
|
const takenKeys = new Set(body.properties.keys());
|
|
803
803
|
for (const [name, occurrences] of byName) {
|
|
804
804
|
if (!collides(name, occurrences)) {
|
|
805
805
|
takenKeys.add(name);
|
|
806
806
|
}
|
|
807
807
|
}
|
|
808
|
+
const claimKey = (base) => {
|
|
809
|
+
let key = base;
|
|
810
|
+
for (let suffix = 2; takenKeys.has(key); suffix++) {
|
|
811
|
+
key = `${base}_${suffix}`;
|
|
812
|
+
}
|
|
813
|
+
takenKeys.add(key);
|
|
814
|
+
return key;
|
|
815
|
+
};
|
|
808
816
|
for (const [name, occurrences] of byName) {
|
|
809
817
|
for (const parameter of occurrences) {
|
|
810
|
-
|
|
811
|
-
if (collides(name, occurrences)) {
|
|
812
|
-
const base = `${name}__${parameter.in}`;
|
|
813
|
-
key = base;
|
|
814
|
-
for (let suffix = 2; takenKeys.has(key); suffix++) {
|
|
815
|
-
key = `${base}_${suffix}`;
|
|
816
|
-
}
|
|
817
|
-
takenKeys.add(key);
|
|
818
|
-
}
|
|
818
|
+
const key = collides(name, occurrences) ? claimKey(`${name}__${parameter.in}`) : name;
|
|
819
819
|
properties[key] = describeParameter(parameter, normalizer);
|
|
820
820
|
parameters[key] = { kind: "parameter", parameter };
|
|
821
821
|
if (parameter.in === "path" || parameter.required) {
|
|
@@ -824,10 +824,11 @@ var buildToolBinding = (route, normalizer, withOutputSchema) => {
|
|
|
824
824
|
}
|
|
825
825
|
}
|
|
826
826
|
for (const [name, property] of body.properties) {
|
|
827
|
-
|
|
828
|
-
|
|
827
|
+
const key = name === "__proto__" ? claimKey(`${name}__body`) : name;
|
|
828
|
+
properties[key] = property.schema;
|
|
829
|
+
parameters[key] = { kind: "body", name };
|
|
829
830
|
if (property.required) {
|
|
830
|
-
required.push(
|
|
831
|
+
required.push(key);
|
|
831
832
|
}
|
|
832
833
|
}
|
|
833
834
|
const inputSchema = {
|
|
@@ -852,7 +853,7 @@ var buildToolBinding = (route, normalizer, withOutputSchema) => {
|
|
|
852
853
|
};
|
|
853
854
|
var describeBody = (route, normalizer) => {
|
|
854
855
|
const properties = /* @__PURE__ */ new Map();
|
|
855
|
-
const content = route.method === "get" ? void 0 : _optionalChain([route, 'access',
|
|
856
|
+
const content = route.method === "get" ? void 0 : _optionalChain([route, 'access', _12 => _12.requestBody, 'optionalAccess', _13 => _13.content]);
|
|
856
857
|
if (!content || Object.keys(content).length === 0) {
|
|
857
858
|
return { properties };
|
|
858
859
|
}
|
|
@@ -865,8 +866,8 @@ var describeBody = (route, normalizer) => {
|
|
|
865
866
|
}
|
|
866
867
|
const kind = encodingKindFor(contentType);
|
|
867
868
|
const encoding = { contentType, kind };
|
|
868
|
-
const required = _nullishCoalesce(_optionalChain([route, 'access',
|
|
869
|
-
const rawSchema = _optionalChain([content, 'access',
|
|
869
|
+
const required = _nullishCoalesce(_optionalChain([route, 'access', _14 => _14.requestBody, 'optionalAccess', _15 => _15.required]), () => ( false));
|
|
870
|
+
const rawSchema = _optionalChain([content, 'access', _16 => _16[contentType], 'optionalAccess', _17 => _17.schema]);
|
|
870
871
|
const schema = rawSchema ? normalizer.normalize(rawSchema) : void 0;
|
|
871
872
|
if (kind === "text") {
|
|
872
873
|
properties.set("body", { required, schema: _nullishCoalesce(schema, () => ( { type: "string" })) });
|
|
@@ -891,9 +892,9 @@ var describeBody = (route, normalizer) => {
|
|
|
891
892
|
var MAX_OUTPUT_SCHEMA_DEFINITIONS = 100;
|
|
892
893
|
var buildOutputSchema = (route, normalizer) => {
|
|
893
894
|
const status = Object.keys(route.responses).filter((code) => /^2\d\d$/.test(code)).sort()[0];
|
|
894
|
-
const content = status ? _optionalChain([route, 'access',
|
|
895
|
+
const content = status ? _optionalChain([route, 'access', _18 => _18.responses, 'access', _19 => _19[status], 'optionalAccess', _20 => _20.content]) : void 0;
|
|
895
896
|
const contentType = content && findJsonContentType(Object.keys(content));
|
|
896
|
-
const raw = contentType ? _optionalChain([content, 'optionalAccess',
|
|
897
|
+
const raw = contentType ? _optionalChain([content, 'optionalAccess', _21 => _21[contentType], 'optionalAccess', _22 => _22.schema]) : void 0;
|
|
897
898
|
if (!raw) {
|
|
898
899
|
return void 0;
|
|
899
900
|
}
|
|
@@ -931,7 +932,7 @@ var flattenObject = (schema, definitions, depth = 0) => {
|
|
|
931
932
|
);
|
|
932
933
|
}
|
|
933
934
|
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
934
|
-
const properties2 =
|
|
935
|
+
const properties2 = /* @__PURE__ */ Object.create(null);
|
|
935
936
|
const required = /* @__PURE__ */ new Set();
|
|
936
937
|
for (const branch of schema.allOf) {
|
|
937
938
|
const part = flattenObject(
|
|
@@ -1031,10 +1032,10 @@ var fromOpenAPI = async (options) => {
|
|
|
1031
1032
|
const selected = selectRoutes(extractRoutes(document), options);
|
|
1032
1033
|
const names = generateToolNames(selected, options.toolNames);
|
|
1033
1034
|
const normalizer = createSchemaNormalizer(document);
|
|
1034
|
-
const server = _nullishCoalesce(options.server, () => ( new (0,
|
|
1035
|
-
description: _optionalChain([document, 'access',
|
|
1036
|
-
name: _nullishCoalesce(_nullishCoalesce(options.name, () => ( _optionalChain([document, 'access',
|
|
1037
|
-
version: _nullishCoalesce(options.version, () => ( semanticVersion(_optionalChain([document, 'access',
|
|
1035
|
+
const server = _nullishCoalesce(options.server, () => ( new (0, _chunkR7AFGJBRcjs.ViteMCP)({
|
|
1036
|
+
description: _optionalChain([document, 'access', _23 => _23.info, 'optionalAccess', _24 => _24.description]),
|
|
1037
|
+
name: _nullishCoalesce(_nullishCoalesce(options.name, () => ( _optionalChain([document, 'access', _25 => _25.info, 'optionalAccess', _26 => _26.title]))), () => ( "OpenAPI")),
|
|
1038
|
+
version: _nullishCoalesce(options.version, () => ( semanticVersion(_optionalChain([document, 'access', _27 => _27.info, 'optionalAccess', _28 => _28.version]))))
|
|
1038
1039
|
})));
|
|
1039
1040
|
for (const route of selected) {
|
|
1040
1041
|
const name = names.get(route);
|
|
@@ -1070,8 +1071,8 @@ var fromOpenAPI = async (options) => {
|
|
|
1070
1071
|
route
|
|
1071
1072
|
}),
|
|
1072
1073
|
name,
|
|
1073
|
-
outputSchema: binding.outputSchema ?
|
|
1074
|
-
parameters:
|
|
1074
|
+
outputSchema: binding.outputSchema ? _chunkR7AFGJBRcjs.jsonSchemaAdapter.call(void 0, binding.outputSchema) : void 0,
|
|
1075
|
+
parameters: _chunkR7AFGJBRcjs.jsonSchemaAdapter.call(void 0, binding.inputSchema),
|
|
1075
1076
|
timeoutMs: options.timeoutMs
|
|
1076
1077
|
});
|
|
1077
1078
|
}
|