@vitemcp/server 1.9.17 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -1
- package/dist/ViteMCP.cjs +4 -4
- package/dist/ViteMCP.d.cts +18 -1
- package/dist/ViteMCP.d.ts +18 -1
- package/dist/ViteMCP.js +3 -3
- package/dist/auth/index.cjs +2 -2
- package/dist/auth/index.d.cts +21 -1
- package/dist/auth/index.d.ts +21 -1
- package/dist/auth/index.js +1 -1
- package/dist/{chunk-B3LLXB6O.js → chunk-3W6VP3KX.js} +32 -11
- package/dist/chunk-3W6VP3KX.js.map +1 -0
- package/dist/{chunk-ZEYQBA72.cjs → chunk-4LU4AXU4.cjs} +83 -39
- package/dist/chunk-4LU4AXU4.cjs.map +1 -0
- package/dist/{chunk-JMDI672G.js → chunk-BLXUZUZ4.js} +16 -1
- package/dist/chunk-BLXUZUZ4.js.map +1 -0
- package/dist/{chunk-TNT3APOK.cjs → chunk-FSPSPB7Y.cjs} +37 -16
- package/dist/chunk-FSPSPB7Y.cjs.map +1 -0
- package/dist/{chunk-4BX2CT5Z.js → chunk-NLBRDP5F.js} +84 -40
- package/dist/{chunk-4BX2CT5Z.js.map → chunk-NLBRDP5F.js.map} +1 -1
- package/dist/{chunk-QPVEGWOL.cjs → chunk-NZGRSB2D.cjs} +17 -2
- package/dist/chunk-NZGRSB2D.cjs.map +1 -0
- package/dist/edge/index.cjs +23 -10
- package/dist/edge/index.cjs.map +1 -1
- package/dist/edge/index.d.cts +11 -0
- package/dist/edge/index.d.ts +11 -0
- package/dist/edge/index.js +19 -6
- package/dist/edge/index.js.map +1 -1
- package/dist/openapi/index.cjs +43 -43
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.js +33 -33
- package/dist/openapi/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-B3LLXB6O.js.map +0 -1
- package/dist/chunk-JMDI672G.js.map +0 -1
- package/dist/chunk-QPVEGWOL.cjs.map +0 -1
- package/dist/chunk-TNT3APOK.cjs.map +0 -1
- package/dist/chunk-ZEYQBA72.cjs.map +0 -1
|
@@ -65,6 +65,20 @@ var isPlain = (value) => {
|
|
|
65
65
|
return Array.isArray(value) || prototype === Object.prototype || prototype === null;
|
|
66
66
|
};
|
|
67
67
|
|
|
68
|
+
// src/toolInputLimit.ts
|
|
69
|
+
var DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 1e4;
|
|
70
|
+
var resolveMaxToolInputElements = (value) => {
|
|
71
|
+
if (value === void 0) {
|
|
72
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
73
|
+
}
|
|
74
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
|
|
75
|
+
throw new RangeError(
|
|
76
|
+
`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
};
|
|
81
|
+
|
|
68
82
|
// src/toSdkSchema.ts
|
|
69
83
|
var SDK_TARGET = "draft-2020-12";
|
|
70
84
|
var LENIENT_OPTIONS = /* @__PURE__ */ new Map([
|
|
@@ -154,5 +168,6 @@ var strictInputSchema = (schema) => ({
|
|
|
154
168
|
|
|
155
169
|
|
|
156
170
|
|
|
157
|
-
|
|
158
|
-
|
|
171
|
+
|
|
172
|
+
exports.formatBytes = formatBytes; exports.ownKeysOnly = ownKeysOnly; exports.resolveMaxToolInputElements = resolveMaxToolInputElements; exports.toSdkSchema = toSdkSchema; exports.valibotToJsonSchema = valibotToJsonSchema;
|
|
173
|
+
//# sourceMappingURL=chunk-NZGRSB2D.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/server/server/dist/chunk-NZGRSB2D.cjs","../src/formatBytes.ts","../src/ownKeysOnly.ts","../src/toolInputLimit.ts","../src/toSdkSchema.ts"],"names":[],"mappings":"AAAA;ACCO,IAAM,YAAA,EAAc,C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AA;AACF,IAAA;AACM,EAAA;AACA,IAAA;AACJ,MAAA;AAEF,IAAA;AACF,EAAA;AAEO,EAAA;AACL,IAAA;AACA,IAAA;AACD,EAAA;AACH;AAGM;AAIJ,EAAA;AACK,IAAA;AACH,IAAA;AACF,EAAA;AACF;AAQM;AAIA,EAAA;AACI,IAAA;AACJ,MAAA;AACE,QAAA;AACD,MAAA;AACH,IAAA;AACF,EAAA;AACF;AAMM;AAKA,EAAA;AACK,IAAA;AACA,EAAA;AACD,IAAA;AAED,IAAA;AACG,MAAA;AACR,IAAA;AAEO,IAAA;AACC,MAAA;AACN,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAeM;AACD,EAAA;AACG,EAAA;AACJ,IAAA;AAIF,EAAA;AACW,EAAA;AACT,IAAA;AACE,MAAA;AACE,QAAA;AACA,QAAA;AAGD,MAAA;AACH,IAAA;AACF,EAAA;AACF;AJhEY;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/server/server/dist/chunk-NZGRSB2D.cjs","sourcesContent":[null,"/** Renders a byte cap the way the error message should read (e.g. \"1 MiB\"). */\nexport const formatBytes = (bytes: number): string => {\n if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {\n return `${bytes / (1024 * 1024)} MiB`;\n }\n\n if (bytes >= 1024 && bytes % 1024 === 0) {\n return `${bytes / 1024} KiB`;\n }\n\n return `${bytes} bytes`;\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Has `schema` validate by own keys only — see `withOwnKeysOnly` — by\n * replacing its `~standard` in place. The schema keeps its `shape`, which the\n * SDK reads to complete an argument, and its JSON Schema, which `prompts/list`\n * is built from.\n *\n * For the argument schemas `ViteMCP` and `EdgeViteMCP` build for their\n * prompts. A tool's schemas belong to whoever wrote the tool, so\n * `toSdkSchema` wraps them instead.\n *\n * An argument map the request left out validates as an empty one, as the SDK\n * already arranges for a tool's. `prompts/get` may omit `arguments`, and the\n * SDK validates the map as it was sent, so a prompt whose arguments are all\n * optional refused the request as \"expected object, received undefined\".\n */\nexport const ownKeysOnly = <S extends StandardSchemaV1>(schema: S): S => {\n const standard = withOwnKeysOnly(schema[\"~standard\"]);\n\n return Object.defineProperty(schema, \"~standard\", {\n value: {\n ...standard,\n validate: (value: unknown) => standard.validate(value ?? {}),\n },\n });\n};\n\n/**\n * `standard`, with a `validate` that sees only the keys an object has of its\n * own.\n *\n * Zod and Valibot look each key up with `in` and read it with `[]`, and both\n * walk the prototype chain, so a key that was left out reads as present when\n * `Object.prototype` has a member by that name. An optional argument called\n * `toString`, `constructor` or `valueOf`, at any depth, failed every request\n * that left it out, as \"expected string, received function\", and a required\n * one was reported as the wrong type instead of as missing. Validating a copy\n * whose objects have no prototype leaves the library nothing to inherit.\n *\n * A library that hands its input back, as ArkType and `jsonSchemaAdapter` do,\n * hands back the copy, so the copied objects get their prototype back before\n * the value goes on: `execute` still receives ordinary objects.\n */\nexport const withOwnKeysOnly = <P extends StandardSchemaV1.Props>(\n standard: P,\n): P => ({\n ...standard,\n validate: async (value: unknown) => {\n const copies = new Map<object, object>();\n const result = await standard.validate(withoutPrototypes(value, copies));\n\n if (!result.issues && copies.size > 0) {\n restorePrototypes(result.value, new Set(copies.values()), new Set());\n }\n\n return result;\n },\n});\n\n/**\n * `value`, with each plain object in it, at any depth, copied onto one without\n * a prototype, and each array copied to reach them. `copies` maps every\n * original to its copy, so one that occurs twice, or inside itself, is copied\n * once.\n */\nconst withoutPrototypes = (\n value: unknown,\n copies: Map<object, object>,\n): unknown => {\n if (!isPlain(value)) {\n return value;\n }\n\n const existing = copies.get(value);\n\n if (existing) {\n return existing;\n }\n\n const copy: Record<string, unknown> = Array.isArray(value)\n ? []\n : Object.create(null);\n\n copies.set(value, copy);\n\n for (const [key, item] of Object.entries(value)) {\n copy[key] = withoutPrototypes(item, copies);\n }\n\n return copy;\n};\n\n/**\n * Gives each object copy in `copies` that `value` holds, at any depth,\n * `Object.prototype` back.\n */\nconst restorePrototypes = (\n value: unknown,\n copies: Set<object>,\n seen: Set<object>,\n): void => {\n if (!isPlain(value) || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (copies.has(value) && !Array.isArray(value)) {\n Object.setPrototypeOf(value, Object.prototype);\n }\n\n for (const item of Object.values(value)) {\n restorePrototypes(item, copies, seen);\n }\n};\n\n/**\n * An array, or an object made by a literal or without a prototype: what JSON\n * parses to, and the only kinds of object that are copied.\n */\nconst isPlain = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const prototype: unknown = Object.getPrototypeOf(value);\n\n return (\n Array.isArray(value) || prototype === Object.prototype || prototype === null\n );\n};\n","/**\n * `maxToolInputElements` when a server sets none.\n *\n * Validation keeps every issue it finds, so what checking one call costs grows\n * with how many elements its arguments hold, and a cap on the body does not\n * bound it: half a million invalid elements fit in 1 MiB, and Zod kept half a\n * gigabyte of issues reporting them. Ten thousand keep that near 8 MB.\n */\nconst DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10_000;\n\n/**\n * The limit a server was given, or the default, refused where the SDK would\n * refuse it. The SDK checks as it builds a server, and a server is built for\n * every request: checked once up front, a bad value stops the server from\n * being created rather than failing every request it would have answered.\n */\nexport const resolveMaxToolInputElements = (\n value: number | undefined,\n): number => {\n if (value === undefined) {\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n }\n\n if (typeof value !== \"number\" || Number.isNaN(value) || value < 1) {\n throw new RangeError(\n `maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`,\n );\n }\n\n return value;\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { JsonSchema } from \"xsschema\";\n\nimport { withOwnKeysOnly } from \"./ownKeysOnly.js\";\n\n/**\n * Turns a Standard Schema that carries no JSON Schema into one. Which\n * libraries that can be done for depends on the runtime, so each entry point\n * supplies its own.\n */\nexport type JsonSchemaConverter = (\n schema: StandardSchemaV1,\n io: \"input\" | \"output\",\n) => Promise<JsonSchema>;\n\n/**\n * `~standard.jsonSchema`, as Zod v4 and ArkType implement it. Declared here\n * because `@standard-schema/spec` 1.0 predates it.\n */\ntype NativeJsonSchema = Record<\n \"input\" | \"output\",\n (options: {\n libraryOptions?: Record<string, unknown>;\n target: string;\n }) => JsonSchema\n>;\n\n/** The draft the SDK asks a schema for when `tools/list` describes a tool. */\nconst SDK_TARGET = \"draft-2020-12\";\n\n/**\n * What a library is told so that it leaves open the parts of a schema JSON\n * Schema cannot say, rather than refuse the schema over them. Zod describes\n * such a part as `{}`. ArkType hands over what it had worked out before it\n * reached the part: `{}` for a `Date`, `{ type: \"string\" }` for a string under\n * a `narrow()`.\n *\n * A library not named here is left to refuse, and its tool is not served.\n */\nconst LENIENT_OPTIONS = new Map<string, Record<string, unknown>>([\n [\"arktype\", { fallback: (context: { base: JsonSchema }) => context.base }],\n [\"zod\", { unrepresentable: \"any\" }],\n]);\n\n/**\n * A tool's schema as the SDK registers it: one that validates by own keys only\n * (see `withOwnKeysOnly`) and carries a JSON Schema. The schema itself is left\n * as it was, since whoever wrote it may use it elsewhere.\n *\n * Zod v4 and ArkType emit JSON Schema natively, and theirs is kept; anything\n * else (Valibot, say) is converted, and the conversion is only what\n * `tools/list` advertises. Validation stays with the library the schema was\n * written in: the conversion drops what JSON Schema cannot say — a transform,\n * a `check()` — so validating against it instead would pass `execute`\n * arguments the schema never produced.\n *\n * A native schema is converted here too, once, the way the SDK will for\n * `tools/list`. The SDK converts every tool in the one handler, so a schema\n * its library refused to convert — a `z.date()`, a `z.bigint()`, an ArkType\n * `narrow()` — failed the list for every tool, though each could still be\n * called. One refused is asked for again with what JSON Schema cannot say left\n * open (see `LENIENT_OPTIONS`), which is what Valibot's converter is already\n * told, and that copy is advertised in place of the library's own.\n *\n * Converted inputs are closed with `strictInputSchema`. Outputs are left as\n * converted, since closing them would misdescribe results the schema allows.\n *\n * Shared by `ViteMCP` and `EdgeViteMCP`, so what a tool advertises does not\n * depend on which of them serves it. Rejects when `convert` does, when a\n * library refuses a schema even leniently, and for an input schema that does\n * not describe an object: each caller leaves that tool out and serves the rest.\n */\nexport const toSdkSchema = async (\n schema: unknown,\n io: \"input\" | \"output\",\n convert: JsonSchemaConverter,\n): Promise<unknown> => {\n if (!schema) {\n return undefined;\n }\n\n const standard = withOwnKeysOnly(\n (\n schema as {\n \"~standard\": {\n jsonSchema?: NativeJsonSchema;\n } & StandardSchemaV1.Props;\n }\n )[\"~standard\"],\n );\n\n if (standard.jsonSchema) {\n const { json, lenient } = nativeJsonSchema(\n standard.jsonSchema,\n standard.vendor,\n io,\n );\n\n assertDescribesArguments(json, io);\n\n return lenient ? advertising(standard, json) : { \"~standard\": standard };\n }\n\n const json = await convert(schema as StandardSchemaV1, io);\n\n assertDescribesArguments(json, io);\n\n return advertising(standard, io === \"input\" ? strictInputSchema(json) : json);\n};\n\n/**\n * JSON Schema for a Valibot schema, for advertising.\n *\n * Valibot's converter is called directly so it can be told to skip what JSON\n * Schema cannot express — a transform, a `check()` — rather than refuse the\n * whole schema. Valibot still validates, so the copy only has to describe what\n * a caller sends (`typeMode: \"input\"`, which stops at the first transform) or\n * receives (`\"output\"`).\n *\n * The `import()` has to stay inside the `try`. An edge bundle is built with\n * every import resolved ahead of time, and a bundler fails the build over one\n * it cannot resolve — unless it can see the failure is handled, in which case\n * a server that never touches Valibot builds without the converter installed.\n */\nexport const valibotToJsonSchema: JsonSchemaConverter = async (schema, io) => {\n let converter;\n\n try {\n converter = await import(\"@valibot/to-json-schema\");\n } catch {\n throw new Error(\n 'The \"@valibot/to-json-schema\" package is required to describe Valibot ' +\n \"schemas. Install it with: npm install @valibot/to-json-schema\",\n );\n }\n\n return converter.toJsonSchema(schema as never, {\n errorMode: \"ignore\",\n typeMode: io,\n }) as JsonSchema;\n};\n\n/** `standard`, carrying `advertised` as its JSON Schema, input and output. */\nconst advertising = <P extends StandardSchemaV1.Props>(\n standard: P,\n advertised: JsonSchema,\n) => ({\n \"~standard\": {\n ...standard,\n jsonSchema: { input: () => advertised, output: () => advertised },\n },\n});\n\n/**\n * Refuses an input schema that describes anything but an object. A tool's\n * arguments are always one, and the SDK will not list a schema that says\n * otherwise: `parameters: z.string()` failed `tools/list` for every tool, as an\n * unconvertible schema did.\n */\nconst assertDescribesArguments = (\n json: JsonSchema,\n io: \"input\" | \"output\",\n): void => {\n if (io === \"input\" && json.type !== undefined && json.type !== \"object\") {\n throw new Error(\n `A tool's arguments are an object, and this schema describes ${JSON.stringify(\n json.type,\n )}. Wrap it in an object schema.`,\n );\n }\n};\n\n/**\n * A schema's own JSON Schema, and whether it had to be asked for leniently.\n * Throws what the library does when it refuses the schema either way.\n */\nconst nativeJsonSchema = (\n native: NativeJsonSchema,\n vendor: string,\n io: \"input\" | \"output\",\n): { json: JsonSchema; lenient: boolean } => {\n try {\n return { json: native[io]({ target: SDK_TARGET }), lenient: false };\n } catch (error) {\n const libraryOptions = LENIENT_OPTIONS.get(vendor);\n\n if (!libraryOptions) {\n throw error;\n }\n\n return {\n json: native[io]({ libraryOptions, target: SDK_TARGET }),\n lenient: true,\n };\n }\n};\n\n/**\n * Closes an advertised input schema's objects to undeclared keys, except where\n * the schema describes those keys itself. A record's value schema, or an\n * object's rest schema, arrives as `additionalProperties`; replacing it with\n * `false` would tell clients the tool takes none of those keys, so a\n * `v.record()` argument could only ever be sent as `{}`.\n *\n * Nor is an object closed whose keys are declared elsewhere: in its `allOf`,\n * `anyOf` or `oneOf` branches — a `v.intersect()`, `v.union()` or\n * `v.variant()` — or behind a `$ref`, which is how a `v.lazy()` arrives.\n * `additionalProperties` sees only the `properties` beside it, so closing one\n * refused every key declared elsewhere, and every argument with them.\n */\nconst strictInputSchema = (schema: JsonSchema): JsonSchema => ({\n ...schema,\n ...(!(schema.allOf ?? schema.anyOf ?? schema.oneOf ?? schema.$ref) && {\n additionalProperties:\n typeof schema.additionalProperties === \"object\"\n ? schema.additionalProperties\n : false,\n }),\n ...(schema.properties && {\n properties: Object.fromEntries(\n Object.entries(schema.properties).map(([key, value]) => [\n key,\n typeof value === \"object\" && value.type === \"object\"\n ? strictInputSchema(value)\n : value,\n ]),\n ),\n }),\n});\n"]}
|
package/dist/edge/index.cjs
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
|
|
7
|
+
var _chunkNZGRSB2Dcjs = require('../chunk-NZGRSB2D.cjs');
|
|
7
8
|
|
|
8
9
|
// src/edge/index.ts
|
|
9
10
|
var _server = require('@modelcontextprotocol/server');
|
|
@@ -16,7 +17,7 @@ var convertToJsonSchema = async (schema, io) => {
|
|
|
16
17
|
`Schema library "${vendor}" carries no JSON Schema (\`~standard.jsonSchema\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`
|
|
17
18
|
);
|
|
18
19
|
}
|
|
19
|
-
return
|
|
20
|
+
return _chunkNZGRSB2Dcjs.valibotToJsonSchema.call(void 0, schema, io);
|
|
20
21
|
};
|
|
21
22
|
var readCappedRequest = async (request, maxBytes) => {
|
|
22
23
|
if (!request.body) {
|
|
@@ -60,10 +61,12 @@ var invalidRequest = (description) => Response.json(
|
|
|
60
61
|
{ status: 400 }
|
|
61
62
|
);
|
|
62
63
|
var EdgeViteMCP = class {
|
|
64
|
+
#description;
|
|
63
65
|
#handler = null;
|
|
64
66
|
#honoApp = new (0, _hono.Hono)();
|
|
65
67
|
#logger;
|
|
66
68
|
#maxBodySize;
|
|
69
|
+
#maxToolInputElements;
|
|
67
70
|
#mcpPath;
|
|
68
71
|
#name;
|
|
69
72
|
#prompts = [];
|
|
@@ -73,10 +76,14 @@ var EdgeViteMCP = class {
|
|
|
73
76
|
#toolSchemas = /* @__PURE__ */ new WeakMap();
|
|
74
77
|
#version;
|
|
75
78
|
constructor(options) {
|
|
79
|
+
this.#description = options.description;
|
|
76
80
|
this.#name = options.name;
|
|
77
81
|
this.#version = options.version;
|
|
78
82
|
this.#logger = _nullishCoalesce(options.logger, () => ( console));
|
|
79
83
|
this.#maxBodySize = _nullishCoalesce(options.maxBodySize, () => ( DEFAULT_MAX_BODY_SIZE));
|
|
84
|
+
this.#maxToolInputElements = _chunkNZGRSB2Dcjs.resolveMaxToolInputElements.call(void 0,
|
|
85
|
+
options.maxToolInputElements
|
|
86
|
+
);
|
|
80
87
|
this.#mcpPath = _nullishCoalesce(options.mcpPath, () => ( "/mcp"));
|
|
81
88
|
}
|
|
82
89
|
// As on `ViteMCP`, an entry added under a key already in use replaces the
|
|
@@ -114,10 +121,12 @@ var EdgeViteMCP = class {
|
|
|
114
121
|
}
|
|
115
122
|
if (!capped) {
|
|
116
123
|
return invalidRequest(
|
|
117
|
-
`Request body exceeds ${
|
|
124
|
+
`Request body exceeds ${_chunkNZGRSB2Dcjs.formatBytes.call(void 0, this.#maxBodySize)}`
|
|
118
125
|
);
|
|
119
126
|
}
|
|
120
|
-
this.#handler ??= _server.createMcpHandler.call(void 0, () => this.#buildServer()
|
|
127
|
+
this.#handler ??= _server.createMcpHandler.call(void 0, () => this.#buildServer(), {
|
|
128
|
+
maxRequestBodySize: this.#maxBodySize
|
|
129
|
+
});
|
|
121
130
|
return this.#handler.fetch(capped);
|
|
122
131
|
}
|
|
123
132
|
return this.#honoApp.fetch(request);
|
|
@@ -127,10 +136,14 @@ var EdgeViteMCP = class {
|
|
|
127
136
|
return this.#honoApp;
|
|
128
137
|
}
|
|
129
138
|
async #buildServer() {
|
|
130
|
-
const server = new (0, _server.McpServer)(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
139
|
+
const server = new (0, _server.McpServer)(
|
|
140
|
+
{
|
|
141
|
+
description: this.#description,
|
|
142
|
+
name: this.#name,
|
|
143
|
+
version: this.#version
|
|
144
|
+
},
|
|
145
|
+
{ maxToolInputElements: this.#maxToolInputElements }
|
|
146
|
+
);
|
|
134
147
|
const tools = (await Promise.all(
|
|
135
148
|
this.#tools.map(async (tool) => {
|
|
136
149
|
const schema = await this.#sdkSchemaFor(tool);
|
|
@@ -179,7 +192,7 @@ var EdgeViteMCP = class {
|
|
|
179
192
|
for (const arg of _nullishCoalesce(prompt.arguments, () => ( []))) {
|
|
180
193
|
shape[arg.name] = arg.required ? _zod.z.string() : _zod.z.string().optional();
|
|
181
194
|
}
|
|
182
|
-
const argsSchema = _optionalChain([prompt, 'access', _ => _.arguments, 'optionalAccess', _2 => _2.length]) ?
|
|
195
|
+
const argsSchema = _optionalChain([prompt, 'access', _ => _.arguments, 'optionalAccess', _2 => _2.length]) ? _chunkNZGRSB2Dcjs.ownKeysOnly.call(void 0, _zod.z.object(shape)) : void 0;
|
|
183
196
|
const load = async (args) => {
|
|
184
197
|
const text = await prompt.load(_nullishCoalesce(args, () => ( {})));
|
|
185
198
|
return {
|
|
@@ -209,7 +222,7 @@ var EdgeViteMCP = class {
|
|
|
209
222
|
#sdkSchemaFor(tool) {
|
|
210
223
|
let schema = this.#toolSchemas.get(tool);
|
|
211
224
|
if (!schema) {
|
|
212
|
-
schema =
|
|
225
|
+
schema = _chunkNZGRSB2Dcjs.toSdkSchema.call(void 0, tool.parameters, "input", convertToJsonSchema).then(
|
|
213
226
|
(inputSchema) => ({ inputSchema }),
|
|
214
227
|
(error) => {
|
|
215
228
|
this.#logger.error(
|
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,M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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 // 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"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/server/server/dist/edge/index.cjs","../../src/edge/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACFA,sDAA4C;AAE5C,4BAAqB;AACrB,0BAAkB;AAyGlB,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;AAC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d,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;ADlLA;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 { resolveMaxToolInputElements } from \"../toolInputLimit.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 /**\n * What this server is, for a human reading a client's server list.\n * Advertised in `serverInfo`, as `ViteMCP` advertises its own.\n */\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 * Most array elements and object members, counted together, that one\n * `tools/call` may carry in its arguments (default: 10,000, as on\n * `ViteMCP`). A call over it gets an error result before any schema sees\n * it. Pass `Infinity` to lift the limit.\n */\n maxToolInputElements?: 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 #description: string | undefined;\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #maxToolInputElements: 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.#description = options.description;\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.#maxToolInputElements = resolveMaxToolInputElements(\n options.maxToolInputElements,\n );\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 // The SDK reads the body again, under a cap of its own: 4 MiB unless\n // told otherwise, which refused bodies a larger `maxBodySize` admits.\n this.#handler ??= createMcpHandler(() => this.#buildServer(), {\n maxRequestBodySize: this.#maxBodySize,\n });\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 // `description` was accepted and then left out here, so a server that set\n // it — as the README's Workers example does — advertised none.\n const server = new McpServer(\n {\n description: this.#description,\n name: this.#name,\n version: this.#version,\n },\n { maxToolInputElements: this.#maxToolInputElements },\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.d.cts
CHANGED
|
@@ -60,6 +60,10 @@ interface EdgeTool<TParams = unknown> {
|
|
|
60
60
|
* Options for EdgeViteMCP
|
|
61
61
|
*/
|
|
62
62
|
interface EdgeViteMCPOptions {
|
|
63
|
+
/**
|
|
64
|
+
* What this server is, for a human reading a client's server list.
|
|
65
|
+
* Advertised in `serverInfo`, as `ViteMCP` advertises its own.
|
|
66
|
+
*/
|
|
63
67
|
description?: string;
|
|
64
68
|
logger?: EdgeLogger;
|
|
65
69
|
/**
|
|
@@ -68,6 +72,13 @@ interface EdgeViteMCPOptions {
|
|
|
68
72
|
* memory. Routes added through `getApp()` are not covered.
|
|
69
73
|
*/
|
|
70
74
|
maxBodySize?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Most array elements and object members, counted together, that one
|
|
77
|
+
* `tools/call` may carry in its arguments (default: 10,000, as on
|
|
78
|
+
* `ViteMCP`). A call over it gets an error result before any schema sees
|
|
79
|
+
* it. Pass `Infinity` to lift the limit.
|
|
80
|
+
*/
|
|
81
|
+
maxToolInputElements?: number;
|
|
71
82
|
/**
|
|
72
83
|
* Base path for MCP endpoints (default: "/mcp")
|
|
73
84
|
*/
|
package/dist/edge/index.d.ts
CHANGED
|
@@ -60,6 +60,10 @@ interface EdgeTool<TParams = unknown> {
|
|
|
60
60
|
* Options for EdgeViteMCP
|
|
61
61
|
*/
|
|
62
62
|
interface EdgeViteMCPOptions {
|
|
63
|
+
/**
|
|
64
|
+
* What this server is, for a human reading a client's server list.
|
|
65
|
+
* Advertised in `serverInfo`, as `ViteMCP` advertises its own.
|
|
66
|
+
*/
|
|
63
67
|
description?: string;
|
|
64
68
|
logger?: EdgeLogger;
|
|
65
69
|
/**
|
|
@@ -68,6 +72,13 @@ interface EdgeViteMCPOptions {
|
|
|
68
72
|
* memory. Routes added through `getApp()` are not covered.
|
|
69
73
|
*/
|
|
70
74
|
maxBodySize?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Most array elements and object members, counted together, that one
|
|
77
|
+
* `tools/call` may carry in its arguments (default: 10,000, as on
|
|
78
|
+
* `ViteMCP`). A call over it gets an error result before any schema sees
|
|
79
|
+
* it. Pass `Infinity` to lift the limit.
|
|
80
|
+
*/
|
|
81
|
+
maxToolInputElements?: number;
|
|
71
82
|
/**
|
|
72
83
|
* Base path for MCP endpoints (default: "/mcp")
|
|
73
84
|
*/
|
package/dist/edge/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
formatBytes,
|
|
3
3
|
ownKeysOnly,
|
|
4
|
+
resolveMaxToolInputElements,
|
|
4
5
|
toSdkSchema,
|
|
5
6
|
valibotToJsonSchema
|
|
6
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-BLXUZUZ4.js";
|
|
7
8
|
|
|
8
9
|
// src/edge/index.ts
|
|
9
10
|
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
|
|
@@ -60,10 +61,12 @@ var invalidRequest = (description) => Response.json(
|
|
|
60
61
|
{ status: 400 }
|
|
61
62
|
);
|
|
62
63
|
var EdgeViteMCP = class {
|
|
64
|
+
#description;
|
|
63
65
|
#handler = null;
|
|
64
66
|
#honoApp = new Hono();
|
|
65
67
|
#logger;
|
|
66
68
|
#maxBodySize;
|
|
69
|
+
#maxToolInputElements;
|
|
67
70
|
#mcpPath;
|
|
68
71
|
#name;
|
|
69
72
|
#prompts = [];
|
|
@@ -73,10 +76,14 @@ var EdgeViteMCP = class {
|
|
|
73
76
|
#toolSchemas = /* @__PURE__ */ new WeakMap();
|
|
74
77
|
#version;
|
|
75
78
|
constructor(options) {
|
|
79
|
+
this.#description = options.description;
|
|
76
80
|
this.#name = options.name;
|
|
77
81
|
this.#version = options.version;
|
|
78
82
|
this.#logger = options.logger ?? console;
|
|
79
83
|
this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
|
|
84
|
+
this.#maxToolInputElements = resolveMaxToolInputElements(
|
|
85
|
+
options.maxToolInputElements
|
|
86
|
+
);
|
|
80
87
|
this.#mcpPath = options.mcpPath ?? "/mcp";
|
|
81
88
|
}
|
|
82
89
|
// As on `ViteMCP`, an entry added under a key already in use replaces the
|
|
@@ -117,7 +124,9 @@ var EdgeViteMCP = class {
|
|
|
117
124
|
`Request body exceeds ${formatBytes(this.#maxBodySize)}`
|
|
118
125
|
);
|
|
119
126
|
}
|
|
120
|
-
this.#handler ??= createMcpHandler(() => this.#buildServer()
|
|
127
|
+
this.#handler ??= createMcpHandler(() => this.#buildServer(), {
|
|
128
|
+
maxRequestBodySize: this.#maxBodySize
|
|
129
|
+
});
|
|
121
130
|
return this.#handler.fetch(capped);
|
|
122
131
|
}
|
|
123
132
|
return this.#honoApp.fetch(request);
|
|
@@ -127,10 +136,14 @@ var EdgeViteMCP = class {
|
|
|
127
136
|
return this.#honoApp;
|
|
128
137
|
}
|
|
129
138
|
async #buildServer() {
|
|
130
|
-
const server = new McpServer(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
139
|
+
const server = new McpServer(
|
|
140
|
+
{
|
|
141
|
+
description: this.#description,
|
|
142
|
+
name: this.#name,
|
|
143
|
+
version: this.#version
|
|
144
|
+
},
|
|
145
|
+
{ maxToolInputElements: this.#maxToolInputElements }
|
|
146
|
+
);
|
|
134
147
|
const tools = (await Promise.all(
|
|
135
148
|
this.#tools.map(async (tool) => {
|
|
136
149
|
const schema = await this.#sdkSchemaFor(tool);
|
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 // 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,IA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AM,IAAI,IAAI,IAAI,IAAI,WAAW,EAAE,OAAO,IAAI,EAAE,OAAO,EAAE,SAAS;AAAA,MACpE;AAEA,YAAM,aAAa,OAAO,WAAW,SACjC,YAAY,EAAE,OAAO,KAAK,CAAC,IAC3B;AAEJ,YAAM,OAAO,OAAO,SAAkC;AACpD,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 { resolveMaxToolInputElements } from \"../toolInputLimit.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 /**\n * What this server is, for a human reading a client's server list.\n * Advertised in `serverInfo`, as `ViteMCP` advertises its own.\n */\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 * Most array elements and object members, counted together, that one\n * `tools/call` may carry in its arguments (default: 10,000, as on\n * `ViteMCP`). A call over it gets an error result before any schema sees\n * it. Pass `Infinity` to lift the limit.\n */\n maxToolInputElements?: 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 #description: string | undefined;\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #maxBodySize: number;\n #maxToolInputElements: 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.#description = options.description;\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.#maxToolInputElements = resolveMaxToolInputElements(\n options.maxToolInputElements,\n );\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 // The SDK reads the body again, under a cap of its own: 4 MiB unless\n // told otherwise, which refused bodies a larger `maxBodySize` admits.\n this.#handler ??= createMcpHandler(() => this.#buildServer(), {\n maxRequestBodySize: this.#maxBodySize,\n });\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 // `description` was accepted and then left out here, so a server that set\n // it — as the README's Workers example does — advertised none.\n const server = new McpServer(\n {\n description: this.#description,\n name: this.#name,\n version: this.#version,\n },\n { maxToolInputElements: this.#maxToolInputElements },\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;AAyGlB,IAAM,sBAA2C,OAAO,QAAQ,OAAO;AACrE,QAAM,EAAE,OAAO,IAAI,OAAO,WAA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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,9 +3,9 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
7
|
-
require('../chunk-
|
|
8
|
-
require('../chunk-
|
|
6
|
+
var _chunkFSPSPB7Ycjs = require('../chunk-FSPSPB7Y.cjs');
|
|
7
|
+
require('../chunk-4LU4AXU4.cjs');
|
|
8
|
+
require('../chunk-NZGRSB2D.cjs');
|
|
9
9
|
|
|
10
10
|
// src/openapi/parameters.ts
|
|
11
11
|
var appendQueryParameter = (query, parameter, given) => {
|
|
@@ -287,7 +287,7 @@ var buildBody = (binding, values, headers) => {
|
|
|
287
287
|
var buildPath = (route, values) => {
|
|
288
288
|
const unfilled = [...route.path.matchAll(/\{([^{}]*)\}/g)].filter(([, name]) => !values.has(name)).map(([placeholder]) => placeholder);
|
|
289
289
|
if (unfilled.length > 0) {
|
|
290
|
-
throw new (0,
|
|
290
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
291
291
|
`${route.method.toUpperCase()} ${route.path} cannot be called: the OpenAPI document declares no path parameter for ${unfilled.join(", ")}.`
|
|
292
292
|
);
|
|
293
293
|
}
|
|
@@ -298,7 +298,7 @@ var buildPath = (route, values) => {
|
|
|
298
298
|
const written = new Set(route.path.split("/").filter(isDotSegment));
|
|
299
299
|
const introduced = path.split("/").find((segment) => isDotSegment(segment) && !written.has(segment));
|
|
300
300
|
if (introduced !== void 0) {
|
|
301
|
-
throw new (0,
|
|
301
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
302
302
|
`${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.`
|
|
303
303
|
);
|
|
304
304
|
}
|
|
@@ -316,7 +316,7 @@ var readResponse = async (response, options) => {
|
|
|
316
316
|
const mediaType = contentType.split(";")[0].trim().toLowerCase();
|
|
317
317
|
const label = `${route.method.toUpperCase()} ${route.path}`;
|
|
318
318
|
if (!response.ok) {
|
|
319
|
-
throw new (0,
|
|
319
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
320
320
|
`${label} failed with ${response.status} ${response.statusText}: ${truncate(
|
|
321
321
|
await response.text(),
|
|
322
322
|
2e3
|
|
@@ -328,7 +328,7 @@ var readResponse = async (response, options) => {
|
|
|
328
328
|
if (bytes.byteLength <= MAX_INLINE_MEDIA_BYTES) {
|
|
329
329
|
return mediaType.startsWith("image/") ? { data: toBase64(bytes), mimeType: mediaType, type: "image" } : { data: toBase64(bytes), mimeType: mediaType, type: "audio" };
|
|
330
330
|
}
|
|
331
|
-
throw new (0,
|
|
331
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
332
332
|
`${label} returned ${bytes.byteLength} bytes of ${contentType}, too large to return inline.`
|
|
333
333
|
);
|
|
334
334
|
}
|
|
@@ -338,7 +338,7 @@ var readResponse = async (response, options) => {
|
|
|
338
338
|
return { structuredContent: parsed };
|
|
339
339
|
}
|
|
340
340
|
if (binding.outputSchema) {
|
|
341
|
-
throw new (0,
|
|
341
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
342
342
|
`${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.`
|
|
343
343
|
);
|
|
344
344
|
}
|
|
@@ -360,7 +360,7 @@ var setHeader = (headers, name, value) => {
|
|
|
360
360
|
try {
|
|
361
361
|
headers.set(name, value);
|
|
362
362
|
} catch (e2) {
|
|
363
|
-
throw new (0,
|
|
363
|
+
throw new (0, _chunkFSPSPB7Ycjs.UserError)(
|
|
364
364
|
`"${name}" is not a valid header name, or the value given for it is not a valid header value.`
|
|
365
365
|
);
|
|
366
366
|
}
|
|
@@ -467,7 +467,7 @@ var readSpecText = async (spec) => {
|
|
|
467
467
|
headers: { accept: "application/json, text/yaml, */*" }
|
|
468
468
|
});
|
|
469
469
|
if (!response.ok) {
|
|
470
|
-
await
|
|
470
|
+
await _chunkFSPSPB7Ycjs.cancelResponseBody.call(void 0, response);
|
|
471
471
|
throw new Error(
|
|
472
472
|
`Failed to fetch the OpenAPI document from ${spec}: ${response.status} ${response.statusText}`
|
|
473
473
|
);
|
|
@@ -995,46 +995,46 @@ var describeParameter = (parameter, normalizer) => {
|
|
|
995
995
|
return description ? { ...schema, description } : schema;
|
|
996
996
|
};
|
|
997
997
|
var flattenObject = (schema, definitions, depth = 0) => {
|
|
998
|
-
if (!schema || depth > 8) {
|
|
998
|
+
if (!schema || depth > 8 || isNonEmptyArray(schema.anyOf) || isNonEmptyArray(schema.oneOf)) {
|
|
999
999
|
return void 0;
|
|
1000
1000
|
}
|
|
1001
|
+
const parts = [];
|
|
1001
1002
|
if (typeof schema.$ref === "string" && schema.$ref.startsWith("#/$defs/")) {
|
|
1002
|
-
|
|
1003
|
-
|
|
1003
|
+
parts.push(definitions[schema.$ref.slice("#/$defs/".length)]);
|
|
1004
|
+
}
|
|
1005
|
+
if (isNonEmptyArray(schema.allOf)) {
|
|
1006
|
+
parts.push(...schema.allOf);
|
|
1007
|
+
}
|
|
1008
|
+
const own = isPropertyMap(schema.properties) ? schema.properties : void 0;
|
|
1009
|
+
if (parts.length === 0 && !own) {
|
|
1010
|
+
return void 0;
|
|
1011
|
+
}
|
|
1012
|
+
const properties = /* @__PURE__ */ Object.create(null);
|
|
1013
|
+
const required = /* @__PURE__ */ new Set();
|
|
1014
|
+
for (const part of parts) {
|
|
1015
|
+
const flattened = flattenObject(
|
|
1016
|
+
part,
|
|
1004
1017
|
definitions,
|
|
1005
1018
|
depth + 1
|
|
1006
1019
|
);
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
for (const
|
|
1012
|
-
|
|
1013
|
-
branch,
|
|
1014
|
-
definitions,
|
|
1015
|
-
depth + 1
|
|
1016
|
-
);
|
|
1017
|
-
if (!part) {
|
|
1018
|
-
return void 0;
|
|
1019
|
-
}
|
|
1020
|
-
Object.assign(properties2, part.properties);
|
|
1021
|
-
for (const name of part.required) {
|
|
1022
|
-
required.add(name);
|
|
1023
|
-
}
|
|
1020
|
+
if (!flattened) {
|
|
1021
|
+
return void 0;
|
|
1022
|
+
}
|
|
1023
|
+
Object.assign(properties, flattened.properties);
|
|
1024
|
+
for (const name of flattened.required) {
|
|
1025
|
+
required.add(name);
|
|
1024
1026
|
}
|
|
1025
|
-
return { properties: properties2, required };
|
|
1026
1027
|
}
|
|
1027
|
-
|
|
1028
|
-
if (
|
|
1029
|
-
|
|
1028
|
+
Object.assign(properties, own);
|
|
1029
|
+
if (Array.isArray(schema.required)) {
|
|
1030
|
+
for (const name of schema.required) {
|
|
1031
|
+
required.add(name);
|
|
1032
|
+
}
|
|
1030
1033
|
}
|
|
1031
|
-
return {
|
|
1032
|
-
properties,
|
|
1033
|
-
required: new Set(
|
|
1034
|
-
Array.isArray(schema.required) ? schema.required : []
|
|
1035
|
-
)
|
|
1036
|
-
};
|
|
1034
|
+
return { properties, required };
|
|
1037
1035
|
};
|
|
1036
|
+
var isNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
|
|
1037
|
+
var isPropertyMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1038
1038
|
var encodingKindFor = (contentType) => {
|
|
1039
1039
|
if (contentType === "application/x-www-form-urlencoded") {
|
|
1040
1040
|
return "form";
|
|
@@ -1106,7 +1106,7 @@ var fromOpenAPI = async (options) => {
|
|
|
1106
1106
|
const selected = selectRoutes(extractRoutes(document), options);
|
|
1107
1107
|
const names = generateToolNames(selected, options.toolNames);
|
|
1108
1108
|
const normalizer = createSchemaNormalizer(document);
|
|
1109
|
-
const server = _nullishCoalesce(options.server, () => ( new (0,
|
|
1109
|
+
const server = _nullishCoalesce(options.server, () => ( new (0, _chunkFSPSPB7Ycjs.ViteMCP)({
|
|
1110
1110
|
description: _optionalChain([document, 'access', _25 => _25.info, 'optionalAccess', _26 => _26.description]),
|
|
1111
1111
|
name: _nullishCoalesce(_nullishCoalesce(options.name, () => ( _optionalChain([document, 'access', _27 => _27.info, 'optionalAccess', _28 => _28.title]))), () => ( "OpenAPI")),
|
|
1112
1112
|
version: _nullishCoalesce(options.version, () => ( semanticVersion(_optionalChain([document, 'access', _29 => _29.info, 'optionalAccess', _30 => _30.version]))))
|
|
@@ -1145,8 +1145,8 @@ var fromOpenAPI = async (options) => {
|
|
|
1145
1145
|
route
|
|
1146
1146
|
}),
|
|
1147
1147
|
name,
|
|
1148
|
-
outputSchema: binding.outputSchema ?
|
|
1149
|
-
parameters:
|
|
1148
|
+
outputSchema: binding.outputSchema ? _chunkFSPSPB7Ycjs.jsonSchemaAdapter.call(void 0, binding.outputSchema) : void 0,
|
|
1149
|
+
parameters: _chunkFSPSPB7Ycjs.jsonSchemaAdapter.call(void 0, binding.inputSchema),
|
|
1150
1150
|
timeoutMs: options.timeoutMs
|
|
1151
1151
|
});
|
|
1152
1152
|
}
|