@vitemcp/server 1.6.5 → 1.8.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/README.md +52 -0
- package/dist/ViteMCP.cjs +4 -1320
- package/dist/ViteMCP.cjs.map +1 -1
- package/dist/ViteMCP.js +14 -1330
- package/dist/ViteMCP.js.map +1 -1
- package/dist/auth/index.cjs +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/chunk-2624N2BP.cjs +1351 -0
- package/dist/chunk-2624N2BP.cjs.map +1 -0
- package/dist/chunk-3CGG26M4.js +1351 -0
- package/dist/chunk-3CGG26M4.js.map +1 -0
- package/dist/{chunk-J2FAZRSL.js → chunk-GCCQBATS.js} +12 -3
- package/dist/chunk-GCCQBATS.js.map +1 -0
- package/dist/{chunk-252JIXOL.cjs → chunk-VTEMGFQZ.cjs} +12 -3
- package/dist/chunk-VTEMGFQZ.cjs.map +1 -0
- package/dist/openapi/index.cjs +1020 -0
- package/dist/openapi/index.cjs.map +1 -0
- package/dist/openapi/index.d.cts +142 -0
- package/dist/openapi/index.d.ts +142 -0
- package/dist/openapi/index.js +1020 -0
- package/dist/openapi/index.js.map +1 -0
- package/package.json +18 -2
- package/dist/chunk-252JIXOL.cjs.map +0 -1
- package/dist/chunk-J2FAZRSL.js.map +0 -1
|
@@ -0,0 +1,1351 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; }// src/ViteMCP.ts
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
var _server = require('@modelcontextprotocol/server');
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
var _stdio = require('@modelcontextprotocol/server/stdio');
|
|
20
|
+
var _async_hooks = require('async_hooks');
|
|
21
|
+
var _promises = require('fs/promises');
|
|
22
|
+
var _hono = require('hono');
|
|
23
|
+
var _cors = require('hono/cors');
|
|
24
|
+
var _http = require('http'); var _http2 = _interopRequireDefault(_http);
|
|
25
|
+
var _https = require('https'); var _https2 = _interopRequireDefault(_https);
|
|
26
|
+
var _promises3 = require('timers/promises');
|
|
27
|
+
var _undici = require('undici');
|
|
28
|
+
var _uritemplates = require('uri-templates'); var _uritemplates2 = _interopRequireDefault(_uritemplates);
|
|
29
|
+
var _xsschema = require('xsschema');
|
|
30
|
+
var _zod = require('zod');
|
|
31
|
+
|
|
32
|
+
// src/auth/router.ts
|
|
33
|
+
|
|
34
|
+
var OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;
|
|
35
|
+
var errorResponse = (error) => {
|
|
36
|
+
const err = error;
|
|
37
|
+
return {
|
|
38
|
+
body: _nullishCoalesce(_optionalChain([err, 'access', _ => _.toJSON, 'optionalCall', _2 => _2()]), () => ( { error: "invalid_request" })),
|
|
39
|
+
status: _nullishCoalesce(err.statusCode, () => ( 400))
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
var readCappedBody = async (request) => {
|
|
43
|
+
const declared = request.headers.get("content-length");
|
|
44
|
+
if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (!request.body) {
|
|
48
|
+
try {
|
|
49
|
+
const text = await request.text();
|
|
50
|
+
return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;
|
|
51
|
+
} catch (e) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const reader = request.body.getReader();
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let size = 0;
|
|
58
|
+
try {
|
|
59
|
+
for (; ; ) {
|
|
60
|
+
const { done, value } = await reader.read();
|
|
61
|
+
if (done) {
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
size += value.byteLength;
|
|
65
|
+
if (size > OAUTH_PROXY_MAX_BODY_SIZE) {
|
|
66
|
+
await reader.cancel().catch(() => {
|
|
67
|
+
});
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
chunks.push(value);
|
|
71
|
+
}
|
|
72
|
+
} catch (e2) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
76
|
+
};
|
|
77
|
+
var readJsonBody = async (request) => {
|
|
78
|
+
const text = await readCappedBody(request);
|
|
79
|
+
if (text === null) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(text);
|
|
84
|
+
} catch (e3) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
var tooLarge = {
|
|
89
|
+
error: "invalid_request",
|
|
90
|
+
error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`
|
|
91
|
+
};
|
|
92
|
+
var noStore = {
|
|
93
|
+
"Cache-Control": "no-store",
|
|
94
|
+
Pragma: "no-cache"
|
|
95
|
+
};
|
|
96
|
+
var toSnakeCase = (value) => {
|
|
97
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
return Object.fromEntries(
|
|
101
|
+
Object.entries(value).map(([k, v]) => [
|
|
102
|
+
k.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase(),
|
|
103
|
+
v
|
|
104
|
+
])
|
|
105
|
+
);
|
|
106
|
+
};
|
|
107
|
+
var createOAuthRouter = (options) => {
|
|
108
|
+
const app = new (0, _hono.Hono)();
|
|
109
|
+
const { proxy } = options;
|
|
110
|
+
const basePath = _nullishCoalesce(options.basePath, () => ( ""));
|
|
111
|
+
const endpoint = _nullishCoalesce(options.endpoint, () => ( ""));
|
|
112
|
+
const serve = (path, body) => app.get(path, (c) => c.json(body));
|
|
113
|
+
if (options.authorizationServer) {
|
|
114
|
+
serve(
|
|
115
|
+
`/.well-known/oauth-authorization-server${basePath}`,
|
|
116
|
+
toSnakeCase(options.authorizationServer)
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
if (options.protectedResource) {
|
|
120
|
+
const body = toSnakeCase(options.protectedResource);
|
|
121
|
+
const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;
|
|
122
|
+
serve(scoped, body);
|
|
123
|
+
if (scoped !== "/.well-known/oauth-protected-resource") {
|
|
124
|
+
serve("/.well-known/oauth-protected-resource", body);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (!proxy) {
|
|
128
|
+
return app;
|
|
129
|
+
}
|
|
130
|
+
app.post(`${basePath}/oauth/register`, async (c) => {
|
|
131
|
+
const body = await readJsonBody(c.req.raw);
|
|
132
|
+
if (body === null) {
|
|
133
|
+
return c.json(tooLarge, 400, noStore);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
return c.json(await proxy.registerClient(body), 201, noStore);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
const { body: errBody, status } = errorResponse(error);
|
|
139
|
+
return c.json(errBody, status, noStore);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
app.get(`${basePath}/oauth/authorize`, async (c) => {
|
|
143
|
+
try {
|
|
144
|
+
const params = Object.fromEntries(
|
|
145
|
+
new URL(c.req.url).searchParams.entries()
|
|
146
|
+
);
|
|
147
|
+
return await proxy.authorize(params);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
const { body, status } = errorResponse(error);
|
|
150
|
+
return c.json(body, status);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
app.post(`${basePath}/oauth/token`, async (c) => {
|
|
154
|
+
const raw = c.req.raw;
|
|
155
|
+
const text = await readCappedBody(raw);
|
|
156
|
+
if (text === null) {
|
|
157
|
+
return c.json(tooLarge, 400, noStore);
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const params = Object.fromEntries(new URLSearchParams(text).entries());
|
|
161
|
+
const authHeader = raw.headers.get("authorization");
|
|
162
|
+
if (_optionalChain([authHeader, 'optionalAccess', _3 => _3.toLowerCase, 'call', _4 => _4(), 'access', _5 => _5.startsWith, 'call', _6 => _6("basic ")])) {
|
|
163
|
+
const decoded = Buffer.from(authHeader.slice(6), "base64").toString(
|
|
164
|
+
"utf8"
|
|
165
|
+
);
|
|
166
|
+
const separator = decoded.indexOf(":");
|
|
167
|
+
if (separator !== -1) {
|
|
168
|
+
params.client_id ||= decodeURIComponent(decoded.slice(0, separator));
|
|
169
|
+
params.client_secret ||= decodeURIComponent(
|
|
170
|
+
decoded.slice(separator + 1)
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const result = params.grant_type === "refresh_token" ? await proxy.exchangeRefreshToken(params) : await proxy.exchangeAuthorizationCode(params);
|
|
175
|
+
return c.json(result, 200, noStore);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
const { body, status } = errorResponse(error);
|
|
178
|
+
return c.json(body, status, noStore);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
app.get(
|
|
182
|
+
`${basePath}/oauth/callback`,
|
|
183
|
+
async (c) => proxy.handleCallback(c.req.raw)
|
|
184
|
+
);
|
|
185
|
+
app.all(
|
|
186
|
+
`${basePath}/oauth/consent`,
|
|
187
|
+
async (c) => proxy.handleConsent(c.req.raw)
|
|
188
|
+
);
|
|
189
|
+
return app;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// src/cancelResponseBody.ts
|
|
193
|
+
var cancelResponseBody = async (response) => {
|
|
194
|
+
if (!response.body) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
await response.body.cancel();
|
|
199
|
+
} catch (e4) {
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// src/DiscoveryDocumentCache.ts
|
|
204
|
+
var DiscoveryDocumentCache = class {
|
|
205
|
+
get size() {
|
|
206
|
+
return this.#cache.size;
|
|
207
|
+
}
|
|
208
|
+
#cache = /* @__PURE__ */ new Map();
|
|
209
|
+
#generation = 0;
|
|
210
|
+
#inFlight = /* @__PURE__ */ new Map();
|
|
211
|
+
#timeoutMs;
|
|
212
|
+
#ttl;
|
|
213
|
+
#urlGenerations = /* @__PURE__ */ new Map();
|
|
214
|
+
/**
|
|
215
|
+
* @param options - configuration options
|
|
216
|
+
* @param options.timeoutMs - timeout in miliseconds for the upstream fetch
|
|
217
|
+
* @param options.ttl - time-to-live in miliseconds
|
|
218
|
+
*/
|
|
219
|
+
constructor(options = {}) {
|
|
220
|
+
this.#timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( 1e4));
|
|
221
|
+
this.#ttl = _nullishCoalesce(options.ttl, () => ( 36e5));
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* @param url - optional URL to clear. if omitted, clears all cached documents.
|
|
225
|
+
*/
|
|
226
|
+
clear(url) {
|
|
227
|
+
if (url) {
|
|
228
|
+
this.#cache.delete(url);
|
|
229
|
+
this.#inFlight.delete(url);
|
|
230
|
+
this.#urlGenerations.set(url, (_nullishCoalesce(this.#urlGenerations.get(url), () => ( 0))) + 1);
|
|
231
|
+
} else {
|
|
232
|
+
this.#cache.clear();
|
|
233
|
+
this.#inFlight.clear();
|
|
234
|
+
this.#urlGenerations.clear();
|
|
235
|
+
this.#generation++;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* fetches a discovery document from the given URL.
|
|
240
|
+
* uses cached value if available and not expired.
|
|
241
|
+
* coalesces concurrent requests for the same URL to prevent duplicate fetches.
|
|
242
|
+
*
|
|
243
|
+
* @param url - the discovery document URL (e.g., /.well-known/openid-configuration)
|
|
244
|
+
* @returns the discovery document as a JSON object
|
|
245
|
+
* @throws Error if the fetch fails or returns non-OK status
|
|
246
|
+
*/
|
|
247
|
+
async get(url) {
|
|
248
|
+
const now = Date.now();
|
|
249
|
+
const cached = this.#cache.get(url);
|
|
250
|
+
if (cached && cached.expiresAt > now) {
|
|
251
|
+
return cached.data;
|
|
252
|
+
}
|
|
253
|
+
const inFlight = this.#inFlight.get(url);
|
|
254
|
+
if (inFlight) {
|
|
255
|
+
return inFlight;
|
|
256
|
+
}
|
|
257
|
+
const fetchPromise = this.#fetchAndCache(
|
|
258
|
+
url,
|
|
259
|
+
this.#generation,
|
|
260
|
+
_nullishCoalesce(this.#urlGenerations.get(url), () => ( 0))
|
|
261
|
+
);
|
|
262
|
+
this.#inFlight.set(url, fetchPromise);
|
|
263
|
+
try {
|
|
264
|
+
const data = await fetchPromise;
|
|
265
|
+
return data;
|
|
266
|
+
} finally {
|
|
267
|
+
if (this.#inFlight.get(url) === fetchPromise) {
|
|
268
|
+
this.#inFlight.delete(url);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* @param url - the URL to check
|
|
274
|
+
* @returns true if the URL is cached and nott expired
|
|
275
|
+
*/
|
|
276
|
+
has(url) {
|
|
277
|
+
const cached = this.#cache.get(url);
|
|
278
|
+
if (!cached) {
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
if (cached.expiresAt <= now) {
|
|
283
|
+
this.#cache.delete(url);
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
async #fetchAndCache(url, generation, urlGeneration) {
|
|
289
|
+
let res;
|
|
290
|
+
try {
|
|
291
|
+
res = await fetch(url, {
|
|
292
|
+
signal: AbortSignal.timeout(this.#timeoutMs)
|
|
293
|
+
});
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
`Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
if (!res.ok) {
|
|
303
|
+
await cancelResponseBody(res);
|
|
304
|
+
throw new Error(
|
|
305
|
+
`Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
const data = await res.json();
|
|
309
|
+
const expiresAt = Date.now() + this.#ttl;
|
|
310
|
+
if (this.#generation === generation && (_nullishCoalesce(this.#urlGenerations.get(url), () => ( 0))) === urlGeneration) {
|
|
311
|
+
this.#cache.set(url, {
|
|
312
|
+
data,
|
|
313
|
+
expiresAt
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return data;
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// src/jsonSchemaAdapter.ts
|
|
321
|
+
function jsonSchemaAdapter(schema) {
|
|
322
|
+
let compiled;
|
|
323
|
+
const getValidator = () => {
|
|
324
|
+
compiled ??= compileSchema(schema).catch((error) => {
|
|
325
|
+
compiled = void 0;
|
|
326
|
+
throw error;
|
|
327
|
+
});
|
|
328
|
+
return compiled;
|
|
329
|
+
};
|
|
330
|
+
return {
|
|
331
|
+
"~standard": {
|
|
332
|
+
jsonSchema: {
|
|
333
|
+
input: () => schema,
|
|
334
|
+
output: () => schema
|
|
335
|
+
},
|
|
336
|
+
validate: async (data) => {
|
|
337
|
+
const validate = await getValidator();
|
|
338
|
+
if (validate(data)) {
|
|
339
|
+
return { value: data };
|
|
340
|
+
}
|
|
341
|
+
return { issues: (_nullishCoalesce(validate.errors, () => ( []))).map(toIssue) };
|
|
342
|
+
},
|
|
343
|
+
vendor: "json-schema",
|
|
344
|
+
version: 1
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
async function compileSchema(schema) {
|
|
349
|
+
let ajvModule;
|
|
350
|
+
try {
|
|
351
|
+
ajvModule = await Promise.resolve().then(() => _interopRequireWildcard(require("ajv")));
|
|
352
|
+
} catch (e5) {
|
|
353
|
+
throw new Error(
|
|
354
|
+
'The "ajv" package is required to validate JSON Schema tool parameters. Install it with: npm install ajv'
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
const Ajv = unwrapDefault(unwrapDefault(ajvModule));
|
|
358
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
359
|
+
try {
|
|
360
|
+
const formatsModule = await Promise.resolve().then(() => _interopRequireWildcard(require("ajv-formats")));
|
|
361
|
+
const addFormats = unwrapDefault(
|
|
362
|
+
unwrapDefault(formatsModule)
|
|
363
|
+
);
|
|
364
|
+
addFormats(ajv);
|
|
365
|
+
} catch (e6) {
|
|
366
|
+
}
|
|
367
|
+
return ajv.compile(schema);
|
|
368
|
+
}
|
|
369
|
+
function toIssue(error) {
|
|
370
|
+
const path = error.instancePath.split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).map((segment) => {
|
|
371
|
+
const index = Number(segment);
|
|
372
|
+
return /^(?:0|[1-9]\d*)$/.test(segment) && Number.isSafeInteger(index) ? index : segment;
|
|
373
|
+
});
|
|
374
|
+
const missingProperty = _optionalChain([error, 'access', _7 => _7.params, 'optionalAccess', _8 => _8.missingProperty]);
|
|
375
|
+
if (error.keyword === "required" && typeof missingProperty === "string") {
|
|
376
|
+
path.push(missingProperty);
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
message: error.message || "Validation error",
|
|
380
|
+
path
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function unwrapDefault(value) {
|
|
384
|
+
return typeof value === "object" && value !== null && "default" in value ? value.default : value;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// src/ViteMCP.ts
|
|
388
|
+
var MEDIA_FETCH_TIMEOUT_MS = 3e4;
|
|
389
|
+
var ViteMCPError = class extends Error {
|
|
390
|
+
constructor(message) {
|
|
391
|
+
super(message);
|
|
392
|
+
this.name = new.target.name;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
var UnexpectedStateError = class extends ViteMCPError {
|
|
396
|
+
|
|
397
|
+
constructor(message, extras) {
|
|
398
|
+
super(message);
|
|
399
|
+
this.name = new.target.name;
|
|
400
|
+
this.extras = extras;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
var UserError = class extends UnexpectedStateError {
|
|
404
|
+
};
|
|
405
|
+
var readMedia = async (source, kind) => {
|
|
406
|
+
let rawData;
|
|
407
|
+
try {
|
|
408
|
+
if ("url" in source) {
|
|
409
|
+
const response = await _undici.fetch.call(void 0, source.url, {
|
|
410
|
+
signal: AbortSignal.timeout(_nullishCoalesce(source.timeoutMs, () => ( MEDIA_FETCH_TIMEOUT_MS)))
|
|
411
|
+
});
|
|
412
|
+
if (!response.ok) {
|
|
413
|
+
await cancelResponseBody(response);
|
|
414
|
+
throw new Error(`Server responded with status: ${response.status}`);
|
|
415
|
+
}
|
|
416
|
+
rawData = Buffer.from(await response.arrayBuffer());
|
|
417
|
+
} else if ("path" in source) {
|
|
418
|
+
rawData = await _promises.readFile.call(void 0, source.path);
|
|
419
|
+
} else if ("buffer" in source) {
|
|
420
|
+
rawData = source.buffer;
|
|
421
|
+
} else {
|
|
422
|
+
throw new Error(
|
|
423
|
+
`Invalid ${kind} source: provide one of url, path, or buffer`
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
} catch (error) {
|
|
427
|
+
if ("url" in source) {
|
|
428
|
+
const reason = error instanceof Error && error.name === "TimeoutError" ? `timed out after ${_nullishCoalesce(source.timeoutMs, () => ( MEDIA_FETCH_TIMEOUT_MS))}ms` : error instanceof Error ? error.message : String(error);
|
|
429
|
+
throw new Error(
|
|
430
|
+
`Failed to fetch ${kind} from URL (${source.url}): ${reason}`
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
if (error instanceof Error) {
|
|
434
|
+
throw error;
|
|
435
|
+
}
|
|
436
|
+
throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);
|
|
437
|
+
}
|
|
438
|
+
const { fileTypeFromBuffer } = await Promise.resolve().then(() => _interopRequireWildcard(require("file-type")));
|
|
439
|
+
const mimeType = await fileTypeFromBuffer(rawData);
|
|
440
|
+
return {
|
|
441
|
+
data: rawData.toString("base64"),
|
|
442
|
+
mimeType: _nullishCoalesce(_optionalChain([mimeType, 'optionalAccess', _9 => _9.mime]), () => ( (kind === "image" ? "image/png" : "audio/mpeg")))
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
var imageContent = async (source) => {
|
|
446
|
+
const { data, mimeType } = await readMedia(source, "image");
|
|
447
|
+
return { data, mimeType, type: "image" };
|
|
448
|
+
};
|
|
449
|
+
var audioContent = async (source) => {
|
|
450
|
+
const { data, mimeType } = await readMedia(source, "audio");
|
|
451
|
+
return { data, mimeType, type: "audio" };
|
|
452
|
+
};
|
|
453
|
+
var ServerState = /* @__PURE__ */ ((ServerState2) => {
|
|
454
|
+
ServerState2["Error"] = "error";
|
|
455
|
+
ServerState2["Running"] = "running";
|
|
456
|
+
ServerState2["Starting"] = "starting";
|
|
457
|
+
ServerState2["Stopped"] = "stopped";
|
|
458
|
+
return ServerState2;
|
|
459
|
+
})(ServerState || {});
|
|
460
|
+
var ViteMCP = class {
|
|
461
|
+
/**
|
|
462
|
+
* The `auth` provider this server was constructed with, or `undefined` when
|
|
463
|
+
* OAuth was configured through the `oauth` option instead (or not at all).
|
|
464
|
+
*
|
|
465
|
+
* Exposed so a caller who inlined the provider into the options — the way
|
|
466
|
+
* every example does — can still reach it at shutdown. The provider holds an
|
|
467
|
+
* `OAuthProxy` with two cleanup timers, and `stop()` deliberately leaves them
|
|
468
|
+
* running: the server does not own the provider, and a stopped server can be
|
|
469
|
+
* started again. Terminal teardown is therefore the caller's call:
|
|
470
|
+
*
|
|
471
|
+
* ```ts
|
|
472
|
+
* await server.stop();
|
|
473
|
+
* server.authProvider?.destroy();
|
|
474
|
+
* ```
|
|
475
|
+
*
|
|
476
|
+
* In that order — `destroy()` is terminal, and a request still draining would
|
|
477
|
+
* throw against a destroyed provider.
|
|
478
|
+
*/
|
|
479
|
+
get authProvider() {
|
|
480
|
+
return this.#options.auth;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* The port the HTTP server is actually listening on, or `null` when it is
|
|
484
|
+
* not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a
|
|
485
|
+
* free port and read it back here — this avoids the race inherent in
|
|
486
|
+
* picking a port first and binding it afterwards.
|
|
487
|
+
*/
|
|
488
|
+
get port() {
|
|
489
|
+
const address = _optionalChain([this, 'access', _10 => _10.#httpServer, 'optionalAccess', _11 => _11.address, 'call', _12 => _12()]);
|
|
490
|
+
return address && typeof address === "object" ? address.port : null;
|
|
491
|
+
}
|
|
492
|
+
get serverState() {
|
|
493
|
+
return this.#serverState;
|
|
494
|
+
}
|
|
495
|
+
#authenticate;
|
|
496
|
+
/**
|
|
497
|
+
* Carries the `authenticate` result from the HTTP route into the per-request
|
|
498
|
+
* server factory. The SDK invokes that factory from within `handler.fetch`,
|
|
499
|
+
* so the running store is always the one this request established — whereas
|
|
500
|
+
* a field on `this` would be shared by every concurrent request.
|
|
501
|
+
*/
|
|
502
|
+
#authStore = new (0, _async_hooks.AsyncLocalStorage)();
|
|
503
|
+
#connectedServers = [];
|
|
504
|
+
#corsMiddleware = null;
|
|
505
|
+
#handler = null;
|
|
506
|
+
#honoApp = new (0, _hono.Hono)();
|
|
507
|
+
#httpServer = null;
|
|
508
|
+
#logger;
|
|
509
|
+
#options;
|
|
510
|
+
#prompts = [];
|
|
511
|
+
#resources = [];
|
|
512
|
+
#resourceTemplates = [];
|
|
513
|
+
#serverState = "stopped" /* Stopped */;
|
|
514
|
+
/**
|
|
515
|
+
* Whether this server publishes an RFC 9728 protected-resource document, and
|
|
516
|
+
* so whether a 401 can point a client at it. Latched when the routes are
|
|
517
|
+
* mounted rather than read back from `auth` per rejection: the provider's
|
|
518
|
+
* config getter builds its proxy on demand and refuses once destroyed.
|
|
519
|
+
*/
|
|
520
|
+
#servesProtectedResourceMetadata = false;
|
|
521
|
+
#stdioHandle = null;
|
|
522
|
+
#tools = [];
|
|
523
|
+
constructor(options) {
|
|
524
|
+
this.#options = options;
|
|
525
|
+
this.#logger = _nullishCoalesce(options.logger, () => ( console));
|
|
526
|
+
const provider = options.auth;
|
|
527
|
+
this.#authenticate = _nullishCoalesce(options.authenticate, () => ( (provider ? ((request) => provider.authenticate(request)) : void 0)));
|
|
528
|
+
this.#honoApp = this.#freshApp();
|
|
529
|
+
}
|
|
530
|
+
addPrompt(prompt) {
|
|
531
|
+
this.#prompts.push(prompt);
|
|
532
|
+
this.#notifyListChanged("prompts");
|
|
533
|
+
}
|
|
534
|
+
addPrompts(prompts) {
|
|
535
|
+
for (const prompt of prompts) {
|
|
536
|
+
this.#prompts.push(prompt);
|
|
537
|
+
}
|
|
538
|
+
this.#notifyListChanged("prompts");
|
|
539
|
+
}
|
|
540
|
+
addResource(resource) {
|
|
541
|
+
this.#resources.push(resource);
|
|
542
|
+
this.#notifyListChanged("resources");
|
|
543
|
+
}
|
|
544
|
+
addResources(resources) {
|
|
545
|
+
for (const resource of resources) {
|
|
546
|
+
this.#resources.push(resource);
|
|
547
|
+
}
|
|
548
|
+
this.#notifyListChanged("resources");
|
|
549
|
+
}
|
|
550
|
+
addResourceTemplate(template) {
|
|
551
|
+
this.#resourceTemplates.push(template);
|
|
552
|
+
this.#notifyListChanged("resources");
|
|
553
|
+
}
|
|
554
|
+
addResourceTemplates(templates) {
|
|
555
|
+
for (const template of templates) {
|
|
556
|
+
this.#resourceTemplates.push(template);
|
|
557
|
+
}
|
|
558
|
+
this.#notifyListChanged("resources");
|
|
559
|
+
}
|
|
560
|
+
addTool(tool) {
|
|
561
|
+
assertStandardSchema(tool.parameters, tool.name, "parameters");
|
|
562
|
+
assertStandardSchema(tool.outputSchema, tool.name, "outputSchema");
|
|
563
|
+
this.#tools.push(tool);
|
|
564
|
+
this.#notifyListChanged("tools");
|
|
565
|
+
}
|
|
566
|
+
addTools(tools) {
|
|
567
|
+
for (const tool of tools) {
|
|
568
|
+
assertStandardSchema(tool.parameters, tool.name, "parameters");
|
|
569
|
+
assertStandardSchema(tool.outputSchema, tool.name, "outputSchema");
|
|
570
|
+
this.#tools.push(tool);
|
|
571
|
+
}
|
|
572
|
+
this.#notifyListChanged("tools");
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Connects the server to an arbitrary transport — used for in-memory unit
|
|
576
|
+
* testing, where a linked transport pair replaces a real socket.
|
|
577
|
+
*/
|
|
578
|
+
async connect(transport) {
|
|
579
|
+
const server = await this.#buildServer(void 0);
|
|
580
|
+
await server.connect(transport);
|
|
581
|
+
this.#connectedServers.push(server);
|
|
582
|
+
this.#serverState = "running" /* Running */;
|
|
583
|
+
return server;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Resolves a resource (or resource template) URI to an embeddable resource
|
|
587
|
+
* body, for returning inline from a tool.
|
|
588
|
+
*/
|
|
589
|
+
async embedded(uri) {
|
|
590
|
+
const direct = this.#resources.find((resource) => resource.uri === uri);
|
|
591
|
+
if (direct) {
|
|
592
|
+
const loaded = await direct.load(
|
|
593
|
+
this.#makeContext(void 0, void 0).context
|
|
594
|
+
);
|
|
595
|
+
const first = Array.isArray(loaded) ? loaded[0] : loaded;
|
|
596
|
+
if (!first) {
|
|
597
|
+
throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {
|
|
598
|
+
uri
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
return { ...first, mimeType: _nullishCoalesce(first.mimeType, () => ( direct.mimeType)), uri };
|
|
602
|
+
}
|
|
603
|
+
for (const template of this.#resourceTemplates) {
|
|
604
|
+
const params = _uritemplates2.default.call(void 0, template.uriTemplate).fromUri(uri);
|
|
605
|
+
if (!params) {
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const loaded = await template.load(
|
|
609
|
+
params,
|
|
610
|
+
this.#makeContext(void 0, void 0).context
|
|
611
|
+
);
|
|
612
|
+
const first = Array.isArray(loaded) ? loaded[0] : loaded;
|
|
613
|
+
if (!first) {
|
|
614
|
+
throw new UnexpectedStateError(
|
|
615
|
+
`Resource template loaded no content: ${uri}`,
|
|
616
|
+
{ uri }
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return { ...first, mimeType: _nullishCoalesce(first.mimeType, () => ( template.mimeType)), uri };
|
|
620
|
+
}
|
|
621
|
+
throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });
|
|
622
|
+
}
|
|
623
|
+
/** The Hono app serving the HTTP transport, for mounting custom routes. */
|
|
624
|
+
getApp() {
|
|
625
|
+
return this.#honoApp;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Publishes `notifications/resources/updated` for a URI to any subscription
|
|
629
|
+
* that opted in to it.
|
|
630
|
+
*/
|
|
631
|
+
notifyResourceUpdated(uri) {
|
|
632
|
+
_optionalChain([this, 'access', _13 => _13.#handler, 'optionalAccess', _14 => _14.notify, 'access', _15 => _15.resourceUpdated, 'call', _16 => _16(uri)]);
|
|
633
|
+
}
|
|
634
|
+
removePrompt(name) {
|
|
635
|
+
this.#prompts = this.#prompts.filter((p) => p.name !== name);
|
|
636
|
+
this.#notifyListChanged("prompts");
|
|
637
|
+
}
|
|
638
|
+
removePrompts(names) {
|
|
639
|
+
this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));
|
|
640
|
+
this.#notifyListChanged("prompts");
|
|
641
|
+
}
|
|
642
|
+
removeResource(name) {
|
|
643
|
+
this.#resources = this.#resources.filter((r) => r.name !== name);
|
|
644
|
+
this.#notifyListChanged("resources");
|
|
645
|
+
}
|
|
646
|
+
removeResources(names) {
|
|
647
|
+
this.#resources = this.#resources.filter((r) => !names.includes(r.name));
|
|
648
|
+
this.#notifyListChanged("resources");
|
|
649
|
+
}
|
|
650
|
+
removeResourceTemplate(name) {
|
|
651
|
+
this.#resourceTemplates = this.#resourceTemplates.filter(
|
|
652
|
+
(r) => r.name !== name
|
|
653
|
+
);
|
|
654
|
+
this.#notifyListChanged("resources");
|
|
655
|
+
}
|
|
656
|
+
removeResourceTemplates(names) {
|
|
657
|
+
this.#resourceTemplates = this.#resourceTemplates.filter(
|
|
658
|
+
(r) => !names.includes(r.name)
|
|
659
|
+
);
|
|
660
|
+
this.#notifyListChanged("resources");
|
|
661
|
+
}
|
|
662
|
+
removeTool(name) {
|
|
663
|
+
this.#tools = this.#tools.filter((t) => t.name !== name);
|
|
664
|
+
this.#notifyListChanged("tools");
|
|
665
|
+
}
|
|
666
|
+
removeTools(names) {
|
|
667
|
+
this.#tools = this.#tools.filter((t) => !names.includes(t.name));
|
|
668
|
+
this.#notifyListChanged("tools");
|
|
669
|
+
}
|
|
670
|
+
async start(options) {
|
|
671
|
+
this.#serverState = "starting" /* Starting */;
|
|
672
|
+
try {
|
|
673
|
+
if (options.transportType === "stdio") {
|
|
674
|
+
this.#stdioHandle = _stdio.serveStdio.call(void 0, () => this.#buildServer(void 0));
|
|
675
|
+
this.#logger.info(`[ViteMCP info] server is running on stdio`);
|
|
676
|
+
} else {
|
|
677
|
+
await this.#startHttp(options.httpStream);
|
|
678
|
+
}
|
|
679
|
+
this.#serverState = "running" /* Running */;
|
|
680
|
+
} catch (error) {
|
|
681
|
+
this.#serverState = "error" /* Error */;
|
|
682
|
+
throw error;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
async stop() {
|
|
686
|
+
this.#honoApp = this.#freshApp();
|
|
687
|
+
this.#corsMiddleware = null;
|
|
688
|
+
for (const server of this.#connectedServers) {
|
|
689
|
+
await server.close().catch(() => {
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
this.#connectedServers = [];
|
|
693
|
+
await _optionalChain([this, 'access', _17 => _17.#stdioHandle, 'optionalAccess', _18 => _18.close, 'optionalCall', _19 => _19()]);
|
|
694
|
+
this.#stdioHandle = null;
|
|
695
|
+
await _optionalChain([this, 'access', _20 => _20.#handler, 'optionalAccess', _21 => _21.close, 'call', _22 => _22()]);
|
|
696
|
+
this.#handler = null;
|
|
697
|
+
if (this.#httpServer) {
|
|
698
|
+
await new Promise(
|
|
699
|
+
(resolve) => this.#httpServer.close(() => resolve())
|
|
700
|
+
);
|
|
701
|
+
this.#httpServer = null;
|
|
702
|
+
}
|
|
703
|
+
this.#serverState = "stopped" /* Stopped */;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Runs the `authenticate` hook and decides whether the exchange may proceed,
|
|
707
|
+
* returning either the store to run it under or the `Response` refusing it.
|
|
708
|
+
*
|
|
709
|
+
* Deliberately *not* done inside the per-request server factory: that
|
|
710
|
+
* factory's only return channel is an `McpServer`, so a refusal raised there
|
|
711
|
+
* is indistinguishable from a crash and reaches the client as a 500 with no
|
|
712
|
+
* `WWW-Authenticate` — the one header that tells an MCP client where to log
|
|
713
|
+
* in. Doing it here also covers the legacy fallback, which shares the same
|
|
714
|
+
* route, so no transport can be reached without passing this.
|
|
715
|
+
*/
|
|
716
|
+
async #authenticateRequest(request) {
|
|
717
|
+
if (!this.#authenticate) {
|
|
718
|
+
return { auth: void 0 };
|
|
719
|
+
}
|
|
720
|
+
let auth;
|
|
721
|
+
try {
|
|
722
|
+
auth = await this.#authenticate(request);
|
|
723
|
+
} catch (error) {
|
|
724
|
+
if (error instanceof Response) {
|
|
725
|
+
return error;
|
|
726
|
+
}
|
|
727
|
+
this.#logger.error("[ViteMCP error]", error);
|
|
728
|
+
return _server.bearerAuthChallengeResponse.call(void 0,
|
|
729
|
+
new (0, _server.OAuthError)(_server.OAuthErrorCode.ServerError, "Internal Server Error")
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
if (!auth) {
|
|
733
|
+
return this.#options.allowAnonymous ? { auth: void 0 } : this.#unauthorized(request);
|
|
734
|
+
}
|
|
735
|
+
return { auth };
|
|
736
|
+
}
|
|
737
|
+
async #buildServer(auth) {
|
|
738
|
+
const server = new (0, _server.McpServer)(
|
|
739
|
+
{
|
|
740
|
+
description: this.#options.description,
|
|
741
|
+
icons: this.#options.icons,
|
|
742
|
+
name: this.#options.name,
|
|
743
|
+
title: this.#options.title,
|
|
744
|
+
version: this.#options.version,
|
|
745
|
+
websiteUrl: this.#options.websiteUrl
|
|
746
|
+
},
|
|
747
|
+
{ instructions: this.#options.instructions }
|
|
748
|
+
);
|
|
749
|
+
for (const tool of this.#tools) {
|
|
750
|
+
if (tool.canAccess && !tool.canAccess(auth)) {
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
server.registerTool(
|
|
754
|
+
tool.name,
|
|
755
|
+
{
|
|
756
|
+
_meta: tool._meta,
|
|
757
|
+
annotations: tool.annotations,
|
|
758
|
+
description: tool.description,
|
|
759
|
+
inputSchema: await this.#toSdkSchema(
|
|
760
|
+
tool.parameters,
|
|
761
|
+
`Tool "${tool.name}" parameters`
|
|
762
|
+
),
|
|
763
|
+
outputSchema: await this.#toSdkSchema(
|
|
764
|
+
tool.outputSchema,
|
|
765
|
+
`Tool "${tool.name}" outputSchema`
|
|
766
|
+
)
|
|
767
|
+
},
|
|
768
|
+
(async (args, ctx) => {
|
|
769
|
+
const timeout = tool.timeoutMs ? { controller: new AbortController(), ms: tool.timeoutMs } : void 0;
|
|
770
|
+
const { context, release } = this.#makeContext(
|
|
771
|
+
auth,
|
|
772
|
+
ctx,
|
|
773
|
+
_optionalChain([timeout, 'optionalAccess', _23 => _23.controller, 'access', _24 => _24.signal])
|
|
774
|
+
);
|
|
775
|
+
try {
|
|
776
|
+
const result = await (timeout ? withTimeout(tool.execute(args, context), timeout, tool.name) : tool.execute(args, context));
|
|
777
|
+
return normalizeToolResult(result, tool.outputSchema !== void 0);
|
|
778
|
+
} catch (error) {
|
|
779
|
+
if (error instanceof UserError) {
|
|
780
|
+
return {
|
|
781
|
+
content: [{ text: error.message, type: "text" }],
|
|
782
|
+
isError: true,
|
|
783
|
+
...error.extras ? { structuredContent: error.extras } : {}
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
throw error;
|
|
787
|
+
} finally {
|
|
788
|
+
release();
|
|
789
|
+
}
|
|
790
|
+
})
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
for (const resource of this.#resources) {
|
|
794
|
+
if (resource.canAccess && !resource.canAccess(auth)) {
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
server.registerResource(
|
|
798
|
+
resource.name,
|
|
799
|
+
resource.uri,
|
|
800
|
+
{
|
|
801
|
+
cacheHint: resource.cache,
|
|
802
|
+
description: resource.description,
|
|
803
|
+
mimeType: resource.mimeType
|
|
804
|
+
},
|
|
805
|
+
(async (uri, ctx) => {
|
|
806
|
+
const { context, release } = this.#makeContext(auth, ctx);
|
|
807
|
+
try {
|
|
808
|
+
const loaded = await resource.load(context);
|
|
809
|
+
const bodies = Array.isArray(loaded) ? loaded : [loaded];
|
|
810
|
+
return {
|
|
811
|
+
contents: bodies.map((body) => ({
|
|
812
|
+
...body,
|
|
813
|
+
mimeType: _nullishCoalesce(body.mimeType, () => ( resource.mimeType)),
|
|
814
|
+
uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
|
|
815
|
+
}))
|
|
816
|
+
};
|
|
817
|
+
} finally {
|
|
818
|
+
release();
|
|
819
|
+
}
|
|
820
|
+
})
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
for (const template of this.#resourceTemplates) {
|
|
824
|
+
if (template.canAccess && !template.canAccess(auth)) {
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
const complete = {};
|
|
828
|
+
for (const arg of _nullishCoalesce(template.arguments, () => ( []))) {
|
|
829
|
+
const completer = _nullishCoalesce(arg.complete, () => ( (template.complete ? (value) => template.complete(arg.name, value) : void 0)));
|
|
830
|
+
if (completer) {
|
|
831
|
+
complete[arg.name] = async (value) => (await completer(value)).values;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
server.registerResource(
|
|
835
|
+
template.name,
|
|
836
|
+
new (0, _server.ResourceTemplate)(template.uriTemplate, {
|
|
837
|
+
complete,
|
|
838
|
+
list: void 0
|
|
839
|
+
}),
|
|
840
|
+
{
|
|
841
|
+
cacheHint: template.cache,
|
|
842
|
+
description: template.description,
|
|
843
|
+
mimeType: template.mimeType
|
|
844
|
+
},
|
|
845
|
+
(async (uri, args, ctx) => {
|
|
846
|
+
const { context, release } = this.#makeContext(auth, ctx);
|
|
847
|
+
try {
|
|
848
|
+
const loaded = await template.load(_nullishCoalesce(args, () => ( {})), context);
|
|
849
|
+
const bodies = Array.isArray(loaded) ? loaded : [loaded];
|
|
850
|
+
return {
|
|
851
|
+
contents: bodies.map((body) => ({
|
|
852
|
+
...body,
|
|
853
|
+
mimeType: _nullishCoalesce(body.mimeType, () => ( template.mimeType)),
|
|
854
|
+
uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
|
|
855
|
+
}))
|
|
856
|
+
};
|
|
857
|
+
} finally {
|
|
858
|
+
release();
|
|
859
|
+
}
|
|
860
|
+
})
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
for (const prompt of this.#prompts) {
|
|
864
|
+
if (prompt.canAccess && !prompt.canAccess(auth)) {
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
server.registerPrompt(
|
|
868
|
+
prompt.name,
|
|
869
|
+
{
|
|
870
|
+
argsSchema: promptArgsSchema(prompt),
|
|
871
|
+
description: prompt.description
|
|
872
|
+
},
|
|
873
|
+
(async (args, ctx) => {
|
|
874
|
+
const { context, release } = this.#makeContext(auth, ctx);
|
|
875
|
+
try {
|
|
876
|
+
const loaded = await prompt.load(_nullishCoalesce(args, () => ( {})), context);
|
|
877
|
+
if (typeof loaded !== "string") {
|
|
878
|
+
return loaded;
|
|
879
|
+
}
|
|
880
|
+
return {
|
|
881
|
+
messages: [
|
|
882
|
+
{
|
|
883
|
+
content: { text: loaded, type: "text" },
|
|
884
|
+
role: "user"
|
|
885
|
+
}
|
|
886
|
+
]
|
|
887
|
+
};
|
|
888
|
+
} finally {
|
|
889
|
+
release();
|
|
890
|
+
}
|
|
891
|
+
})
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
return server;
|
|
895
|
+
}
|
|
896
|
+
/** Builds the Hono app with the CORS shim installed ahead of user routes. */
|
|
897
|
+
#freshApp() {
|
|
898
|
+
const app = new (0, _hono.Hono)();
|
|
899
|
+
app.use(
|
|
900
|
+
"*",
|
|
901
|
+
(c, next) => this.#corsMiddleware ? this.#corsMiddleware(c, next) : next()
|
|
902
|
+
);
|
|
903
|
+
return app;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Bridges the v2 per-request context onto ViteMCP's `Context`.
|
|
907
|
+
*
|
|
908
|
+
* `timeoutSignal` is folded into `context.signal` for a tool that declares
|
|
909
|
+
* `timeoutMs`; everything else mirrors the SDK's request signal alone. Call
|
|
910
|
+
* `release()` once the handler has settled — see {@link requestScope}.
|
|
911
|
+
*/
|
|
912
|
+
#makeContext(auth, rawCtx, timeoutSignal) {
|
|
913
|
+
const ctx = rawCtx;
|
|
914
|
+
const mcpReq = _optionalChain([ctx, 'optionalAccess', _25 => _25.mcpReq]);
|
|
915
|
+
const requestedLevel = _optionalChain([mcpReq, 'optionalAccess', _26 => _26._meta, 'optionalAccess', _27 => _27["io.modelcontextprotocol/logLevel"]]);
|
|
916
|
+
const emit = (level, message, data) => {
|
|
917
|
+
if (!requestedLevel) {
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
void _optionalChain([mcpReq, 'optionalAccess', _28 => _28.notify, 'optionalCall', _29 => _29({
|
|
921
|
+
method: "notifications/message",
|
|
922
|
+
params: { data: { context: data, message }, level }
|
|
923
|
+
}), 'optionalAccess', _30 => _30.catch, 'call', _31 => _31(() => {
|
|
924
|
+
})]);
|
|
925
|
+
};
|
|
926
|
+
const scope = requestScope(_optionalChain([mcpReq, 'optionalAccess', _32 => _32.signal]), timeoutSignal);
|
|
927
|
+
return {
|
|
928
|
+
context: {
|
|
929
|
+
auth,
|
|
930
|
+
elicit: (params) => _server.inputRequired.elicit({
|
|
931
|
+
message: params.message,
|
|
932
|
+
requestedSchema: params.requestedSchema
|
|
933
|
+
}),
|
|
934
|
+
input: (key, schema) => _server.acceptedContent.call(void 0,
|
|
935
|
+
_optionalChain([mcpReq, 'optionalAccess', _33 => _33.inputResponses]),
|
|
936
|
+
key,
|
|
937
|
+
schema
|
|
938
|
+
),
|
|
939
|
+
inputRequired: (inputRequests, requestState) => _server.inputRequired.call(void 0, { inputRequests, requestState }),
|
|
940
|
+
inputResponses: _optionalChain([mcpReq, 'optionalAccess', _34 => _34.inputResponses]),
|
|
941
|
+
log: {
|
|
942
|
+
debug: (m, d) => emit("debug", m, d),
|
|
943
|
+
error: (m, d) => emit("error", m, d),
|
|
944
|
+
info: (m, d) => emit("info", m, d),
|
|
945
|
+
warn: (m, d) => emit("warning", m, d)
|
|
946
|
+
},
|
|
947
|
+
reportProgress: async (progress) => {
|
|
948
|
+
const progressToken = _optionalChain([mcpReq, 'optionalAccess', _35 => _35._meta, 'optionalAccess', _36 => _36.progressToken]);
|
|
949
|
+
if (progressToken === void 0) {
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
await _optionalChain([mcpReq, 'optionalAccess', _37 => _37.notify, 'optionalCall', _38 => _38({
|
|
953
|
+
method: "notifications/progress",
|
|
954
|
+
params: {
|
|
955
|
+
message: progress.message,
|
|
956
|
+
progress: progress.progress,
|
|
957
|
+
progressToken,
|
|
958
|
+
total: progress.total
|
|
959
|
+
}
|
|
960
|
+
})]);
|
|
961
|
+
},
|
|
962
|
+
requestId: _optionalChain([mcpReq, 'optionalAccess', _39 => _39.id]),
|
|
963
|
+
// The SDK exposes this as an accessor; call it so callers get the
|
|
964
|
+
// value.
|
|
965
|
+
requestState: _optionalChain([mcpReq, 'optionalAccess', _40 => _40.requestState, 'optionalCall', _41 => _41()]),
|
|
966
|
+
signal: scope.signal
|
|
967
|
+
},
|
|
968
|
+
release: scope.release
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Publishes a change event to any open `subscriptions/listen` stream. This
|
|
973
|
+
* replaces the 2025-era `notifications/*_list_changed` broadcast, which had
|
|
974
|
+
* no addressee on a stateless transport.
|
|
975
|
+
*/
|
|
976
|
+
#notifyListChanged(kind) {
|
|
977
|
+
const notifier = _optionalChain([this, 'access', _42 => _42.#handler, 'optionalAccess', _43 => _43.notify]);
|
|
978
|
+
if (!notifier) {
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (kind === "tools") notifier.toolsChanged();
|
|
982
|
+
if (kind === "prompts") notifier.promptsChanged();
|
|
983
|
+
if (kind === "resources") notifier.resourcesChanged();
|
|
984
|
+
}
|
|
985
|
+
async #startHttp(config) {
|
|
986
|
+
this.#handler = _server.createMcpHandler.call(void 0,
|
|
987
|
+
// Authentication has already run in the route below, which is the only
|
|
988
|
+
// place that can turn a refusal into an HTTP status. What reaches here
|
|
989
|
+
// is either an authenticated session or a deliberately anonymous one.
|
|
990
|
+
async () => this.#buildServer(_optionalChain([this, 'access', _44 => _44.#authStore, 'access', _45 => _45.getStore, 'call', _46 => _46(), 'optionalAccess', _47 => _47.auth])),
|
|
991
|
+
{
|
|
992
|
+
// Tradeoff: `server/discover` advertises only 2026-07-28, so legacy
|
|
993
|
+
// requests are answered unadvertised and skip Mcp-* validation.
|
|
994
|
+
legacy: _nullishCoalesce(config.legacy, () => ( "stateless")),
|
|
995
|
+
...config.enableJsonResponse ? { responseMode: "json" } : {},
|
|
996
|
+
onerror: (error) => this.#logger.error("[ViteMCP error]", error)
|
|
997
|
+
}
|
|
998
|
+
);
|
|
999
|
+
this.#corsMiddleware = config.cors === false ? null : _cors.cors.call(void 0, config.cors);
|
|
1000
|
+
const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _48 => _48.#options, 'access', _49 => _49.auth, 'optionalAccess', _50 => _50.getOAuthConfig, 'call', _51 => _51()])));
|
|
1001
|
+
if (_optionalChain([oauth, 'optionalAccess', _52 => _52.enabled]) !== false && (_nullishCoalesce(_nullishCoalesce(_optionalChain([oauth, 'optionalAccess', _53 => _53.proxy]), () => ( _optionalChain([oauth, 'optionalAccess', _54 => _54.authorizationServer]))), () => ( _optionalChain([oauth, 'optionalAccess', _55 => _55.protectedResource]))))) {
|
|
1002
|
+
this.#honoApp.route(
|
|
1003
|
+
"/",
|
|
1004
|
+
createOAuthRouter({
|
|
1005
|
+
authorizationServer: oauth.authorizationServer,
|
|
1006
|
+
basePath: config.basePath,
|
|
1007
|
+
endpoint: _nullishCoalesce(config.endpoint, () => ( "/mcp")),
|
|
1008
|
+
protectedResource: oauth.protectedResource,
|
|
1009
|
+
proxy: oauth.proxy
|
|
1010
|
+
})
|
|
1011
|
+
);
|
|
1012
|
+
this.#servesProtectedResourceMetadata = Boolean(oauth.protectedResource);
|
|
1013
|
+
}
|
|
1014
|
+
const health = this.#options.health;
|
|
1015
|
+
if (_optionalChain([health, 'optionalAccess', _56 => _56.enabled]) !== false) {
|
|
1016
|
+
this.#honoApp.get(
|
|
1017
|
+
_nullishCoalesce(_optionalChain([health, 'optionalAccess', _57 => _57.path]), () => ( "/health")),
|
|
1018
|
+
(c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _58 => _58.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _59 => _59.status]), () => ( 200)))
|
|
1019
|
+
);
|
|
1020
|
+
}
|
|
1021
|
+
const endpoint = `${_nullishCoalesce(config.basePath, () => ( ""))}${_nullishCoalesce(config.endpoint, () => ( "/mcp"))}`;
|
|
1022
|
+
const handler = this.#handler;
|
|
1023
|
+
const host = _nullishCoalesce(config.host, () => ( "127.0.0.1"));
|
|
1024
|
+
const isLoopback = ["::1", "127.0.0.1", "localhost"].includes(host);
|
|
1025
|
+
const allowedOrigins = _nullishCoalesce(config.allowedOrigins, () => ( (isLoopback ? _server.localhostAllowedOrigins.call(void 0, ) : [])));
|
|
1026
|
+
if (!config.allowedOrigins && !isLoopback) {
|
|
1027
|
+
this.#logger.warn(
|
|
1028
|
+
`[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
this.#honoApp.all(endpoint, async (c) => {
|
|
1032
|
+
const rejected = _server.originValidationResponse.call(void 0, c.req.raw, allowedOrigins);
|
|
1033
|
+
if (rejected) {
|
|
1034
|
+
return rejected;
|
|
1035
|
+
}
|
|
1036
|
+
const authenticated = await this.#authenticateRequest(c.req.raw);
|
|
1037
|
+
if (authenticated instanceof Response) {
|
|
1038
|
+
return authenticated;
|
|
1039
|
+
}
|
|
1040
|
+
return this.#authStore.run(authenticated, () => handler.fetch(c.req.raw));
|
|
1041
|
+
});
|
|
1042
|
+
const app = this.#honoApp;
|
|
1043
|
+
const maxBodySize = _nullishCoalesce(config.maxBodySize, () => ( OAUTH_PROXY_MAX_BODY_SIZE));
|
|
1044
|
+
const useTls = Boolean(config.sslCert && config.sslKey);
|
|
1045
|
+
const requestListener = (req, res) => {
|
|
1046
|
+
void (async () => {
|
|
1047
|
+
try {
|
|
1048
|
+
const body = await readCappedNodeBody(req, maxBodySize);
|
|
1049
|
+
if (body === OVERSIZE) {
|
|
1050
|
+
res.writeHead(400, {
|
|
1051
|
+
Connection: "close",
|
|
1052
|
+
"Content-Type": "application/json"
|
|
1053
|
+
});
|
|
1054
|
+
req.resume();
|
|
1055
|
+
res.once("finish", () => _optionalChain([res, 'access', _60 => _60.socket, 'optionalAccess', _61 => _61.end, 'call', _62 => _62()]));
|
|
1056
|
+
res.end(
|
|
1057
|
+
JSON.stringify({
|
|
1058
|
+
error: "invalid_request",
|
|
1059
|
+
error_description: `Request body exceeds ${formatBytes(maxBodySize)}`
|
|
1060
|
+
})
|
|
1061
|
+
);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const response = await app.fetch(
|
|
1065
|
+
nodeToWebRequest(req, body, useTls, clientDisconnectSignal(res)),
|
|
1066
|
+
{
|
|
1067
|
+
incoming: req,
|
|
1068
|
+
outgoing: res
|
|
1069
|
+
}
|
|
1070
|
+
);
|
|
1071
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
1072
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
this.#logger.debug(`[ViteMCP debug] request failed:`, error);
|
|
1075
|
+
if (!res.headersSent) {
|
|
1076
|
+
res.writeHead(400, {
|
|
1077
|
+
Connection: "close",
|
|
1078
|
+
"Content-Type": "application/json"
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
res.end(
|
|
1082
|
+
JSON.stringify({
|
|
1083
|
+
error: "invalid_request",
|
|
1084
|
+
error_description: "Request body could not be read"
|
|
1085
|
+
})
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
})();
|
|
1089
|
+
};
|
|
1090
|
+
this.#httpServer = useTls ? _https2.default.createServer(
|
|
1091
|
+
{
|
|
1092
|
+
...config.sslCa ? { ca: await _promises.readFile.call(void 0, config.sslCa) } : {},
|
|
1093
|
+
cert: await _promises.readFile.call(void 0, config.sslCert),
|
|
1094
|
+
key: await _promises.readFile.call(void 0, config.sslKey)
|
|
1095
|
+
},
|
|
1096
|
+
requestListener
|
|
1097
|
+
) : _http2.default.createServer(requestListener);
|
|
1098
|
+
await new Promise(
|
|
1099
|
+
(resolve) => this.#httpServer.listen(
|
|
1100
|
+
config.port,
|
|
1101
|
+
_nullishCoalesce(config.host, () => ( "127.0.0.1")),
|
|
1102
|
+
resolve
|
|
1103
|
+
)
|
|
1104
|
+
);
|
|
1105
|
+
this.#logger.info(
|
|
1106
|
+
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${_nullishCoalesce(config.host, () => ( "127.0.0.1"))}:${_nullishCoalesce(this.port, () => ( config.port))}${endpoint}`
|
|
1107
|
+
);
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Converts a schema the SDK cannot consume directly. Zod v4 emits JSON
|
|
1111
|
+
* Schema natively; valibot/arktype go via xsschema.
|
|
1112
|
+
*/
|
|
1113
|
+
async #toSdkSchema(schema, label) {
|
|
1114
|
+
if (!schema) {
|
|
1115
|
+
return void 0;
|
|
1116
|
+
}
|
|
1117
|
+
const standard = schema["~standard"];
|
|
1118
|
+
if (_optionalChain([standard, 'optionalAccess', _63 => _63.jsonSchema])) {
|
|
1119
|
+
return schema;
|
|
1120
|
+
}
|
|
1121
|
+
try {
|
|
1122
|
+
const json = _xsschema.strictJsonSchema.call(void 0, await _xsschema.toJsonSchema.call(void 0, schema));
|
|
1123
|
+
return _server.fromJsonSchema.call(void 0, json);
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
throw new UnexpectedStateError(
|
|
1126
|
+
`${label} is not a supported Standard Schema: ${error instanceof Error ? error.message : String(error)}`,
|
|
1127
|
+
{ label }
|
|
1128
|
+
);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* The RFC 6750 §3 challenge sent when `authenticate` refuses a request.
|
|
1133
|
+
*
|
|
1134
|
+
* `resource_metadata` (RFC 9728 §5.1) is the parameter that turns a bare
|
|
1135
|
+
* rejection into a login: it points the client at this server's
|
|
1136
|
+
* protected-resource document, from which it discovers the authorization
|
|
1137
|
+
* server and starts the flow. It is derived from the URL the request
|
|
1138
|
+
* arrived on, which is exactly where `createOAuthRouter` mounts that
|
|
1139
|
+
* document, and is omitted when this server publishes no such document.
|
|
1140
|
+
*/
|
|
1141
|
+
#unauthorized(request) {
|
|
1142
|
+
return _server.bearerAuthChallengeResponse.call(void 0,
|
|
1143
|
+
new (0, _server.OAuthError)(_server.OAuthErrorCode.InvalidToken, "Authentication required"),
|
|
1144
|
+
this.#servesProtectedResourceMetadata ? {
|
|
1145
|
+
resourceMetadataUrl: _server.getOAuthProtectedResourceMetadataUrl.call(void 0,
|
|
1146
|
+
new URL(request.url)
|
|
1147
|
+
)
|
|
1148
|
+
} : {}
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
var nodeToWebRequest = (req, body, secure, signal) => {
|
|
1153
|
+
const host = _nullishCoalesce(req.headers.host, () => ( "localhost"));
|
|
1154
|
+
const url = `${secure ? "https" : "http"}://${host}${_nullishCoalesce(req.url, () => ( "/"))}`;
|
|
1155
|
+
const headers = new Headers();
|
|
1156
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
1157
|
+
if (value === void 0 || name.startsWith(":")) {
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (Array.isArray(value)) {
|
|
1161
|
+
for (const item of value) {
|
|
1162
|
+
headers.append(name, item);
|
|
1163
|
+
}
|
|
1164
|
+
} else {
|
|
1165
|
+
headers.set(name, value);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
const method = (_nullishCoalesce(req.method, () => ( "GET"))).toUpperCase();
|
|
1169
|
+
const hasBody = method !== "GET" && method !== "HEAD" && body.byteLength > 0;
|
|
1170
|
+
return new Request(url, {
|
|
1171
|
+
headers,
|
|
1172
|
+
method,
|
|
1173
|
+
signal,
|
|
1174
|
+
...hasBody ? { body } : {}
|
|
1175
|
+
});
|
|
1176
|
+
};
|
|
1177
|
+
var clientDisconnectSignal = (res) => {
|
|
1178
|
+
const controller = new AbortController();
|
|
1179
|
+
const abortIfPremature = () => {
|
|
1180
|
+
if (!res.writableEnded) {
|
|
1181
|
+
controller.abort(new Error("Client disconnected"));
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
if (res.closed) {
|
|
1185
|
+
abortIfPremature();
|
|
1186
|
+
} else {
|
|
1187
|
+
res.once("close", abortIfPremature);
|
|
1188
|
+
}
|
|
1189
|
+
return controller.signal;
|
|
1190
|
+
};
|
|
1191
|
+
var withTimeout = (work, timeout, toolName) => new Promise((resolve, reject) => {
|
|
1192
|
+
const timer = setTimeout(() => {
|
|
1193
|
+
const error = new UserError(
|
|
1194
|
+
`Tool '${toolName}' timed out after ${timeout.ms}ms`,
|
|
1195
|
+
{ timeoutMs: timeout.ms, toolName }
|
|
1196
|
+
);
|
|
1197
|
+
timeout.controller.abort(error);
|
|
1198
|
+
reject(error);
|
|
1199
|
+
}, timeout.ms);
|
|
1200
|
+
work.then(resolve, reject).finally(() => clearTimeout(timer));
|
|
1201
|
+
});
|
|
1202
|
+
var requestScope = (...sources) => {
|
|
1203
|
+
const controller = new AbortController();
|
|
1204
|
+
const detach = new AbortController();
|
|
1205
|
+
for (const source of sources) {
|
|
1206
|
+
if (source === void 0) {
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
if (source.aborted) {
|
|
1210
|
+
controller.abort(source.reason);
|
|
1211
|
+
break;
|
|
1212
|
+
}
|
|
1213
|
+
source.addEventListener("abort", () => controller.abort(source.reason), {
|
|
1214
|
+
once: true,
|
|
1215
|
+
signal: detach.signal
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
return { release: () => detach.abort(), signal: controller.signal };
|
|
1219
|
+
};
|
|
1220
|
+
var formatBytes = (bytes) => {
|
|
1221
|
+
if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {
|
|
1222
|
+
return `${bytes / (1024 * 1024)} MiB`;
|
|
1223
|
+
}
|
|
1224
|
+
if (bytes >= 1024 && bytes % 1024 === 0) {
|
|
1225
|
+
return `${bytes / 1024} KiB`;
|
|
1226
|
+
}
|
|
1227
|
+
return `${bytes} bytes`;
|
|
1228
|
+
};
|
|
1229
|
+
var OVERSIZE = /* @__PURE__ */ Symbol("oversize");
|
|
1230
|
+
var readCappedNodeBody = async (req, maxBytes) => {
|
|
1231
|
+
const declared = Number(_nullishCoalesce(req.headers["content-length"], () => ( 0)));
|
|
1232
|
+
if (declared > maxBytes) {
|
|
1233
|
+
return OVERSIZE;
|
|
1234
|
+
}
|
|
1235
|
+
let size = 0;
|
|
1236
|
+
const chunks = [];
|
|
1237
|
+
for await (const chunk of req) {
|
|
1238
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1239
|
+
size += buf.byteLength;
|
|
1240
|
+
if (size > maxBytes) {
|
|
1241
|
+
return OVERSIZE;
|
|
1242
|
+
}
|
|
1243
|
+
chunks.push(buf);
|
|
1244
|
+
}
|
|
1245
|
+
return Buffer.concat(chunks);
|
|
1246
|
+
};
|
|
1247
|
+
var assertStandardSchema = (schema, toolName, field) => {
|
|
1248
|
+
if (schema === void 0) {
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
const standard = _optionalChain([schema, 'optionalAccess', _64 => _64["~standard"]]);
|
|
1252
|
+
if (typeof _optionalChain([standard, 'optionalAccess', _65 => _65.validate]) !== "function") {
|
|
1253
|
+
throw new UnexpectedStateError(
|
|
1254
|
+
`Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,
|
|
1255
|
+
{ toolName }
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
var promptArgsSchema = (prompt) => {
|
|
1260
|
+
const args = prompt.arguments;
|
|
1261
|
+
if (!_optionalChain([args, 'optionalAccess', _66 => _66.length])) {
|
|
1262
|
+
return void 0;
|
|
1263
|
+
}
|
|
1264
|
+
const shape = {};
|
|
1265
|
+
for (const arg of args) {
|
|
1266
|
+
const explicitCompleter = _nullishCoalesce(arg.complete, () => ( (prompt.complete ? (value) => prompt.complete(arg.name, value) : void 0)));
|
|
1267
|
+
const enumValues = arg.enum;
|
|
1268
|
+
const completer = _nullishCoalesce(explicitCompleter, () => ( (_optionalChain([enumValues, 'optionalAccess', _67 => _67.length]) ? async (value) => ({
|
|
1269
|
+
// An empty value is how an editor asks for the whole set before the
|
|
1270
|
+
// user has typed anything; filtering it would answer with nothing.
|
|
1271
|
+
values: value ? enumValues.filter(
|
|
1272
|
+
(option) => option.toLowerCase().includes(value.toLowerCase())
|
|
1273
|
+
) : [...enumValues]
|
|
1274
|
+
}) : void 0)));
|
|
1275
|
+
const valueSchema = _optionalChain([enumValues, 'optionalAccess', _68 => _68.length]) ? _zod.z.enum(enumValues) : _zod.z.string();
|
|
1276
|
+
const described = arg.description ? valueSchema.describe(arg.description) : valueSchema;
|
|
1277
|
+
const base = completer ? _server.completable.call(void 0,
|
|
1278
|
+
described,
|
|
1279
|
+
(async (value) => (await completer(value)).values)
|
|
1280
|
+
) : described;
|
|
1281
|
+
shape[arg.name] = arg.required ? base : base.optional();
|
|
1282
|
+
}
|
|
1283
|
+
return _zod.z.object(shape);
|
|
1284
|
+
};
|
|
1285
|
+
var isStructuredResult = (value) => {
|
|
1286
|
+
if (!Object.hasOwn(value, "structuredContent") || value.structuredContent === void 0) {
|
|
1287
|
+
return false;
|
|
1288
|
+
}
|
|
1289
|
+
if (value.isError !== void 0 && typeof value.isError !== "boolean") {
|
|
1290
|
+
return false;
|
|
1291
|
+
}
|
|
1292
|
+
if (value._meta !== void 0 && (typeof value._meta !== "object" || value._meta === null || Array.isArray(value._meta))) {
|
|
1293
|
+
return false;
|
|
1294
|
+
}
|
|
1295
|
+
return Object.keys(value).every(
|
|
1296
|
+
(key) => key === "structuredContent" || key === "isError" || key === "_meta" || value[key] === void 0
|
|
1297
|
+
);
|
|
1298
|
+
};
|
|
1299
|
+
var normalizeToolResult = (result, hasOutputSchema) => {
|
|
1300
|
+
if (result === void 0 || result === null) {
|
|
1301
|
+
return { content: [] };
|
|
1302
|
+
}
|
|
1303
|
+
if (typeof result === "string") {
|
|
1304
|
+
return { content: [{ text: result, type: "text" }] };
|
|
1305
|
+
}
|
|
1306
|
+
if (typeof result === "object") {
|
|
1307
|
+
const value = result;
|
|
1308
|
+
if (value.resultType === "input_required" || Array.isArray(value.content)) {
|
|
1309
|
+
return value;
|
|
1310
|
+
}
|
|
1311
|
+
if (isStructuredResult(value)) {
|
|
1312
|
+
return {
|
|
1313
|
+
content: [
|
|
1314
|
+
{
|
|
1315
|
+
// `undefined` is excluded already; this covers what else JSON
|
|
1316
|
+
// declines to represent, so a broken payload stays a tool error
|
|
1317
|
+
// rather than an unserializable content block.
|
|
1318
|
+
text: _nullishCoalesce(JSON.stringify(value.structuredContent), () => ( "null")),
|
|
1319
|
+
type: "text"
|
|
1320
|
+
}
|
|
1321
|
+
],
|
|
1322
|
+
structuredContent: value.structuredContent,
|
|
1323
|
+
...value.isError === void 0 ? {} : { isError: value.isError },
|
|
1324
|
+
...value._meta === void 0 ? {} : { _meta: value._meta }
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
if (!hasOutputSchema && (value.type === "text" || value.type === "image" || value.type === "audio" || value.type === "resource" || value.type === "resource_link")) {
|
|
1328
|
+
return { content: [value] };
|
|
1329
|
+
}
|
|
1330
|
+
return {
|
|
1331
|
+
content: [{ text: JSON.stringify(value), type: "text" }],
|
|
1332
|
+
structuredContent: value
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
return { content: [{ text: String(result), type: "text" }] };
|
|
1336
|
+
};
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
exports.DiscoveryDocumentCache = DiscoveryDocumentCache; exports.jsonSchemaAdapter = jsonSchemaAdapter; exports.delay = _promises3.setTimeout; exports.MEDIA_FETCH_TIMEOUT_MS = MEDIA_FETCH_TIMEOUT_MS; exports.ViteMCPError = ViteMCPError; exports.UnexpectedStateError = UnexpectedStateError; exports.UserError = UserError; exports.imageContent = imageContent; exports.audioContent = audioContent; exports.ServerState = ServerState; exports.ViteMCP = ViteMCP;
|
|
1351
|
+
//# sourceMappingURL=chunk-2624N2BP.cjs.map
|