@vitemcp/server 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +2001 -0
- package/dist/OAuthProvider-Cg7nUJJT.d.cts +961 -0
- package/dist/OAuthProvider-Cg7nUJJT.d.ts +961 -0
- package/dist/ViteMCP.cjs +1115 -0
- package/dist/ViteMCP.cjs.map +1 -0
- package/dist/ViteMCP.d.cts +400 -0
- package/dist/ViteMCP.d.ts +400 -0
- package/dist/ViteMCP.js +1115 -0
- package/dist/ViteMCP.js.map +1 -0
- package/dist/auth/index.cjs +55 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +411 -0
- package/dist/auth/index.d.ts +411 -0
- package/dist/auth/index.js +55 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/bin/vitemcp.cjs +237 -0
- package/dist/bin/vitemcp.cjs.map +1 -0
- package/dist/bin/vitemcp.d.cts +1 -0
- package/dist/bin/vitemcp.d.ts +1 -0
- package/dist/bin/vitemcp.js +237 -0
- package/dist/bin/vitemcp.js.map +1 -0
- package/dist/chunk-57MXTIW7.cjs +3119 -0
- package/dist/chunk-57MXTIW7.cjs.map +1 -0
- package/dist/chunk-NZIPGNND.js +3119 -0
- package/dist/chunk-NZIPGNND.js.map +1 -0
- package/dist/edge/index.cjs +115 -0
- package/dist/edge/index.cjs.map +1 -0
- package/dist/edge/index.d.cts +84 -0
- package/dist/edge/index.d.ts +84 -0
- package/dist/edge/index.js +115 -0
- package/dist/edge/index.js.map +1 -0
- package/package.json +152 -0
package/dist/ViteMCP.js
ADDED
|
@@ -0,0 +1,1115 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthProvider,
|
|
3
|
+
AzureProvider,
|
|
4
|
+
GitHubProvider,
|
|
5
|
+
GoogleProvider,
|
|
6
|
+
OAuthProvider,
|
|
7
|
+
getAuthSession,
|
|
8
|
+
requireAll,
|
|
9
|
+
requireAny,
|
|
10
|
+
requireAuth,
|
|
11
|
+
requireRole,
|
|
12
|
+
requireScopes
|
|
13
|
+
} from "./chunk-NZIPGNND.js";
|
|
14
|
+
|
|
15
|
+
// src/ViteMCP.ts
|
|
16
|
+
import {
|
|
17
|
+
acceptedContent,
|
|
18
|
+
completable,
|
|
19
|
+
createMcpHandler,
|
|
20
|
+
fromJsonSchema,
|
|
21
|
+
inputRequired,
|
|
22
|
+
localhostAllowedOrigins,
|
|
23
|
+
McpServer,
|
|
24
|
+
originValidationResponse,
|
|
25
|
+
ResourceTemplate as SDKResourceTemplate
|
|
26
|
+
} from "@modelcontextprotocol/server";
|
|
27
|
+
import {
|
|
28
|
+
serveStdio
|
|
29
|
+
} from "@modelcontextprotocol/server/stdio";
|
|
30
|
+
import { readFile } from "fs/promises";
|
|
31
|
+
import { Hono as Hono2 } from "hono";
|
|
32
|
+
import { cors } from "hono/cors";
|
|
33
|
+
import http from "http";
|
|
34
|
+
import https from "https";
|
|
35
|
+
import { setTimeout as delay } from "timers/promises";
|
|
36
|
+
import { fetch as fetch2 } from "undici";
|
|
37
|
+
import parseURITemplate from "uri-templates";
|
|
38
|
+
import { strictJsonSchema, toJsonSchema } from "xsschema";
|
|
39
|
+
import { z } from "zod";
|
|
40
|
+
|
|
41
|
+
// src/auth/router.ts
|
|
42
|
+
import { Hono } from "hono";
|
|
43
|
+
var OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;
|
|
44
|
+
var errorResponse = (error) => {
|
|
45
|
+
const err = error;
|
|
46
|
+
return {
|
|
47
|
+
body: err.toJSON?.() ?? { error: "invalid_request" },
|
|
48
|
+
status: err.statusCode ?? 400
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
var readCappedBody = async (request) => {
|
|
52
|
+
const declared = request.headers.get("content-length");
|
|
53
|
+
if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (!request.body) {
|
|
57
|
+
try {
|
|
58
|
+
const text = await request.text();
|
|
59
|
+
return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const reader = request.body.getReader();
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
try {
|
|
68
|
+
for (; ; ) {
|
|
69
|
+
const { done, value } = await reader.read();
|
|
70
|
+
if (done) {
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
size += value.byteLength;
|
|
74
|
+
if (size > OAUTH_PROXY_MAX_BODY_SIZE) {
|
|
75
|
+
await reader.cancel().catch(() => {
|
|
76
|
+
});
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
chunks.push(value);
|
|
80
|
+
}
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
85
|
+
};
|
|
86
|
+
var readJsonBody = async (request) => {
|
|
87
|
+
const text = await readCappedBody(request);
|
|
88
|
+
if (text === null) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(text);
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
var tooLarge = {
|
|
98
|
+
error: "invalid_request",
|
|
99
|
+
error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`
|
|
100
|
+
};
|
|
101
|
+
var toSnakeCase = (value) => {
|
|
102
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
return Object.fromEntries(
|
|
106
|
+
Object.entries(value).map(([k, v]) => [
|
|
107
|
+
k.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase(),
|
|
108
|
+
v
|
|
109
|
+
])
|
|
110
|
+
);
|
|
111
|
+
};
|
|
112
|
+
var createOAuthRouter = (options) => {
|
|
113
|
+
const app = new Hono();
|
|
114
|
+
const { proxy } = options;
|
|
115
|
+
const basePath = options.basePath ?? "";
|
|
116
|
+
const endpoint = options.endpoint ?? "";
|
|
117
|
+
const serve = (path, body) => app.get(path, (c) => c.json(body));
|
|
118
|
+
if (options.authorizationServer) {
|
|
119
|
+
serve(
|
|
120
|
+
`/.well-known/oauth-authorization-server${basePath}`,
|
|
121
|
+
toSnakeCase(options.authorizationServer)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if (options.protectedResource) {
|
|
125
|
+
const body = toSnakeCase(options.protectedResource);
|
|
126
|
+
const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;
|
|
127
|
+
serve(scoped, body);
|
|
128
|
+
if (scoped !== "/.well-known/oauth-protected-resource") {
|
|
129
|
+
serve("/.well-known/oauth-protected-resource", body);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (!proxy) {
|
|
133
|
+
return app;
|
|
134
|
+
}
|
|
135
|
+
app.post(`${basePath}/oauth/register`, async (c) => {
|
|
136
|
+
const body = await readJsonBody(c.req.raw);
|
|
137
|
+
if (body === null) {
|
|
138
|
+
return c.json(tooLarge, 400);
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
return c.json(await proxy.registerClient(body), 201);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
const { body: errBody, status } = errorResponse(error);
|
|
144
|
+
return c.json(errBody, status);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
app.get(`${basePath}/oauth/authorize`, async (c) => {
|
|
148
|
+
try {
|
|
149
|
+
const params = Object.fromEntries(
|
|
150
|
+
new URL(c.req.url).searchParams.entries()
|
|
151
|
+
);
|
|
152
|
+
return await proxy.authorize(params);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
const { body, status } = errorResponse(error);
|
|
155
|
+
return c.json(body, status);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
app.post(`${basePath}/oauth/token`, async (c) => {
|
|
159
|
+
const raw = c.req.raw;
|
|
160
|
+
const text = await readCappedBody(raw);
|
|
161
|
+
if (text === null) {
|
|
162
|
+
return c.json(tooLarge, 400);
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const params = Object.fromEntries(new URLSearchParams(text).entries());
|
|
166
|
+
const authHeader = raw.headers.get("authorization");
|
|
167
|
+
if (authHeader?.toLowerCase().startsWith("basic ")) {
|
|
168
|
+
const decoded = Buffer.from(authHeader.slice(6), "base64").toString(
|
|
169
|
+
"utf8"
|
|
170
|
+
);
|
|
171
|
+
const separator = decoded.indexOf(":");
|
|
172
|
+
if (separator !== -1) {
|
|
173
|
+
params.client_id ||= decodeURIComponent(decoded.slice(0, separator));
|
|
174
|
+
params.client_secret ||= decodeURIComponent(
|
|
175
|
+
decoded.slice(separator + 1)
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const result = params.grant_type === "refresh_token" ? await proxy.exchangeRefreshToken(params) : await proxy.exchangeAuthorizationCode(params);
|
|
180
|
+
return c.json(result);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
const { body, status } = errorResponse(error);
|
|
183
|
+
return c.json(body, status);
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
app.get(
|
|
187
|
+
`${basePath}/oauth/callback`,
|
|
188
|
+
async (c) => proxy.handleCallback(c.req.raw)
|
|
189
|
+
);
|
|
190
|
+
app.all(
|
|
191
|
+
`${basePath}/oauth/consent`,
|
|
192
|
+
async (c) => proxy.handleConsent(c.req.raw)
|
|
193
|
+
);
|
|
194
|
+
return app;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
// src/DiscoveryDocumentCache.ts
|
|
198
|
+
var DiscoveryDocumentCache = class {
|
|
199
|
+
get size() {
|
|
200
|
+
return this.#cache.size;
|
|
201
|
+
}
|
|
202
|
+
#cache = /* @__PURE__ */ new Map();
|
|
203
|
+
#inFlight = /* @__PURE__ */ new Map();
|
|
204
|
+
#timeoutMs;
|
|
205
|
+
#ttl;
|
|
206
|
+
/**
|
|
207
|
+
* @param options - configuration options
|
|
208
|
+
* @param options.timeoutMs - timeout in miliseconds for the upstream fetch
|
|
209
|
+
* @param options.ttl - time-to-live in miliseconds
|
|
210
|
+
*/
|
|
211
|
+
constructor(options = {}) {
|
|
212
|
+
this.#timeoutMs = options.timeoutMs ?? 1e4;
|
|
213
|
+
this.#ttl = options.ttl ?? 36e5;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* @param url - optional URL to clear. if omitted, clears all cached documents.
|
|
217
|
+
*/
|
|
218
|
+
clear(url) {
|
|
219
|
+
if (url) {
|
|
220
|
+
this.#cache.delete(url);
|
|
221
|
+
} else {
|
|
222
|
+
this.#cache.clear();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* fetches a discovery document from the given URL.
|
|
227
|
+
* uses cached value if available and not expired.
|
|
228
|
+
* coalesces concurrent requests for the same URL to prevent duplicate fetches.
|
|
229
|
+
*
|
|
230
|
+
* @param url - the discovery document URL (e.g., /.well-known/openid-configuration)
|
|
231
|
+
* @returns the discovery document as a JSON object
|
|
232
|
+
* @throws Error if the fetch fails or returns non-OK status
|
|
233
|
+
*/
|
|
234
|
+
async get(url) {
|
|
235
|
+
const now = Date.now();
|
|
236
|
+
const cached = this.#cache.get(url);
|
|
237
|
+
if (cached && cached.expiresAt > now) {
|
|
238
|
+
return cached.data;
|
|
239
|
+
}
|
|
240
|
+
const inFlight = this.#inFlight.get(url);
|
|
241
|
+
if (inFlight) {
|
|
242
|
+
return inFlight;
|
|
243
|
+
}
|
|
244
|
+
const fetchPromise = this.#fetchAndCache(url);
|
|
245
|
+
this.#inFlight.set(url, fetchPromise);
|
|
246
|
+
try {
|
|
247
|
+
const data = await fetchPromise;
|
|
248
|
+
return data;
|
|
249
|
+
} finally {
|
|
250
|
+
this.#inFlight.delete(url);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* @param url - the URL to check
|
|
255
|
+
* @returns true if the URL is cached and nott expired
|
|
256
|
+
*/
|
|
257
|
+
has(url) {
|
|
258
|
+
const cached = this.#cache.get(url);
|
|
259
|
+
if (!cached) {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
const now = Date.now();
|
|
263
|
+
if (cached.expiresAt <= now) {
|
|
264
|
+
this.#cache.delete(url);
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
async #fetchAndCache(url) {
|
|
270
|
+
let res;
|
|
271
|
+
try {
|
|
272
|
+
res = await fetch(url, {
|
|
273
|
+
signal: AbortSignal.timeout(this.#timeoutMs)
|
|
274
|
+
});
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
`Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
if (!res.ok) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
const data = await res.json();
|
|
289
|
+
const expiresAt = Date.now() + this.#ttl;
|
|
290
|
+
this.#cache.set(url, {
|
|
291
|
+
data,
|
|
292
|
+
expiresAt
|
|
293
|
+
});
|
|
294
|
+
return data;
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/jsonSchemaAdapter.ts
|
|
299
|
+
function jsonSchemaAdapter(schema) {
|
|
300
|
+
let compiled;
|
|
301
|
+
const getValidator = () => {
|
|
302
|
+
compiled ??= compileSchema(schema).catch((error) => {
|
|
303
|
+
compiled = void 0;
|
|
304
|
+
throw error;
|
|
305
|
+
});
|
|
306
|
+
return compiled;
|
|
307
|
+
};
|
|
308
|
+
return {
|
|
309
|
+
"~standard": {
|
|
310
|
+
jsonSchema: {
|
|
311
|
+
input: () => schema,
|
|
312
|
+
output: () => schema
|
|
313
|
+
},
|
|
314
|
+
validate: async (data) => {
|
|
315
|
+
const validate = await getValidator();
|
|
316
|
+
if (validate(data)) {
|
|
317
|
+
return { value: data };
|
|
318
|
+
}
|
|
319
|
+
return { issues: (validate.errors ?? []).map(toIssue) };
|
|
320
|
+
},
|
|
321
|
+
vendor: "json-schema",
|
|
322
|
+
version: 1
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
async function compileSchema(schema) {
|
|
327
|
+
let ajvModule;
|
|
328
|
+
try {
|
|
329
|
+
ajvModule = await import("ajv");
|
|
330
|
+
} catch {
|
|
331
|
+
throw new Error(
|
|
332
|
+
'The "ajv" package is required to validate JSON Schema tool parameters. Install it with: npm install ajv'
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
const Ajv = unwrapDefault(unwrapDefault(ajvModule));
|
|
336
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
337
|
+
try {
|
|
338
|
+
const formatsModule = await import("ajv-formats");
|
|
339
|
+
const addFormats = unwrapDefault(
|
|
340
|
+
unwrapDefault(formatsModule)
|
|
341
|
+
);
|
|
342
|
+
addFormats(ajv);
|
|
343
|
+
} catch {
|
|
344
|
+
}
|
|
345
|
+
return ajv.compile(schema);
|
|
346
|
+
}
|
|
347
|
+
function toIssue(error) {
|
|
348
|
+
const path = error.instancePath.split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).map((segment) => {
|
|
349
|
+
const index = Number(segment);
|
|
350
|
+
return Number.isInteger(index) && segment !== "" ? index : segment;
|
|
351
|
+
});
|
|
352
|
+
const missingProperty = error.params?.missingProperty;
|
|
353
|
+
if (error.keyword === "required" && typeof missingProperty === "string") {
|
|
354
|
+
path.push(missingProperty);
|
|
355
|
+
}
|
|
356
|
+
return {
|
|
357
|
+
message: error.message || "Validation error",
|
|
358
|
+
path
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
function unwrapDefault(value) {
|
|
362
|
+
return typeof value === "object" && value !== null && "default" in value ? value.default : value;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// src/ViteMCP.ts
|
|
366
|
+
var MEDIA_FETCH_TIMEOUT_MS = 3e4;
|
|
367
|
+
var ViteMCPError = class extends Error {
|
|
368
|
+
constructor(message) {
|
|
369
|
+
super(message);
|
|
370
|
+
this.name = new.target.name;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
var UnexpectedStateError = class extends ViteMCPError {
|
|
374
|
+
extras;
|
|
375
|
+
constructor(message, extras) {
|
|
376
|
+
super(message);
|
|
377
|
+
this.name = new.target.name;
|
|
378
|
+
this.extras = extras;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
var UserError = class extends UnexpectedStateError {
|
|
382
|
+
};
|
|
383
|
+
var readMedia = async (source, kind) => {
|
|
384
|
+
let rawData;
|
|
385
|
+
try {
|
|
386
|
+
if ("url" in source) {
|
|
387
|
+
const response = await fetch2(source.url, {
|
|
388
|
+
signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS)
|
|
389
|
+
});
|
|
390
|
+
if (!response.ok) {
|
|
391
|
+
throw new Error(`Server responded with status: ${response.status}`);
|
|
392
|
+
}
|
|
393
|
+
rawData = Buffer.from(await response.arrayBuffer());
|
|
394
|
+
} else if ("path" in source) {
|
|
395
|
+
rawData = await readFile(source.path);
|
|
396
|
+
} else if ("buffer" in source) {
|
|
397
|
+
rawData = source.buffer;
|
|
398
|
+
} else {
|
|
399
|
+
throw new Error(
|
|
400
|
+
`Invalid ${kind} source: provide one of url, path, or buffer`
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if ("url" in source) {
|
|
405
|
+
const reason = error instanceof Error && error.name === "TimeoutError" ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms` : error instanceof Error ? error.message : String(error);
|
|
406
|
+
throw new Error(
|
|
407
|
+
`Failed to fetch ${kind} from URL (${source.url}): ${reason}`
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
if (error instanceof Error) {
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);
|
|
414
|
+
}
|
|
415
|
+
const { fileTypeFromBuffer } = await import("file-type");
|
|
416
|
+
const mimeType = await fileTypeFromBuffer(rawData);
|
|
417
|
+
return {
|
|
418
|
+
data: rawData.toString("base64"),
|
|
419
|
+
mimeType: mimeType?.mime ?? (kind === "image" ? "image/png" : "audio/mpeg")
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
var imageContent = async (source) => {
|
|
423
|
+
const { data, mimeType } = await readMedia(source, "image");
|
|
424
|
+
return { data, mimeType, type: "image" };
|
|
425
|
+
};
|
|
426
|
+
var audioContent = async (source) => {
|
|
427
|
+
const { data, mimeType } = await readMedia(source, "audio");
|
|
428
|
+
return { data, mimeType, type: "audio" };
|
|
429
|
+
};
|
|
430
|
+
var ServerState = /* @__PURE__ */ ((ServerState2) => {
|
|
431
|
+
ServerState2["Error"] = "error";
|
|
432
|
+
ServerState2["Running"] = "running";
|
|
433
|
+
ServerState2["Starting"] = "starting";
|
|
434
|
+
ServerState2["Stopped"] = "stopped";
|
|
435
|
+
return ServerState2;
|
|
436
|
+
})(ServerState || {});
|
|
437
|
+
var ViteMCP = class {
|
|
438
|
+
get serverState() {
|
|
439
|
+
return this.#serverState;
|
|
440
|
+
}
|
|
441
|
+
#authenticate;
|
|
442
|
+
#connectedServers = [];
|
|
443
|
+
#corsMiddleware = null;
|
|
444
|
+
#handler = null;
|
|
445
|
+
#honoApp = new Hono2();
|
|
446
|
+
#httpServer = null;
|
|
447
|
+
#logger;
|
|
448
|
+
#options;
|
|
449
|
+
#prompts = [];
|
|
450
|
+
#resources = [];
|
|
451
|
+
#resourceTemplates = [];
|
|
452
|
+
#serverState = "stopped" /* Stopped */;
|
|
453
|
+
#stdioHandle = null;
|
|
454
|
+
#tools = [];
|
|
455
|
+
constructor(options) {
|
|
456
|
+
this.#options = options;
|
|
457
|
+
this.#logger = options.logger ?? console;
|
|
458
|
+
const provider = options.auth;
|
|
459
|
+
this.#authenticate = options.authenticate ?? (provider ? ((request) => provider.authenticate(request)) : void 0);
|
|
460
|
+
this.#honoApp = this.#freshApp();
|
|
461
|
+
}
|
|
462
|
+
addPrompt(prompt) {
|
|
463
|
+
this.#prompts.push(prompt);
|
|
464
|
+
this.#notifyListChanged("prompts");
|
|
465
|
+
}
|
|
466
|
+
addPrompts(prompts) {
|
|
467
|
+
for (const prompt of prompts) {
|
|
468
|
+
this.#prompts.push(prompt);
|
|
469
|
+
}
|
|
470
|
+
this.#notifyListChanged("prompts");
|
|
471
|
+
}
|
|
472
|
+
addResource(resource) {
|
|
473
|
+
this.#resources.push(resource);
|
|
474
|
+
this.#notifyListChanged("resources");
|
|
475
|
+
}
|
|
476
|
+
addResources(resources) {
|
|
477
|
+
for (const resource of resources) {
|
|
478
|
+
this.#resources.push(resource);
|
|
479
|
+
}
|
|
480
|
+
this.#notifyListChanged("resources");
|
|
481
|
+
}
|
|
482
|
+
addResourceTemplate(template) {
|
|
483
|
+
this.#resourceTemplates.push(template);
|
|
484
|
+
this.#notifyListChanged("resources");
|
|
485
|
+
}
|
|
486
|
+
addResourceTemplates(templates) {
|
|
487
|
+
for (const template of templates) {
|
|
488
|
+
this.#resourceTemplates.push(template);
|
|
489
|
+
}
|
|
490
|
+
this.#notifyListChanged("resources");
|
|
491
|
+
}
|
|
492
|
+
addTool(tool) {
|
|
493
|
+
assertStandardSchema(tool.parameters, tool.name, "parameters");
|
|
494
|
+
assertStandardSchema(tool.outputSchema, tool.name, "outputSchema");
|
|
495
|
+
this.#tools.push(tool);
|
|
496
|
+
this.#notifyListChanged("tools");
|
|
497
|
+
}
|
|
498
|
+
addTools(tools) {
|
|
499
|
+
for (const tool of tools) {
|
|
500
|
+
assertStandardSchema(tool.parameters, tool.name, "parameters");
|
|
501
|
+
assertStandardSchema(tool.outputSchema, tool.name, "outputSchema");
|
|
502
|
+
this.#tools.push(tool);
|
|
503
|
+
}
|
|
504
|
+
this.#notifyListChanged("tools");
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Connects the server to an arbitrary transport — used for in-memory unit
|
|
508
|
+
* testing, where a linked transport pair replaces a real socket.
|
|
509
|
+
*/
|
|
510
|
+
async connect(transport) {
|
|
511
|
+
const server = await this.#buildServer(void 0);
|
|
512
|
+
await server.connect(transport);
|
|
513
|
+
this.#connectedServers.push(server);
|
|
514
|
+
this.#serverState = "running" /* Running */;
|
|
515
|
+
return server;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Resolves a resource (or resource template) URI to an embeddable resource
|
|
519
|
+
* body, for returning inline from a tool.
|
|
520
|
+
*/
|
|
521
|
+
async embedded(uri) {
|
|
522
|
+
const direct = this.#resources.find((resource) => resource.uri === uri);
|
|
523
|
+
if (direct) {
|
|
524
|
+
const loaded = await direct.load(this.#makeContext(void 0, void 0));
|
|
525
|
+
const first = Array.isArray(loaded) ? loaded[0] : loaded;
|
|
526
|
+
return { ...first, mimeType: first.mimeType ?? direct.mimeType, uri };
|
|
527
|
+
}
|
|
528
|
+
for (const template of this.#resourceTemplates) {
|
|
529
|
+
const params = parseURITemplate(template.uriTemplate).fromUri(uri);
|
|
530
|
+
if (!params) {
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
const loaded = await template.load(
|
|
534
|
+
params,
|
|
535
|
+
this.#makeContext(void 0, void 0)
|
|
536
|
+
);
|
|
537
|
+
const first = Array.isArray(loaded) ? loaded[0] : loaded;
|
|
538
|
+
return { ...first, mimeType: first.mimeType ?? template.mimeType, uri };
|
|
539
|
+
}
|
|
540
|
+
throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });
|
|
541
|
+
}
|
|
542
|
+
/** The Hono app serving the HTTP transport, for mounting custom routes. */
|
|
543
|
+
getApp() {
|
|
544
|
+
return this.#honoApp;
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Publishes `notifications/resources/updated` for a URI to any subscription
|
|
548
|
+
* that opted in to it.
|
|
549
|
+
*/
|
|
550
|
+
notifyResourceUpdated(uri) {
|
|
551
|
+
this.#handler?.notify.resourceUpdated(uri);
|
|
552
|
+
}
|
|
553
|
+
removePrompt(name) {
|
|
554
|
+
this.#prompts = this.#prompts.filter((p) => p.name !== name);
|
|
555
|
+
this.#notifyListChanged("prompts");
|
|
556
|
+
}
|
|
557
|
+
removePrompts(names) {
|
|
558
|
+
this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));
|
|
559
|
+
this.#notifyListChanged("prompts");
|
|
560
|
+
}
|
|
561
|
+
removeResource(name) {
|
|
562
|
+
this.#resources = this.#resources.filter((r) => r.name !== name);
|
|
563
|
+
this.#notifyListChanged("resources");
|
|
564
|
+
}
|
|
565
|
+
removeResources(names) {
|
|
566
|
+
this.#resources = this.#resources.filter((r) => !names.includes(r.name));
|
|
567
|
+
this.#notifyListChanged("resources");
|
|
568
|
+
}
|
|
569
|
+
removeResourceTemplate(name) {
|
|
570
|
+
this.#resourceTemplates = this.#resourceTemplates.filter(
|
|
571
|
+
(r) => r.name !== name
|
|
572
|
+
);
|
|
573
|
+
this.#notifyListChanged("resources");
|
|
574
|
+
}
|
|
575
|
+
removeResourceTemplates(names) {
|
|
576
|
+
this.#resourceTemplates = this.#resourceTemplates.filter(
|
|
577
|
+
(r) => !names.includes(r.name)
|
|
578
|
+
);
|
|
579
|
+
this.#notifyListChanged("resources");
|
|
580
|
+
}
|
|
581
|
+
removeTool(name) {
|
|
582
|
+
this.#tools = this.#tools.filter((t) => t.name !== name);
|
|
583
|
+
this.#notifyListChanged("tools");
|
|
584
|
+
}
|
|
585
|
+
removeTools(names) {
|
|
586
|
+
this.#tools = this.#tools.filter((t) => !names.includes(t.name));
|
|
587
|
+
this.#notifyListChanged("tools");
|
|
588
|
+
}
|
|
589
|
+
async start(options) {
|
|
590
|
+
this.#serverState = "starting" /* Starting */;
|
|
591
|
+
try {
|
|
592
|
+
if (options.transportType === "stdio") {
|
|
593
|
+
this.#stdioHandle = serveStdio(() => this.#buildServer(void 0));
|
|
594
|
+
this.#logger.info(`[ViteMCP info] server is running on stdio`);
|
|
595
|
+
} else {
|
|
596
|
+
await this.#startHttp(options.httpStream);
|
|
597
|
+
}
|
|
598
|
+
this.#serverState = "running" /* Running */;
|
|
599
|
+
} catch (error) {
|
|
600
|
+
this.#serverState = "error" /* Error */;
|
|
601
|
+
throw error;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async stop() {
|
|
605
|
+
this.#honoApp = this.#freshApp();
|
|
606
|
+
this.#corsMiddleware = null;
|
|
607
|
+
for (const server of this.#connectedServers) {
|
|
608
|
+
await server.close().catch(() => {
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
this.#connectedServers = [];
|
|
612
|
+
await this.#stdioHandle?.close?.();
|
|
613
|
+
this.#stdioHandle = null;
|
|
614
|
+
await this.#handler?.close();
|
|
615
|
+
this.#handler = null;
|
|
616
|
+
if (this.#httpServer) {
|
|
617
|
+
await new Promise(
|
|
618
|
+
(resolve) => this.#httpServer.close(() => resolve())
|
|
619
|
+
);
|
|
620
|
+
this.#httpServer = null;
|
|
621
|
+
}
|
|
622
|
+
this.#serverState = "stopped" /* Stopped */;
|
|
623
|
+
}
|
|
624
|
+
async #buildServer(auth) {
|
|
625
|
+
const server = new McpServer(
|
|
626
|
+
{ name: this.#options.name, version: this.#options.version },
|
|
627
|
+
{ instructions: this.#options.instructions }
|
|
628
|
+
);
|
|
629
|
+
for (const tool of this.#tools) {
|
|
630
|
+
if (tool.canAccess && !tool.canAccess(auth)) {
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
server.registerTool(
|
|
634
|
+
tool.name,
|
|
635
|
+
{
|
|
636
|
+
_meta: tool._meta,
|
|
637
|
+
annotations: tool.annotations,
|
|
638
|
+
description: tool.description,
|
|
639
|
+
inputSchema: await this.#toSdkSchema(
|
|
640
|
+
tool.parameters,
|
|
641
|
+
`Tool "${tool.name}" parameters`
|
|
642
|
+
),
|
|
643
|
+
outputSchema: await this.#toSdkSchema(
|
|
644
|
+
tool.outputSchema,
|
|
645
|
+
`Tool "${tool.name}" outputSchema`
|
|
646
|
+
)
|
|
647
|
+
},
|
|
648
|
+
(async (args, ctx) => {
|
|
649
|
+
const context = this.#makeContext(auth, ctx);
|
|
650
|
+
try {
|
|
651
|
+
const result = await (tool.timeoutMs ? withTimeout(
|
|
652
|
+
tool.execute(args, context),
|
|
653
|
+
tool.timeoutMs,
|
|
654
|
+
tool.name
|
|
655
|
+
) : tool.execute(args, context));
|
|
656
|
+
return normalizeToolResult(result);
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (error instanceof UserError) {
|
|
659
|
+
return {
|
|
660
|
+
content: [{ text: error.message, type: "text" }],
|
|
661
|
+
isError: true,
|
|
662
|
+
...error.extras ? { structuredContent: error.extras } : {}
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
})
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
for (const resource of this.#resources) {
|
|
671
|
+
if (resource.canAccess && !resource.canAccess(auth)) {
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
server.registerResource(
|
|
675
|
+
resource.name,
|
|
676
|
+
resource.uri,
|
|
677
|
+
{
|
|
678
|
+
cacheHint: resource.cache,
|
|
679
|
+
description: resource.description,
|
|
680
|
+
mimeType: resource.mimeType
|
|
681
|
+
},
|
|
682
|
+
(async (uri, ctx) => {
|
|
683
|
+
const context = this.#makeContext(auth, ctx);
|
|
684
|
+
const loaded = await resource.load(context);
|
|
685
|
+
const bodies = Array.isArray(loaded) ? loaded : [loaded];
|
|
686
|
+
return {
|
|
687
|
+
contents: bodies.map((body) => ({
|
|
688
|
+
...body,
|
|
689
|
+
mimeType: body.mimeType ?? resource.mimeType,
|
|
690
|
+
uri: body.uri ?? uri.toString()
|
|
691
|
+
}))
|
|
692
|
+
};
|
|
693
|
+
})
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
for (const template of this.#resourceTemplates) {
|
|
697
|
+
if (template.canAccess && !template.canAccess(auth)) {
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
const complete = {};
|
|
701
|
+
for (const arg of template.arguments ?? []) {
|
|
702
|
+
const completer = arg.complete ?? (template.complete ? (value) => template.complete(arg.name, value) : void 0);
|
|
703
|
+
if (completer) {
|
|
704
|
+
complete[arg.name] = async (value) => (await completer(value)).values;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
server.registerResource(
|
|
708
|
+
template.name,
|
|
709
|
+
new SDKResourceTemplate(template.uriTemplate, {
|
|
710
|
+
complete,
|
|
711
|
+
list: void 0
|
|
712
|
+
}),
|
|
713
|
+
{
|
|
714
|
+
cacheHint: template.cache,
|
|
715
|
+
description: template.description,
|
|
716
|
+
mimeType: template.mimeType
|
|
717
|
+
},
|
|
718
|
+
(async (uri, args, ctx) => {
|
|
719
|
+
const context = this.#makeContext(auth, ctx);
|
|
720
|
+
const loaded = await template.load(args ?? {}, context);
|
|
721
|
+
const bodies = Array.isArray(loaded) ? loaded : [loaded];
|
|
722
|
+
return {
|
|
723
|
+
contents: bodies.map((body) => ({
|
|
724
|
+
...body,
|
|
725
|
+
mimeType: body.mimeType ?? template.mimeType,
|
|
726
|
+
uri: body.uri ?? uri.toString()
|
|
727
|
+
}))
|
|
728
|
+
};
|
|
729
|
+
})
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
for (const prompt of this.#prompts) {
|
|
733
|
+
if (prompt.canAccess && !prompt.canAccess(auth)) {
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
server.registerPrompt(
|
|
737
|
+
prompt.name,
|
|
738
|
+
{
|
|
739
|
+
argsSchema: promptArgsSchema(prompt),
|
|
740
|
+
description: prompt.description
|
|
741
|
+
},
|
|
742
|
+
(async (args, ctx) => {
|
|
743
|
+
const context = this.#makeContext(auth, ctx);
|
|
744
|
+
const loaded = await prompt.load(args ?? {}, context);
|
|
745
|
+
if (typeof loaded !== "string") {
|
|
746
|
+
return loaded;
|
|
747
|
+
}
|
|
748
|
+
return {
|
|
749
|
+
messages: [
|
|
750
|
+
{
|
|
751
|
+
content: { text: loaded, type: "text" },
|
|
752
|
+
role: "user"
|
|
753
|
+
}
|
|
754
|
+
]
|
|
755
|
+
};
|
|
756
|
+
})
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
return server;
|
|
760
|
+
}
|
|
761
|
+
/** Builds the Hono app with the CORS shim installed ahead of user routes. */
|
|
762
|
+
#freshApp() {
|
|
763
|
+
const app = new Hono2();
|
|
764
|
+
app.use(
|
|
765
|
+
"*",
|
|
766
|
+
(c, next) => this.#corsMiddleware ? this.#corsMiddleware(c, next) : next()
|
|
767
|
+
);
|
|
768
|
+
return app;
|
|
769
|
+
}
|
|
770
|
+
/** Bridges the v2 per-request context onto ViteMCP's `Context`. */
|
|
771
|
+
#makeContext(auth, rawCtx) {
|
|
772
|
+
const ctx = rawCtx;
|
|
773
|
+
const mcpReq = ctx?.mcpReq;
|
|
774
|
+
const requestedLevel = mcpReq?._meta?.["io.modelcontextprotocol/logLevel"];
|
|
775
|
+
const emit = (level, message, data) => {
|
|
776
|
+
if (!requestedLevel) {
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
void mcpReq?.notify?.({
|
|
780
|
+
method: "notifications/message",
|
|
781
|
+
params: { data: { context: data, message }, level }
|
|
782
|
+
})?.catch(() => {
|
|
783
|
+
});
|
|
784
|
+
};
|
|
785
|
+
return {
|
|
786
|
+
auth,
|
|
787
|
+
elicit: (params) => inputRequired.elicit({
|
|
788
|
+
message: params.message,
|
|
789
|
+
requestedSchema: params.requestedSchema
|
|
790
|
+
}),
|
|
791
|
+
input: (key, schema) => acceptedContent(mcpReq?.inputResponses, key, schema),
|
|
792
|
+
inputRequired: (inputRequests, requestState) => inputRequired({ inputRequests, requestState }),
|
|
793
|
+
inputResponses: mcpReq?.inputResponses,
|
|
794
|
+
log: {
|
|
795
|
+
debug: (m, d) => emit("debug", m, d),
|
|
796
|
+
error: (m, d) => emit("error", m, d),
|
|
797
|
+
info: (m, d) => emit("info", m, d),
|
|
798
|
+
warn: (m, d) => emit("warning", m, d)
|
|
799
|
+
},
|
|
800
|
+
reportProgress: async (progress) => {
|
|
801
|
+
const progressToken = mcpReq?._meta?.progressToken;
|
|
802
|
+
if (progressToken === void 0) {
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
await mcpReq?.notify?.({
|
|
806
|
+
method: "notifications/progress",
|
|
807
|
+
params: {
|
|
808
|
+
message: progress.message,
|
|
809
|
+
progress: progress.progress,
|
|
810
|
+
progressToken,
|
|
811
|
+
total: progress.total
|
|
812
|
+
}
|
|
813
|
+
});
|
|
814
|
+
},
|
|
815
|
+
requestId: mcpReq?.id,
|
|
816
|
+
// The SDK exposes this as an accessor; call it so callers get the value.
|
|
817
|
+
requestState: mcpReq?.requestState?.()
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Publishes a change event to any open `subscriptions/listen` stream. This
|
|
822
|
+
* replaces the 2025-era `notifications/*_list_changed` broadcast, which had
|
|
823
|
+
* no addressee on a stateless transport.
|
|
824
|
+
*/
|
|
825
|
+
#notifyListChanged(kind) {
|
|
826
|
+
const notifier = this.#handler?.notify;
|
|
827
|
+
if (!notifier) {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (kind === "tools") notifier.toolsChanged();
|
|
831
|
+
if (kind === "prompts") notifier.promptsChanged();
|
|
832
|
+
if (kind === "resources") notifier.resourcesChanged();
|
|
833
|
+
}
|
|
834
|
+
async #startHttp(config) {
|
|
835
|
+
this.#handler = createMcpHandler(
|
|
836
|
+
async (ctx) => {
|
|
837
|
+
const request = ctx.requestInfo;
|
|
838
|
+
const auth = this.#authenticate && request ? await this.#authenticate(request) : void 0;
|
|
839
|
+
return this.#buildServer(auth);
|
|
840
|
+
},
|
|
841
|
+
{
|
|
842
|
+
// Tradeoff: `server/discover` advertises only 2026-07-28, so legacy
|
|
843
|
+
// requests are answered unadvertised and skip Mcp-* validation.
|
|
844
|
+
legacy: config.legacy ?? "stateless",
|
|
845
|
+
...config.enableJsonResponse ? { responseMode: "json" } : {},
|
|
846
|
+
onerror: (error) => this.#logger.error("[ViteMCP error]", error)
|
|
847
|
+
}
|
|
848
|
+
);
|
|
849
|
+
this.#corsMiddleware = config.cors === false ? null : cors(config.cors);
|
|
850
|
+
const oauth = this.#options.oauth ?? this.#options.auth?.getOAuthConfig();
|
|
851
|
+
if (oauth?.enabled !== false && (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)) {
|
|
852
|
+
this.#honoApp.route(
|
|
853
|
+
"/",
|
|
854
|
+
createOAuthRouter({
|
|
855
|
+
authorizationServer: oauth.authorizationServer,
|
|
856
|
+
basePath: config.basePath,
|
|
857
|
+
endpoint: config.endpoint ?? "/mcp",
|
|
858
|
+
protectedResource: oauth.protectedResource,
|
|
859
|
+
proxy: oauth.proxy
|
|
860
|
+
})
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
const health = this.#options.health;
|
|
864
|
+
if (health?.enabled !== false) {
|
|
865
|
+
this.#honoApp.get(
|
|
866
|
+
health?.path ?? "/health",
|
|
867
|
+
(c) => c.text(health?.message ?? "ok", health?.status ?? 200)
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
const endpoint = `${config.basePath ?? ""}${config.endpoint ?? "/mcp"}`;
|
|
871
|
+
const handler = this.#handler;
|
|
872
|
+
const host = config.host ?? "127.0.0.1";
|
|
873
|
+
const isLoopback = ["::1", "127.0.0.1", "localhost"].includes(host);
|
|
874
|
+
const allowedOrigins = config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);
|
|
875
|
+
if (!config.allowedOrigins && !isLoopback) {
|
|
876
|
+
this.#logger.warn(
|
|
877
|
+
`[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
this.#honoApp.all(endpoint, async (c) => {
|
|
881
|
+
const rejected = originValidationResponse(c.req.raw, allowedOrigins);
|
|
882
|
+
if (rejected) {
|
|
883
|
+
return rejected;
|
|
884
|
+
}
|
|
885
|
+
return handler.fetch(c.req.raw);
|
|
886
|
+
});
|
|
887
|
+
const app = this.#honoApp;
|
|
888
|
+
const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;
|
|
889
|
+
const useTls = Boolean(config.sslCert && config.sslKey);
|
|
890
|
+
const requestListener = (req, res) => {
|
|
891
|
+
void (async () => {
|
|
892
|
+
try {
|
|
893
|
+
const body = await readCappedNodeBody(req, maxBodySize);
|
|
894
|
+
if (body === OVERSIZE) {
|
|
895
|
+
res.writeHead(400, {
|
|
896
|
+
Connection: "close",
|
|
897
|
+
"Content-Type": "application/json"
|
|
898
|
+
});
|
|
899
|
+
req.resume();
|
|
900
|
+
res.once("finish", () => res.socket?.end());
|
|
901
|
+
res.end(
|
|
902
|
+
JSON.stringify({
|
|
903
|
+
error: "invalid_request",
|
|
904
|
+
error_description: `Request body exceeds ${formatBytes(maxBodySize)}`
|
|
905
|
+
})
|
|
906
|
+
);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const response = await app.fetch(
|
|
910
|
+
nodeToWebRequest(req, body, useTls),
|
|
911
|
+
{
|
|
912
|
+
incoming: req,
|
|
913
|
+
outgoing: res
|
|
914
|
+
}
|
|
915
|
+
);
|
|
916
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
917
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
918
|
+
} catch (error) {
|
|
919
|
+
this.#logger.debug(`[ViteMCP debug] request failed:`, error);
|
|
920
|
+
if (!res.headersSent) {
|
|
921
|
+
res.writeHead(400, {
|
|
922
|
+
Connection: "close",
|
|
923
|
+
"Content-Type": "application/json"
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
res.end(
|
|
927
|
+
JSON.stringify({
|
|
928
|
+
error: "invalid_request",
|
|
929
|
+
error_description: "Request body could not be read"
|
|
930
|
+
})
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
})();
|
|
934
|
+
};
|
|
935
|
+
this.#httpServer = useTls ? https.createServer(
|
|
936
|
+
{
|
|
937
|
+
...config.sslCa ? { ca: await readFile(config.sslCa) } : {},
|
|
938
|
+
cert: await readFile(config.sslCert),
|
|
939
|
+
key: await readFile(config.sslKey)
|
|
940
|
+
},
|
|
941
|
+
requestListener
|
|
942
|
+
) : http.createServer(requestListener);
|
|
943
|
+
await new Promise(
|
|
944
|
+
(resolve) => this.#httpServer.listen(
|
|
945
|
+
config.port,
|
|
946
|
+
config.host ?? "127.0.0.1",
|
|
947
|
+
resolve
|
|
948
|
+
)
|
|
949
|
+
);
|
|
950
|
+
this.#logger.info(
|
|
951
|
+
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${config.host ?? "127.0.0.1"}:${config.port}${endpoint}`
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Converts a schema the SDK cannot consume directly. Zod v4 emits JSON
|
|
956
|
+
* Schema natively; valibot/arktype go via xsschema.
|
|
957
|
+
*/
|
|
958
|
+
async #toSdkSchema(schema, label) {
|
|
959
|
+
if (!schema) {
|
|
960
|
+
return void 0;
|
|
961
|
+
}
|
|
962
|
+
const standard = schema["~standard"];
|
|
963
|
+
if (standard?.jsonSchema) {
|
|
964
|
+
return schema;
|
|
965
|
+
}
|
|
966
|
+
try {
|
|
967
|
+
const json = strictJsonSchema(await toJsonSchema(schema));
|
|
968
|
+
return fromJsonSchema(json);
|
|
969
|
+
} catch (error) {
|
|
970
|
+
throw new UnexpectedStateError(
|
|
971
|
+
`${label} is not a supported Standard Schema: ${error instanceof Error ? error.message : String(error)}`,
|
|
972
|
+
{ label }
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
var nodeToWebRequest = (req, body, secure) => {
|
|
978
|
+
const host = req.headers.host ?? "localhost";
|
|
979
|
+
const url = `${secure ? "https" : "http"}://${host}${req.url ?? "/"}`;
|
|
980
|
+
const headers = new Headers();
|
|
981
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
982
|
+
if (value === void 0 || name.startsWith(":")) {
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
if (Array.isArray(value)) {
|
|
986
|
+
for (const item of value) {
|
|
987
|
+
headers.append(name, item);
|
|
988
|
+
}
|
|
989
|
+
} else {
|
|
990
|
+
headers.set(name, value);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
994
|
+
const hasBody = method !== "GET" && method !== "HEAD" && body.byteLength > 0;
|
|
995
|
+
return new Request(url, {
|
|
996
|
+
headers,
|
|
997
|
+
method,
|
|
998
|
+
...hasBody ? { body } : {}
|
|
999
|
+
});
|
|
1000
|
+
};
|
|
1001
|
+
var withTimeout = (work, timeoutMs, toolName) => new Promise((resolve, reject) => {
|
|
1002
|
+
const timer = setTimeout(() => {
|
|
1003
|
+
reject(
|
|
1004
|
+
new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {
|
|
1005
|
+
timeoutMs,
|
|
1006
|
+
toolName
|
|
1007
|
+
})
|
|
1008
|
+
);
|
|
1009
|
+
}, timeoutMs);
|
|
1010
|
+
work.then(resolve, reject).finally(() => clearTimeout(timer));
|
|
1011
|
+
});
|
|
1012
|
+
var formatBytes = (bytes) => {
|
|
1013
|
+
if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {
|
|
1014
|
+
return `${bytes / (1024 * 1024)} MiB`;
|
|
1015
|
+
}
|
|
1016
|
+
if (bytes >= 1024 && bytes % 1024 === 0) {
|
|
1017
|
+
return `${bytes / 1024} KiB`;
|
|
1018
|
+
}
|
|
1019
|
+
return `${bytes} bytes`;
|
|
1020
|
+
};
|
|
1021
|
+
var OVERSIZE = /* @__PURE__ */ Symbol("oversize");
|
|
1022
|
+
var readCappedNodeBody = async (req, maxBytes) => {
|
|
1023
|
+
const declared = Number(req.headers["content-length"] ?? 0);
|
|
1024
|
+
if (declared > maxBytes) {
|
|
1025
|
+
return OVERSIZE;
|
|
1026
|
+
}
|
|
1027
|
+
let size = 0;
|
|
1028
|
+
const chunks = [];
|
|
1029
|
+
for await (const chunk of req) {
|
|
1030
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1031
|
+
size += buf.byteLength;
|
|
1032
|
+
if (size > maxBytes) {
|
|
1033
|
+
return OVERSIZE;
|
|
1034
|
+
}
|
|
1035
|
+
chunks.push(buf);
|
|
1036
|
+
}
|
|
1037
|
+
return Buffer.concat(chunks);
|
|
1038
|
+
};
|
|
1039
|
+
var assertStandardSchema = (schema, toolName, field) => {
|
|
1040
|
+
if (schema === void 0) {
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
const standard = schema?.["~standard"];
|
|
1044
|
+
if (typeof standard?.validate !== "function") {
|
|
1045
|
+
throw new UnexpectedStateError(
|
|
1046
|
+
`Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,
|
|
1047
|
+
{ toolName }
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
var promptArgsSchema = (prompt) => {
|
|
1052
|
+
const args = prompt.arguments;
|
|
1053
|
+
if (!args?.length) {
|
|
1054
|
+
return void 0;
|
|
1055
|
+
}
|
|
1056
|
+
const shape = {};
|
|
1057
|
+
for (const arg of args) {
|
|
1058
|
+
const completer = arg.complete ?? (prompt.complete ? (value) => prompt.complete(arg.name, value) : void 0);
|
|
1059
|
+
const valueSchema = arg.enum?.length ? z.enum(arg.enum) : z.string();
|
|
1060
|
+
const described = arg.description ? valueSchema.describe(arg.description) : valueSchema;
|
|
1061
|
+
const base = completer ? completable(
|
|
1062
|
+
described,
|
|
1063
|
+
(async (value) => (await completer(value)).values)
|
|
1064
|
+
) : described;
|
|
1065
|
+
shape[arg.name] = arg.required ? base : base.optional();
|
|
1066
|
+
}
|
|
1067
|
+
return z.object(shape);
|
|
1068
|
+
};
|
|
1069
|
+
var normalizeToolResult = (result) => {
|
|
1070
|
+
if (result === void 0 || result === null) {
|
|
1071
|
+
return { content: [] };
|
|
1072
|
+
}
|
|
1073
|
+
if (typeof result === "string") {
|
|
1074
|
+
return { content: [{ text: result, type: "text" }] };
|
|
1075
|
+
}
|
|
1076
|
+
if (typeof result === "object") {
|
|
1077
|
+
const value = result;
|
|
1078
|
+
if (value.resultType === "input_required" || Array.isArray(value.content)) {
|
|
1079
|
+
return value;
|
|
1080
|
+
}
|
|
1081
|
+
if (value.type === "text" || value.type === "image" || value.type === "audio" || value.type === "resource" || value.type === "resource_link") {
|
|
1082
|
+
return { content: [value] };
|
|
1083
|
+
}
|
|
1084
|
+
return {
|
|
1085
|
+
content: [{ text: JSON.stringify(value), type: "text" }],
|
|
1086
|
+
structuredContent: value
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
return { content: [{ text: String(result), type: "text" }] };
|
|
1090
|
+
};
|
|
1091
|
+
export {
|
|
1092
|
+
AuthProvider,
|
|
1093
|
+
AzureProvider,
|
|
1094
|
+
DiscoveryDocumentCache,
|
|
1095
|
+
GitHubProvider,
|
|
1096
|
+
GoogleProvider,
|
|
1097
|
+
MEDIA_FETCH_TIMEOUT_MS,
|
|
1098
|
+
OAuthProvider,
|
|
1099
|
+
ServerState,
|
|
1100
|
+
UnexpectedStateError,
|
|
1101
|
+
UserError,
|
|
1102
|
+
ViteMCP,
|
|
1103
|
+
ViteMCPError,
|
|
1104
|
+
audioContent,
|
|
1105
|
+
delay,
|
|
1106
|
+
getAuthSession,
|
|
1107
|
+
imageContent,
|
|
1108
|
+
jsonSchemaAdapter,
|
|
1109
|
+
requireAll,
|
|
1110
|
+
requireAny,
|
|
1111
|
+
requireAuth,
|
|
1112
|
+
requireRole,
|
|
1113
|
+
requireScopes
|
|
1114
|
+
};
|
|
1115
|
+
//# sourceMappingURL=ViteMCP.js.map
|