@vitemcp/server 1.9.0 → 1.9.2
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 +7 -2
- package/dist/{OAuthProvider-DvW1SyKx.d.cts → OAuthProvider-BaPwgWny.d.cts} +12 -2
- package/dist/{OAuthProvider-DvW1SyKx.d.ts → OAuthProvider-BaPwgWny.d.ts} +12 -2
- package/dist/ViteMCP.cjs +4 -3
- package/dist/ViteMCP.cjs.map +1 -1
- package/dist/ViteMCP.d.cts +2 -2
- package/dist/ViteMCP.d.ts +2 -2
- package/dist/ViteMCP.js +3 -2
- package/dist/auth/index.cjs +2 -2
- package/dist/auth/index.d.cts +2 -2
- package/dist/auth/index.d.ts +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/chunk-4FH73ERY.js +64 -0
- package/dist/chunk-4FH73ERY.js.map +1 -0
- package/dist/{chunk-UFLW3ODH.js → chunk-DSDLJS6O.js} +107 -130
- package/dist/chunk-DSDLJS6O.js.map +1 -0
- package/dist/chunk-FEM6LNS4.cjs +64 -0
- package/dist/chunk-FEM6LNS4.cjs.map +1 -0
- package/dist/{chunk-HWSTK2ZH.js → chunk-KKSDTVEW.js} +79 -18
- package/dist/chunk-KKSDTVEW.js.map +1 -0
- package/dist/{chunk-UPZH53RX.cjs → chunk-RQEMPJ2L.cjs} +109 -132
- package/dist/chunk-RQEMPJ2L.cjs.map +1 -0
- package/dist/{chunk-KFOTRFZS.cjs → chunk-SHPKRGNY.cjs} +93 -32
- package/dist/chunk-SHPKRGNY.cjs.map +1 -0
- package/dist/edge/index.cjs +128 -21
- package/dist/edge/index.cjs.map +1 -1
- package/dist/edge/index.d.cts +6 -0
- package/dist/edge/index.d.ts +6 -0
- package/dist/edge/index.js +127 -20
- package/dist/edge/index.js.map +1 -1
- package/dist/openapi/index.cjs +69 -29
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.d.cts +1 -1
- package/dist/openapi/index.d.ts +1 -1
- package/dist/openapi/index.js +61 -21
- package/dist/openapi/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-HWSTK2ZH.js.map +0 -1
- package/dist/chunk-KFOTRFZS.cjs.map +0 -1
- package/dist/chunk-UFLW3ODH.js.map +0 -1
- package/dist/chunk-UPZH53RX.cjs.map +0 -1
package/dist/edge/index.cjs
CHANGED
|
@@ -1,21 +1,81 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunkFEM6LNS4cjs = require('../chunk-FEM6LNS4.cjs');
|
|
6
|
+
|
|
7
|
+
// src/edge/index.ts
|
|
2
8
|
var _server = require('@modelcontextprotocol/server');
|
|
3
9
|
var _hono = require('hono');
|
|
4
10
|
var _zod = require('zod');
|
|
11
|
+
var convertToJsonSchema = async (schema, io) => {
|
|
12
|
+
const { vendor } = schema["~standard"];
|
|
13
|
+
if (vendor !== "valibot") {
|
|
14
|
+
throw new Error(
|
|
15
|
+
`Schema library "${vendor}" carries no JSON Schema (\`~standard.jsonSchema\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
return _chunkFEM6LNS4cjs.valibotToJsonSchema.call(void 0, schema, io);
|
|
19
|
+
};
|
|
20
|
+
var readCappedRequest = async (request, maxBytes) => {
|
|
21
|
+
if (!request.body) {
|
|
22
|
+
return request;
|
|
23
|
+
}
|
|
24
|
+
if (Number(_nullishCoalesce(request.headers.get("content-length"), () => ( 0))) > maxBytes) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
const reader = request.body.getReader();
|
|
28
|
+
const chunks = [];
|
|
29
|
+
let size = 0;
|
|
30
|
+
for (; ; ) {
|
|
31
|
+
const { done, value } = await reader.read();
|
|
32
|
+
if (done) {
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
size += value.byteLength;
|
|
36
|
+
if (size > maxBytes) {
|
|
37
|
+
await reader.cancel().catch(() => {
|
|
38
|
+
});
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
chunks.push(value);
|
|
42
|
+
}
|
|
43
|
+
const body = new Uint8Array(size);
|
|
44
|
+
let offset = 0;
|
|
45
|
+
for (const chunk of chunks) {
|
|
46
|
+
body.set(chunk, offset);
|
|
47
|
+
offset += chunk.byteLength;
|
|
48
|
+
}
|
|
49
|
+
return new Request(request.url, {
|
|
50
|
+
body,
|
|
51
|
+
headers: request.headers,
|
|
52
|
+
method: request.method,
|
|
53
|
+
signal: request.signal
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
var DEFAULT_MAX_BODY_SIZE = 1024 * 1024;
|
|
57
|
+
var invalidRequest = (description) => Response.json(
|
|
58
|
+
{ error: "invalid_request", error_description: description },
|
|
59
|
+
{ status: 400 }
|
|
60
|
+
);
|
|
5
61
|
var EdgeViteMCP = class {
|
|
6
62
|
#handler = null;
|
|
7
63
|
#honoApp = new (0, _hono.Hono)();
|
|
8
64
|
#logger;
|
|
65
|
+
#maxBodySize;
|
|
9
66
|
#mcpPath;
|
|
10
67
|
#name;
|
|
11
68
|
#prompts = [];
|
|
12
69
|
#resources = [];
|
|
13
70
|
#tools = [];
|
|
71
|
+
/** Each tool's input schema, as `#sdkSchemaFor` converted it. */
|
|
72
|
+
#toolSchemas = /* @__PURE__ */ new WeakMap();
|
|
14
73
|
#version;
|
|
15
74
|
constructor(options) {
|
|
16
75
|
this.#name = options.name;
|
|
17
76
|
this.#version = options.version;
|
|
18
77
|
this.#logger = _nullishCoalesce(options.logger, () => ( console));
|
|
78
|
+
this.#maxBodySize = _nullishCoalesce(options.maxBodySize, () => ( DEFAULT_MAX_BODY_SIZE));
|
|
19
79
|
this.#mcpPath = _nullishCoalesce(options.mcpPath, () => ( "/mcp"));
|
|
20
80
|
}
|
|
21
81
|
addPrompt(prompt) {
|
|
@@ -37,8 +97,20 @@ var EdgeViteMCP = class {
|
|
|
37
97
|
async fetch(request) {
|
|
38
98
|
const url = new URL(request.url);
|
|
39
99
|
if (url.pathname === this.#mcpPath) {
|
|
100
|
+
let capped;
|
|
101
|
+
try {
|
|
102
|
+
capped = await readCappedRequest(request, this.#maxBodySize);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);
|
|
105
|
+
return invalidRequest("Request body could not be read");
|
|
106
|
+
}
|
|
107
|
+
if (!capped) {
|
|
108
|
+
return invalidRequest(
|
|
109
|
+
`Request body exceeds ${_chunkFEM6LNS4cjs.formatBytes.call(void 0, this.#maxBodySize)}`
|
|
110
|
+
);
|
|
111
|
+
}
|
|
40
112
|
this.#handler ??= _server.createMcpHandler.call(void 0, () => this.#buildServer());
|
|
41
|
-
return this.#handler.fetch(
|
|
113
|
+
return this.#handler.fetch(capped);
|
|
42
114
|
}
|
|
43
115
|
return this.#honoApp.fetch(request);
|
|
44
116
|
}
|
|
@@ -46,22 +118,32 @@ var EdgeViteMCP = class {
|
|
|
46
118
|
getApp() {
|
|
47
119
|
return this.#honoApp;
|
|
48
120
|
}
|
|
49
|
-
#buildServer() {
|
|
121
|
+
async #buildServer() {
|
|
50
122
|
const server = new (0, _server.McpServer)({
|
|
51
123
|
name: this.#name,
|
|
52
124
|
version: this.#version
|
|
53
125
|
});
|
|
54
|
-
|
|
126
|
+
const tools = (await Promise.all(
|
|
127
|
+
this.#tools.map(async (tool) => {
|
|
128
|
+
const schema = await this.#sdkSchemaFor(tool);
|
|
129
|
+
return schema && { schema, tool };
|
|
130
|
+
})
|
|
131
|
+
)).filter((entry) => entry !== void 0);
|
|
132
|
+
for (const { schema, tool } of tools) {
|
|
133
|
+
const call = async (args) => {
|
|
134
|
+
const result = await tool.execute(args);
|
|
135
|
+
return typeof result === "string" ? { content: [{ text: result, type: "text" }] } : result;
|
|
136
|
+
};
|
|
55
137
|
server.registerTool(
|
|
56
138
|
tool.name,
|
|
57
139
|
{
|
|
58
140
|
description: tool.description,
|
|
59
|
-
inputSchema:
|
|
141
|
+
inputSchema: schema.inputSchema
|
|
60
142
|
},
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
143
|
+
// The SDK passes arguments only to a tool that declares an input
|
|
144
|
+
// schema; one that does not is called with the request context alone,
|
|
145
|
+
// which must not reach `execute` as its parameters.
|
|
146
|
+
schema.inputSchema ? call : () => call(void 0)
|
|
65
147
|
);
|
|
66
148
|
}
|
|
67
149
|
for (const resource of this.#resources) {
|
|
@@ -89,25 +171,50 @@ var EdgeViteMCP = class {
|
|
|
89
171
|
for (const arg of _nullishCoalesce(prompt.arguments, () => ( []))) {
|
|
90
172
|
shape[arg.name] = arg.required ? _zod.z.string() : _zod.z.string().optional();
|
|
91
173
|
}
|
|
174
|
+
const argsSchema = _optionalChain([prompt, 'access', _ => _.arguments, 'optionalAccess', _2 => _2.length]) ? _zod.z.object(shape) : void 0;
|
|
175
|
+
const load = async (args) => {
|
|
176
|
+
const text = await prompt.load(_nullishCoalesce(args, () => ( {})));
|
|
177
|
+
return {
|
|
178
|
+
messages: [
|
|
179
|
+
{ content: { text, type: "text" }, role: "user" }
|
|
180
|
+
]
|
|
181
|
+
};
|
|
182
|
+
};
|
|
92
183
|
server.registerPrompt(
|
|
93
184
|
prompt.name,
|
|
94
|
-
{
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
(async (args) => {
|
|
99
|
-
const text = await prompt.load(_nullishCoalesce(args, () => ( {})));
|
|
100
|
-
return {
|
|
101
|
-
messages: [
|
|
102
|
-
{ content: { text, type: "text" }, role: "user" }
|
|
103
|
-
]
|
|
104
|
-
};
|
|
105
|
-
})
|
|
185
|
+
{ argsSchema, description: prompt.description },
|
|
186
|
+
// As for tools: without `argsSchema` the SDK passes the request
|
|
187
|
+
// context alone.
|
|
188
|
+
argsSchema ? load : () => load()
|
|
106
189
|
);
|
|
107
190
|
}
|
|
108
191
|
this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);
|
|
109
192
|
return server;
|
|
110
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* A tool's input schema in the form the SDK registers it, or `undefined` for
|
|
196
|
+
* a tool whose schema cannot be converted — reported when that is found.
|
|
197
|
+
*
|
|
198
|
+
* Converted once per tool: `#buildServer` runs on every request, so a tool
|
|
199
|
+
* that cannot be served would otherwise be reported on each of them.
|
|
200
|
+
*/
|
|
201
|
+
#sdkSchemaFor(tool) {
|
|
202
|
+
let schema = this.#toolSchemas.get(tool);
|
|
203
|
+
if (!schema) {
|
|
204
|
+
schema = _chunkFEM6LNS4cjs.toSdkSchema.call(void 0, tool.parameters, "input", convertToJsonSchema).then(
|
|
205
|
+
(inputSchema) => ({ inputSchema }),
|
|
206
|
+
(error) => {
|
|
207
|
+
this.#logger.error(
|
|
208
|
+
`[EdgeViteMCP] Tool "${tool.name}" is not served:`,
|
|
209
|
+
error
|
|
210
|
+
);
|
|
211
|
+
return void 0;
|
|
212
|
+
}
|
|
213
|
+
);
|
|
214
|
+
this.#toolSchemas.set(tool, schema);
|
|
215
|
+
}
|
|
216
|
+
return schema;
|
|
217
|
+
}
|
|
111
218
|
};
|
|
112
219
|
|
|
113
220
|
|
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;ACMA,sDAA4C;AAE5C,4BAAqB;AACrB,0BAAkB;AAwEX,IAAM,YAAA,EAAN,MAAkB;AAAA,EACvB,CAAA,QAAA,EAAuD,IAAA;AAAA,EACvD,CAAA,QAAA,EAAW,IAAI,eAAA,CAAK,CAAA;AAAA,EACpB,CAAA,MAAA;AAAA,EACA,CAAA,OAAA;AAAA,EACA,CAAA,IAAA;AAAA,EACA,CAAA,QAAA,EAAyB,CAAC,CAAA;AAAA,EAC1B,CAAA,UAAA,EAA6B,CAAC,CAAA;AAAA,EAC9B,CAAA,MAAA,EAAqB,CAAC,CAAA;AAAA,EACtB,CAAA,OAAA;AAAA,EAEA,WAAA,CAAY,OAAA,EAA6B;AACvC,IAAA,IAAA,CAAK,CAAA,KAAA,EAAQ,OAAA,CAAQ,IAAA;AACrB,IAAA,IAAA,CAAK,CAAA,QAAA,EAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,CAAA,OAAA,mBAAU,OAAA,CAAQ,MAAA,UAAU,SAAA;AACjC,IAAA,IAAA,CAAK,CAAA,QAAA,mBAAW,OAAA,CAAQ,OAAA,UAAW,QAAA;AAAA,EACrC;AAAA,EAEA,SAAA,CAAU,MAAA,EAA0B;AAClC,IAAA,IAAA,CAAK,CAAA,OAAA,CAAS,IAAA,CAAK,MAAM,CAAA;AACzB,IAAA,IAAA,CAAK,CAAA,QAAA,EAAW,IAAA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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\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 * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\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.#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 this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(request);\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 #buildServer(): McpServer {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n for (const tool of this.#tools) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.parameters as never,\n },\n (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 }) 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 server.registerPrompt(\n prompt.name,\n {\n argsSchema: prompt.arguments?.length ? z.object(shape) : undefined,\n description: prompt.description,\n } as never,\n (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 }) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\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;AACF,yDAA8B;AAC9B;AACA;ACAA,sDAA4C;AAE5C,4BAAqB;AACrB,0BAAkB;AA4FlB,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,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AO,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;AAEA,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;ADjKA;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 {\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 ? z.object(shape) : 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
|
@@ -62,6 +62,12 @@ interface EdgeTool<TParams = unknown> {
|
|
|
62
62
|
interface EdgeViteMCPOptions {
|
|
63
63
|
description?: string;
|
|
64
64
|
logger?: EdgeLogger;
|
|
65
|
+
/**
|
|
66
|
+
* Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,
|
|
67
|
+
* as on the Node transport). A larger one is refused without being held in
|
|
68
|
+
* memory. Routes added through `getApp()` are not covered.
|
|
69
|
+
*/
|
|
70
|
+
maxBodySize?: number;
|
|
65
71
|
/**
|
|
66
72
|
* Base path for MCP endpoints (default: "/mcp")
|
|
67
73
|
*/
|
package/dist/edge/index.d.ts
CHANGED
|
@@ -62,6 +62,12 @@ interface EdgeTool<TParams = unknown> {
|
|
|
62
62
|
interface EdgeViteMCPOptions {
|
|
63
63
|
description?: string;
|
|
64
64
|
logger?: EdgeLogger;
|
|
65
|
+
/**
|
|
66
|
+
* Largest request body the MCP endpoint accepts, in bytes (default: 1 MiB,
|
|
67
|
+
* as on the Node transport). A larger one is refused without being held in
|
|
68
|
+
* memory. Routes added through `getApp()` are not covered.
|
|
69
|
+
*/
|
|
70
|
+
maxBodySize?: number;
|
|
65
71
|
/**
|
|
66
72
|
* Base path for MCP endpoints (default: "/mcp")
|
|
67
73
|
*/
|
package/dist/edge/index.js
CHANGED
|
@@ -1,21 +1,81 @@
|
|
|
1
|
+
import {
|
|
2
|
+
formatBytes,
|
|
3
|
+
toSdkSchema,
|
|
4
|
+
valibotToJsonSchema
|
|
5
|
+
} from "../chunk-4FH73ERY.js";
|
|
6
|
+
|
|
1
7
|
// src/edge/index.ts
|
|
2
8
|
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
|
|
3
9
|
import { Hono } from "hono";
|
|
4
10
|
import { z } from "zod";
|
|
11
|
+
var convertToJsonSchema = async (schema, io) => {
|
|
12
|
+
const { vendor } = schema["~standard"];
|
|
13
|
+
if (vendor !== "valibot") {
|
|
14
|
+
throw new Error(
|
|
15
|
+
`Schema library "${vendor}" carries no JSON Schema (\`~standard.jsonSchema\`), and EdgeViteMCP converts only Valibot's. Use Zod 4, ArkType or Valibot.`
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
return valibotToJsonSchema(schema, io);
|
|
19
|
+
};
|
|
20
|
+
var readCappedRequest = async (request, maxBytes) => {
|
|
21
|
+
if (!request.body) {
|
|
22
|
+
return request;
|
|
23
|
+
}
|
|
24
|
+
if (Number(request.headers.get("content-length") ?? 0) > maxBytes) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
const reader = request.body.getReader();
|
|
28
|
+
const chunks = [];
|
|
29
|
+
let size = 0;
|
|
30
|
+
for (; ; ) {
|
|
31
|
+
const { done, value } = await reader.read();
|
|
32
|
+
if (done) {
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
size += value.byteLength;
|
|
36
|
+
if (size > maxBytes) {
|
|
37
|
+
await reader.cancel().catch(() => {
|
|
38
|
+
});
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
chunks.push(value);
|
|
42
|
+
}
|
|
43
|
+
const body = new Uint8Array(size);
|
|
44
|
+
let offset = 0;
|
|
45
|
+
for (const chunk of chunks) {
|
|
46
|
+
body.set(chunk, offset);
|
|
47
|
+
offset += chunk.byteLength;
|
|
48
|
+
}
|
|
49
|
+
return new Request(request.url, {
|
|
50
|
+
body,
|
|
51
|
+
headers: request.headers,
|
|
52
|
+
method: request.method,
|
|
53
|
+
signal: request.signal
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
var DEFAULT_MAX_BODY_SIZE = 1024 * 1024;
|
|
57
|
+
var invalidRequest = (description) => Response.json(
|
|
58
|
+
{ error: "invalid_request", error_description: description },
|
|
59
|
+
{ status: 400 }
|
|
60
|
+
);
|
|
5
61
|
var EdgeViteMCP = class {
|
|
6
62
|
#handler = null;
|
|
7
63
|
#honoApp = new Hono();
|
|
8
64
|
#logger;
|
|
65
|
+
#maxBodySize;
|
|
9
66
|
#mcpPath;
|
|
10
67
|
#name;
|
|
11
68
|
#prompts = [];
|
|
12
69
|
#resources = [];
|
|
13
70
|
#tools = [];
|
|
71
|
+
/** Each tool's input schema, as `#sdkSchemaFor` converted it. */
|
|
72
|
+
#toolSchemas = /* @__PURE__ */ new WeakMap();
|
|
14
73
|
#version;
|
|
15
74
|
constructor(options) {
|
|
16
75
|
this.#name = options.name;
|
|
17
76
|
this.#version = options.version;
|
|
18
77
|
this.#logger = options.logger ?? console;
|
|
78
|
+
this.#maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
|
|
19
79
|
this.#mcpPath = options.mcpPath ?? "/mcp";
|
|
20
80
|
}
|
|
21
81
|
addPrompt(prompt) {
|
|
@@ -37,8 +97,20 @@ var EdgeViteMCP = class {
|
|
|
37
97
|
async fetch(request) {
|
|
38
98
|
const url = new URL(request.url);
|
|
39
99
|
if (url.pathname === this.#mcpPath) {
|
|
100
|
+
let capped;
|
|
101
|
+
try {
|
|
102
|
+
capped = await readCappedRequest(request, this.#maxBodySize);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.#logger.debug(`[EdgeViteMCP] request body failed:`, error);
|
|
105
|
+
return invalidRequest("Request body could not be read");
|
|
106
|
+
}
|
|
107
|
+
if (!capped) {
|
|
108
|
+
return invalidRequest(
|
|
109
|
+
`Request body exceeds ${formatBytes(this.#maxBodySize)}`
|
|
110
|
+
);
|
|
111
|
+
}
|
|
40
112
|
this.#handler ??= createMcpHandler(() => this.#buildServer());
|
|
41
|
-
return this.#handler.fetch(
|
|
113
|
+
return this.#handler.fetch(capped);
|
|
42
114
|
}
|
|
43
115
|
return this.#honoApp.fetch(request);
|
|
44
116
|
}
|
|
@@ -46,22 +118,32 @@ var EdgeViteMCP = class {
|
|
|
46
118
|
getApp() {
|
|
47
119
|
return this.#honoApp;
|
|
48
120
|
}
|
|
49
|
-
#buildServer() {
|
|
121
|
+
async #buildServer() {
|
|
50
122
|
const server = new McpServer({
|
|
51
123
|
name: this.#name,
|
|
52
124
|
version: this.#version
|
|
53
125
|
});
|
|
54
|
-
|
|
126
|
+
const tools = (await Promise.all(
|
|
127
|
+
this.#tools.map(async (tool) => {
|
|
128
|
+
const schema = await this.#sdkSchemaFor(tool);
|
|
129
|
+
return schema && { schema, tool };
|
|
130
|
+
})
|
|
131
|
+
)).filter((entry) => entry !== void 0);
|
|
132
|
+
for (const { schema, tool } of tools) {
|
|
133
|
+
const call = async (args) => {
|
|
134
|
+
const result = await tool.execute(args);
|
|
135
|
+
return typeof result === "string" ? { content: [{ text: result, type: "text" }] } : result;
|
|
136
|
+
};
|
|
55
137
|
server.registerTool(
|
|
56
138
|
tool.name,
|
|
57
139
|
{
|
|
58
140
|
description: tool.description,
|
|
59
|
-
inputSchema:
|
|
141
|
+
inputSchema: schema.inputSchema
|
|
60
142
|
},
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
143
|
+
// The SDK passes arguments only to a tool that declares an input
|
|
144
|
+
// schema; one that does not is called with the request context alone,
|
|
145
|
+
// which must not reach `execute` as its parameters.
|
|
146
|
+
schema.inputSchema ? call : () => call(void 0)
|
|
65
147
|
);
|
|
66
148
|
}
|
|
67
149
|
for (const resource of this.#resources) {
|
|
@@ -89,25 +171,50 @@ var EdgeViteMCP = class {
|
|
|
89
171
|
for (const arg of prompt.arguments ?? []) {
|
|
90
172
|
shape[arg.name] = arg.required ? z.string() : z.string().optional();
|
|
91
173
|
}
|
|
174
|
+
const argsSchema = prompt.arguments?.length ? z.object(shape) : void 0;
|
|
175
|
+
const load = async (args) => {
|
|
176
|
+
const text = await prompt.load(args ?? {});
|
|
177
|
+
return {
|
|
178
|
+
messages: [
|
|
179
|
+
{ content: { text, type: "text" }, role: "user" }
|
|
180
|
+
]
|
|
181
|
+
};
|
|
182
|
+
};
|
|
92
183
|
server.registerPrompt(
|
|
93
184
|
prompt.name,
|
|
94
|
-
{
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
(async (args) => {
|
|
99
|
-
const text = await prompt.load(args ?? {});
|
|
100
|
-
return {
|
|
101
|
-
messages: [
|
|
102
|
-
{ content: { text, type: "text" }, role: "user" }
|
|
103
|
-
]
|
|
104
|
-
};
|
|
105
|
-
})
|
|
185
|
+
{ argsSchema, description: prompt.description },
|
|
186
|
+
// As for tools: without `argsSchema` the SDK passes the request
|
|
187
|
+
// context alone.
|
|
188
|
+
argsSchema ? load : () => load()
|
|
106
189
|
);
|
|
107
190
|
}
|
|
108
191
|
this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);
|
|
109
192
|
return server;
|
|
110
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* A tool's input schema in the form the SDK registers it, or `undefined` for
|
|
196
|
+
* a tool whose schema cannot be converted — reported when that is found.
|
|
197
|
+
*
|
|
198
|
+
* Converted once per tool: `#buildServer` runs on every request, so a tool
|
|
199
|
+
* that cannot be served would otherwise be reported on each of them.
|
|
200
|
+
*/
|
|
201
|
+
#sdkSchemaFor(tool) {
|
|
202
|
+
let schema = this.#toolSchemas.get(tool);
|
|
203
|
+
if (!schema) {
|
|
204
|
+
schema = toSdkSchema(tool.parameters, "input", convertToJsonSchema).then(
|
|
205
|
+
(inputSchema) => ({ inputSchema }),
|
|
206
|
+
(error) => {
|
|
207
|
+
this.#logger.error(
|
|
208
|
+
`[EdgeViteMCP] Tool "${tool.name}" is not served:`,
|
|
209
|
+
error
|
|
210
|
+
);
|
|
211
|
+
return void 0;
|
|
212
|
+
}
|
|
213
|
+
);
|
|
214
|
+
this.#toolSchemas.set(tool, schema);
|
|
215
|
+
}
|
|
216
|
+
return schema;
|
|
217
|
+
}
|
|
111
218
|
};
|
|
112
219
|
export {
|
|
113
220
|
EdgeViteMCP
|
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\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 * Base path for MCP endpoints (default: \"/mcp\")\n */\n mcpPath?: string;\n name: string;\n version: string;\n}\n\nexport class EdgeViteMCP {\n #handler: null | ReturnType<typeof createMcpHandler> = null;\n #honoApp = new Hono();\n #logger: EdgeLogger;\n #mcpPath: string;\n #name: string;\n #prompts: EdgePrompt[] = [];\n #resources: EdgeResource[] = [];\n #tools: EdgeTool[] = [];\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.#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 this.#handler ??= createMcpHandler(() => this.#buildServer());\n return this.#handler.fetch(request);\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 #buildServer(): McpServer {\n const server = new McpServer({\n name: this.#name,\n version: this.#version,\n });\n\n for (const tool of this.#tools) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.parameters as never,\n },\n (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 }) 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 server.registerPrompt(\n prompt.name,\n {\n argsSchema: prompt.arguments?.length ? z.object(shape) : undefined,\n description: prompt.description,\n } as never,\n (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 }) as never,\n );\n }\n\n this.#logger.debug(`[EdgeViteMCP] built server ${this.#name}`);\n\n return server;\n }\n}\n"],"mappings":";AAMA,SAAS,kBAAkB,iBAAiB;AAE5C,SAAS,YAAY;AACrB,SAAS,SAAS;AAwEX,IAAM,cAAN,MAAkB;AAAA,EACvB,WAAuD;AAAA,EACvD,WAAW,IAAI,KAAK;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAyB,CAAC;AAAA,EAC1B,aAA6B,CAAC;AAAA,EAC9B,SAAqB,CAAC;AAAA,EACtB;AAAA,EAEA,YAAY,SAA6B;AACvC,SAAK,QAAQ,QAAQ;AACrB,SAAK,WAAW,QAAQ;AACxB,SAAK,UAAU,QAAQ,UAAU;AACjC,SAAK,WAAW,QAAQ,WAAW;AAAA,EACrC;AAAA,EAEA,UAAU,QAA0B;AAClC,SAAK,SAAS,KAAK,MAAM;AACzB,SAAK,WAAW;AAChB,WAAO;AAAA,EACT;AAAA,EAEA,YAAY,UAA8B;AACxC,SAAK,WAAW,KAAK,QAAQ;AAC7B,SAAK,WAAW;AAChB,WAAO;AAAA,EACT;AAAA,EAEA,QAAiB,MAA+B;AAC9C,SAAK,OAAO,KAAK,IAAgB;AACjC,SAAK,WAAW;AAChB,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,MAAM,SAAqC;AAC/C,UAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAE/B,QAAI,IAAI,aAAa,KAAK,UAAU;AAClC,WAAK,aAAa,iBAAiB,MAAM,KAAK,aAAa,CAAC;AAC5D,aAAO,KAAK,SAAS,MAAM,OAAO;AAAA,IACpC;AAEA,WAAO,KAAK,SAAS,MAAM,OAAO;AAAA,EACpC;AAAA;AAAA,EAGA,SAAe;AACb,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,eAA0B;AACxB,UAAM,SAAS,IAAI,UAAU;AAAA,MAC3B,MAAM,KAAK;AA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C,iBAAO;AAAA,YACL,UAAU;AAAA,cACR,EAAE,SAAS,EAAE,MAAM,MAAM,OAAO,GAAG,MAAM,OAAgB;AAAA,YAC3D;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ,MAAM,8BAA8B,KAAK,KAAK,EAAE;AAE7D,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 {\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 ? z.object(shape) : 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;AA4FlB,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,C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