@20baht/elysia-openapi-mcp 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1404 @@
1
+ // @bun
2
+ var __require = import.meta.require;
3
+
4
+ // src/auth/authenticate.ts
5
+ import { audienceMatches, checkBearer } from "@20baht/elysia-resource-server";
6
+
7
+ // src/auth/bearer.ts
8
+ import { bearerChallenge, extractBearer } from "@20baht/elysia-resource-server";
9
+
10
+ // src/auth/authenticate.ts
11
+ var NO_STORE = { "cache-control": "no-store", pragma: "no-cache" };
12
+ function challengeResponse(auth, status, error, description, scope) {
13
+ const headers = {
14
+ ...NO_STORE,
15
+ "www-authenticate": bearerChallenge({
16
+ resourceMetadataUrl: auth.resourceMetadataUrl,
17
+ error,
18
+ errorDescription: description,
19
+ scope
20
+ })
21
+ };
22
+ const body = error ? { error, error_description: description } : null;
23
+ return body ? Response.json(body, { status, headers }) : new Response(null, { status, headers });
24
+ }
25
+ var reject = (...args) => ({
26
+ ok: false,
27
+ response: challengeResponse(...args)
28
+ });
29
+ async function authenticate(request, auth) {
30
+ const hint = auth.scopesSupported ?? (auth.scopes.length ? auth.scopes : undefined);
31
+ const checked = await checkBearer(request, auth);
32
+ if (!checked.ok)
33
+ return reject(auth, 401, checked.error, checked.description, hint);
34
+ const { token, claims, scopes } = checked;
35
+ const missing = auth.scopes.filter((s) => !scopes.includes(s));
36
+ if (missing.length > 0) {
37
+ return reject(auth, 403, "insufficient_scope", `Requires scope: ${auth.scopes.join(" ")}`, auth.scopes);
38
+ }
39
+ const authInfo = {
40
+ token,
41
+ clientId: typeof claims.client_id === "string" ? claims.client_id : typeof claims.azp === "string" ? claims.azp : claims.sub,
42
+ scopes,
43
+ expiresAt: typeof claims.exp === "number" ? claims.exp : undefined,
44
+ resource: auth.resourceUrl,
45
+ extra: claims
46
+ };
47
+ return { ok: true, claims, authInfo };
48
+ }
49
+
50
+ // src/auth/access.ts
51
+ var ANONYMOUS_METHODS = new Set(["initialize", "server/discover", "ping", "tools/list"]);
52
+ function requestsIn(body) {
53
+ const messages = Array.isArray(body) ? body : [body];
54
+ return messages.filter((m) => typeof m === "object" && m !== null && typeof m.method === "string");
55
+ }
56
+ var holdsToolScopes = (tool, granted) => tool.scopes.every((s) => granted.includes(s));
57
+ var union = (...lists) => [...new Set(lists.flat())];
58
+ function checkAccess(body, tools, auth, authInfo) {
59
+ for (const message of requestsIn(body)) {
60
+ if (message.method.startsWith("notifications/"))
61
+ continue;
62
+ const tool = message.method === "tools/call" && typeof message.params?.name === "string" ? tools.get(message.params.name) : undefined;
63
+ if (!authInfo) {
64
+ if (ANONYMOUS_METHODS.has(message.method) || tool?.public)
65
+ continue;
66
+ const hint = tool?.scopes.length ? union(auth.scopes, tool.scopes) : auth.scopesSupported ?? (auth.scopes.length ? auth.scopes : undefined);
67
+ return challengeResponse(auth, 401, undefined, undefined, hint);
68
+ }
69
+ if (tool && !holdsToolScopes(tool, authInfo.scopes)) {
70
+ return challengeResponse(auth, 403, "insufficient_scope", `Tool ${tool.name} requires scope: ${tool.scopes.join(" ")}`, union(authInfo.scopes, auth.scopes, tool.scopes));
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ // src/auth/prm.ts
77
+ function protectedResourceMetadata(auth) {
78
+ const doc = {
79
+ resource: auth.resource,
80
+ authorization_servers: auth.authorizationServers,
81
+ bearer_methods_supported: ["header"]
82
+ };
83
+ if (auth.scopesSupported && auth.scopesSupported.length > 0) {
84
+ doc.scopes_supported = auth.scopesSupported;
85
+ }
86
+ if (auth.resourceName)
87
+ doc.resource_name = auth.resourceName;
88
+ if (auth.resourceDocumentation)
89
+ doc.resource_documentation = auth.resourceDocumentation;
90
+ return doc;
91
+ }
92
+
93
+ // src/auth/resource.ts
94
+ import {
95
+ normalizeResource,
96
+ resourcesEqual,
97
+ validateResourceUri
98
+ } from "@20baht/elysia-resource-server";
99
+
100
+ // src/auth/verify.ts
101
+ import {
102
+ createJwksVerifier,
103
+ metadataCandidates,
104
+ verifyWithOAuthProvider
105
+ } from "@20baht/elysia-resource-server";
106
+
107
+ // src/auth/resolve.ts
108
+ var OAUTH_ONLY_KEYS = [
109
+ "authorizationServers",
110
+ "prmPath",
111
+ "scopes",
112
+ "allowAnonymous",
113
+ "scopesSupported",
114
+ "resourceName",
115
+ "resourceDocumentation",
116
+ "clockTolerance",
117
+ "jwks"
118
+ ];
119
+ function isRequestAuth(auth) {
120
+ if ("resource" in auth && auth.resource !== undefined)
121
+ return false;
122
+ const stray = OAUTH_ONLY_KEYS.filter((k) => (k in auth));
123
+ if (stray.length > 0) {
124
+ throw new TypeError(`[mcpify] auth.${stray[0]} needs auth.resource (OAuth mode); request mode takes only auth.verify`);
125
+ }
126
+ if (typeof auth.verify !== "function") {
127
+ throw new TypeError("[mcpify] auth needs either `resource` + `authorizationServers` (OAuth) or `verify(request)`");
128
+ }
129
+ return true;
130
+ }
131
+ function resolveAuth(auth) {
132
+ const resourceUrl = validateResourceUri(auth.resource, "auth.resource");
133
+ const resource = normalizeResource(auth.resource);
134
+ if (!Array.isArray(auth.authorizationServers) || auth.authorizationServers.length === 0) {
135
+ throw new TypeError("[mcpify] auth.authorizationServers needs at least one issuer URL");
136
+ }
137
+ const authorizationServers = auth.authorizationServers.map((as) => normalizeResource(validateResourceUri(as, "auth.authorizationServers entry").toString()));
138
+ const resourcePath = resourceUrl.pathname.replace(/\/+$/, "");
139
+ const prmPath = auth.prmPath ?? `/.well-known/oauth-protected-resource${resourcePath}`;
140
+ if (!prmPath.startsWith("/"))
141
+ throw new TypeError('[mcpify] auth.prmPath must start with "/"');
142
+ const clockTolerance = auth.clockTolerance ?? (auth.verify ? 0 : auth.jwks?.clockTolerance ?? 30);
143
+ if (!Number.isFinite(clockTolerance) || clockTolerance < 0) {
144
+ throw new TypeError("[mcpify] auth.clockTolerance must be a non-negative number of seconds");
145
+ }
146
+ return {
147
+ resource,
148
+ resourceUrl,
149
+ authorizationServers,
150
+ verify: auth.verify ?? createJwksVerifier({
151
+ authorizationServers,
152
+ jwksUri: auth.jwks?.uri,
153
+ algorithms: auth.jwks?.algorithms,
154
+ clockTolerance: auth.jwks?.clockTolerance,
155
+ typ: auth.jwks?.typ,
156
+ fetch: auth.jwks?.fetch
157
+ }),
158
+ prmPath,
159
+ resourceMetadataUrl: `${resourceUrl.origin}${prmPath}`,
160
+ scopes: auth.scopes ?? [],
161
+ allowAnonymous: auth.allowAnonymous === true,
162
+ requireToolScopes: auth.requireToolScopes === true,
163
+ scopesSupported: auth.scopesSupported,
164
+ resourceName: auth.resourceName,
165
+ resourceDocumentation: auth.resourceDocumentation,
166
+ clockTolerance
167
+ };
168
+ }
169
+
170
+ // src/execute.ts
171
+ import {
172
+ ProtocolError,
173
+ ProtocolErrorCode
174
+ } from "@modelcontextprotocol/server";
175
+
176
+ // src/openapi/schema.ts
177
+ var WRAPPED_RESULT_KEY = "result";
178
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
179
+ function refName(ref) {
180
+ const idx = ref.lastIndexOf("/");
181
+ return idx === -1 ? ref : ref.slice(idx + 1);
182
+ }
183
+ var NESTED_MAPS = new Set(["properties", "patternProperties", "$defs", "definitions"]);
184
+ var NESTED_SINGLE = new Set([
185
+ "items",
186
+ "additionalProperties",
187
+ "not",
188
+ "contains",
189
+ "propertyNames"
190
+ ]);
191
+ var NESTED_LISTS = new Set(["anyOf", "oneOf", "allOf", "prefixItems"]);
192
+ function dereference(schema, components, stack = []) {
193
+ if (!isObject(schema))
194
+ return schema;
195
+ if (typeof schema.$ref === "string") {
196
+ const name = refName(schema.$ref);
197
+ const target = components[name];
198
+ const { $ref: _ref, ...siblings } = schema;
199
+ if (!target) {
200
+ return { ...siblings, description: siblings.description ?? `Unresolved reference ${name}` };
201
+ }
202
+ if (stack.includes(name)) {
203
+ return { type: "object", description: `Recursive reference to ${name}`, ...siblings };
204
+ }
205
+ return { ...dereference(target, components, [...stack, name]), ...siblings };
206
+ }
207
+ const out = {};
208
+ for (const [key, value] of Object.entries(schema)) {
209
+ if (key === "$id")
210
+ continue;
211
+ if (NESTED_MAPS.has(key) && isObject(value)) {
212
+ out[key] = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, dereference(v, components, stack)]));
213
+ } else if (NESTED_SINGLE.has(key)) {
214
+ out[key] = Array.isArray(value) ? value.map((v) => dereference(v, components, stack)) : isObject(value) ? dereference(value, components, stack) : value;
215
+ } else if (NESTED_LISTS.has(key) && Array.isArray(value)) {
216
+ out[key] = value.map((v) => dereference(v, components, stack));
217
+ } else {
218
+ out[key] = value;
219
+ }
220
+ }
221
+ return out;
222
+ }
223
+ function simplifyNumeric(schema) {
224
+ if (!isObject(schema))
225
+ return schema;
226
+ let out = schema;
227
+ for (const [key, value] of Object.entries(schema)) {
228
+ let next = value;
229
+ if (NESTED_MAPS.has(key) && isObject(value)) {
230
+ next = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, simplifyNumeric(v)]));
231
+ } else if (NESTED_SINGLE.has(key)) {
232
+ next = Array.isArray(value) ? value.map((v) => simplifyNumeric(v)) : isObject(value) ? simplifyNumeric(value) : value;
233
+ } else if (NESTED_LISTS.has(key) && Array.isArray(value)) {
234
+ next = value.map((v) => simplifyNumeric(v));
235
+ }
236
+ if (next !== value)
237
+ out = { ...out, [key]: next };
238
+ }
239
+ return collapseNumeric(out);
240
+ }
241
+ function collapseNumeric(schema) {
242
+ const anyOf = schema.anyOf;
243
+ if (!Array.isArray(anyOf) || anyOf.length !== 2)
244
+ return schema;
245
+ const isNumericString = (s) => isObject(s) && s.type === "string" && s.format === "numeric";
246
+ const numberBranch = anyOf.find((s) => isObject(s) && (s.type === "number" || s.type === "integer"));
247
+ if (!anyOf.some(isNumericString) || !isObject(numberBranch))
248
+ return schema;
249
+ const { anyOf: _drop, ...rest } = schema;
250
+ return { ...numberBranch, ...rest };
251
+ }
252
+ function hoistUnionDescription(schema) {
253
+ if (typeof schema.description === "string" && schema.description)
254
+ return schema;
255
+ const members = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;
256
+ if (!members)
257
+ return schema;
258
+ const nonNull = members.filter((m) => !(isObject(m) && m.type === "null"));
259
+ const only = nonNull.length === 1 ? nonNull[0] : undefined;
260
+ if (!isObject(only) || typeof only.description !== "string" || !only.description)
261
+ return schema;
262
+ return { ...schema, description: only.description };
263
+ }
264
+ var isObjectSchema = (s) => isObject(s) && (s.type === "object" || isObject(s.properties));
265
+ var isJsonMedia = (type) => {
266
+ const base = type.split(";")[0].trim().toLowerCase();
267
+ return base === "application/json" || base.endsWith("+json");
268
+ };
269
+ function jsonSchemaOf(content) {
270
+ if (!content)
271
+ return;
272
+ const json = content["application/json"] ?? Object.entries(content).find(([type]) => isJsonMedia(type))?.[1];
273
+ return json?.schema;
274
+ }
275
+ function hasNonJsonBodyOnly(op) {
276
+ const types = Object.keys(op.requestBody?.content ?? {});
277
+ return types.length > 0 && !types.some(isJsonMedia);
278
+ }
279
+ var IGNORED_HEADER_PARAMS = new Set(["accept", "content-type", "authorization"]);
280
+ function flattenOperation(toolName, op, components, pathParams, options = {}) {
281
+ const properties = {};
282
+ const required = [];
283
+ const origins = {};
284
+ const diagnostics = [];
285
+ const missingDescription = [];
286
+ const missingPathDescription = [];
287
+ let rawBodyKey;
288
+ const add = (bucket, name, rawSchema, isRequired) => {
289
+ const schema2 = hoistUnionDescription(simplifyNumeric(rawSchema));
290
+ let flat = name;
291
+ if (flat in properties) {
292
+ flat = `${bucket}_${name}`;
293
+ diagnostics.push({
294
+ kind: "argument-collision",
295
+ message: `[mcpify] tool "${toolName}": "${name}" exists in both ${origins[name].bucket} and ${bucket}; the ${bucket} one is exposed as "${flat}"`
296
+ });
297
+ }
298
+ properties[flat] = schema2;
299
+ origins[flat] = { bucket, name };
300
+ if (isRequired)
301
+ required.push(flat);
302
+ if (!schema2.description)
303
+ (bucket === "path" ? missingPathDescription : missingDescription).push(flat);
304
+ return flat;
305
+ };
306
+ const params = (op.parameters ?? []).filter(isObject);
307
+ const byPath = new Map(params.filter((p) => p.in === "path").map((p) => [p.name, p]));
308
+ for (const name of pathParams) {
309
+ const p = byPath.get(name);
310
+ const schema2 = dereference(p?.schema, components) ?? { type: "string" };
311
+ if (p?.description && !schema2.description)
312
+ schema2.description = p.description;
313
+ add("path", name, schema2, true);
314
+ }
315
+ for (const p of byPath.values()) {
316
+ if (!pathParams.includes(p.name)) {
317
+ diagnostics.push({
318
+ kind: "stray-path-param",
319
+ message: `[mcpify] tool "${toolName}": path parameter "${p.name}" is not in the path template and was ignored`
320
+ });
321
+ }
322
+ }
323
+ for (const p of params) {
324
+ if (p.in !== "query")
325
+ continue;
326
+ const schema2 = dereference(p.schema, components) ?? { type: "string" };
327
+ if (p.description && !schema2.description)
328
+ schema2.description = p.description;
329
+ add("query", p.name, schema2, p.required === true);
330
+ }
331
+ const headerParams = params.filter((p) => p.in === "header");
332
+ if (options.headerParams) {
333
+ for (const p of headerParams) {
334
+ if (IGNORED_HEADER_PARAMS.has(p.name.toLowerCase()))
335
+ continue;
336
+ const schema2 = dereference(p.schema, components) ?? { type: "string" };
337
+ if (p.description && !schema2.description)
338
+ schema2.description = p.description;
339
+ add("header", p.name, schema2, p.required === true);
340
+ }
341
+ }
342
+ const requiredHeaders = options.headerParams ? [] : headerParams.filter((p) => p.required);
343
+ if (requiredHeaders.length > 0) {
344
+ diagnostics.push({
345
+ kind: "header-param",
346
+ message: `[mcpify] tool "${toolName}": required header(s) ${requiredHeaders.map((h) => h.name).join(", ")} are not tool arguments; they must arrive on the MCP request itself`
347
+ });
348
+ }
349
+ const body = dereference(jsonSchemaOf(op.requestBody?.content), components);
350
+ if (body) {
351
+ const bodyRequired = op.requestBody?.required !== false;
352
+ if (isObjectSchema(body)) {
353
+ const req = new Set(bodyRequired ? body.required ?? [] : []);
354
+ for (const [name, schema2] of Object.entries(body.properties ?? {})) {
355
+ add("body", name, schema2, req.has(name));
356
+ }
357
+ } else {
358
+ rawBodyKey = add("body", "body", body, bodyRequired);
359
+ }
360
+ }
361
+ if (missingPathDescription.length > 0) {
362
+ diagnostics.push({
363
+ kind: "path-param-description",
364
+ message: `[mcpify] tool "${toolName}": no description for path parameter ${missingPathDescription.join(", ")} \u2014 agents pick arguments better with one`
365
+ });
366
+ }
367
+ if (missingDescription.length > 0) {
368
+ diagnostics.push({
369
+ kind: "argument-description",
370
+ message: `[mcpify] tool "${toolName}": no description for ${missingDescription.join(", ")} \u2014 agents pick arguments better with one`
371
+ });
372
+ }
373
+ const schema = { type: "object", properties };
374
+ if (required.length > 0)
375
+ schema.required = required;
376
+ return { schema, origins, rawBodyKey, warnings: diagnostics.map((d) => d.message), diagnostics };
377
+ }
378
+ function unflattenArgs(args, flat) {
379
+ const params = {};
380
+ const query = {};
381
+ const headers = {};
382
+ let body;
383
+ let rawBody;
384
+ let hasRawBody = false;
385
+ for (const [key, value] of Object.entries(args)) {
386
+ const origin = flat.origins[key];
387
+ if (!origin)
388
+ continue;
389
+ if (flat.rawBodyKey === key) {
390
+ rawBody = value;
391
+ hasRawBody = true;
392
+ continue;
393
+ }
394
+ if (origin.bucket === "path")
395
+ params[origin.name] = value;
396
+ else if (origin.bucket === "query")
397
+ query[origin.name] = value;
398
+ else if (origin.bucket === "header")
399
+ headers[origin.name] = value;
400
+ else
401
+ (body ??= {})[origin.name] = value;
402
+ }
403
+ return { params, query, headers, body: hasRawBody ? rawBody : body };
404
+ }
405
+ var isSuccessKey = (k) => /^2(\d\d|xx)$/i.test(k);
406
+ function deepEqual(a, b) {
407
+ if (a === b)
408
+ return true;
409
+ if (Array.isArray(a)) {
410
+ return Array.isArray(b) && a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
411
+ }
412
+ if (isObject(a) && isObject(b)) {
413
+ const keys = Object.keys(a);
414
+ return keys.length === Object.keys(b).length && keys.every((k) => (k in b) && deepEqual(a[k], b[k]));
415
+ }
416
+ return false;
417
+ }
418
+ function outputSchemaFor(op, components, wrapNonObject, report) {
419
+ const responses = op.responses ?? {};
420
+ let keys = Object.keys(responses).filter(isSuccessKey);
421
+ if (keys.length === 0 && "default" in responses)
422
+ keys = ["default"];
423
+ const schemas = keys.map((key) => {
424
+ const res = responses[key];
425
+ const content = isObject(res) ? res.content : undefined;
426
+ return dereference(jsonSchemaOf(content) ?? content?.["text/plain"]?.schema, components);
427
+ });
428
+ const present = schemas.filter((s) => s !== undefined);
429
+ if (present.length === 0)
430
+ return;
431
+ const schema = present[0];
432
+ if (present.length !== schemas.length || !present.every((s) => deepEqual(s, schema))) {
433
+ report?.(`the 2xx responses (${keys.join(", ")}) do not all declare JSON content with the same schema`);
434
+ return;
435
+ }
436
+ return toOutputSchema(schema, wrapNonObject);
437
+ }
438
+ function toOutputSchema(schema, wrapNonObject) {
439
+ if (isObjectSchema(schema))
440
+ return { schema: { ...schema, type: "object" }, wrapped: false };
441
+ if (!wrapNonObject)
442
+ return;
443
+ return {
444
+ schema: {
445
+ type: "object",
446
+ properties: { [WRAPPED_RESULT_KEY]: schema },
447
+ required: [WRAPPED_RESULT_KEY]
448
+ },
449
+ wrapped: true
450
+ };
451
+ }
452
+
453
+ // src/execute.ts
454
+ var toolRequests = new WeakSet;
455
+ function isToolCall(request) {
456
+ return toolRequests.has(request);
457
+ }
458
+ var STRIPPED = new Set([
459
+ "host",
460
+ "content-length",
461
+ "content-type",
462
+ "accept",
463
+ "accept-encoding",
464
+ "connection",
465
+ "transfer-encoding",
466
+ "keep-alive",
467
+ "upgrade",
468
+ "te",
469
+ "trailer",
470
+ "last-event-id"
471
+ ]);
472
+ var defaultHeaderPolicy = (incoming) => {
473
+ const out = new Headers;
474
+ incoming.forEach((value, key) => {
475
+ const name = key.toLowerCase();
476
+ if (!STRIPPED.has(name) && !name.startsWith("mcp-"))
477
+ out.set(key, value);
478
+ });
479
+ return out;
480
+ };
481
+ function toQueryString(query) {
482
+ const params = new URLSearchParams;
483
+ for (const [key, value] of Object.entries(query)) {
484
+ if (value === undefined || value === null)
485
+ continue;
486
+ const values = Array.isArray(value) ? value : [value];
487
+ for (const v of values) {
488
+ params.append(key, typeof v === "object" && v !== null ? JSON.stringify(v) : String(v));
489
+ }
490
+ }
491
+ const qs = params.toString();
492
+ return qs ? `?${qs}` : "";
493
+ }
494
+ var encodeStatic = (text) => text.replace(/[^\x21-\x7e]/gu, encodeURIComponent);
495
+ function buildToolRequest(tool, args, original, headerPolicy = defaultHeaderPolicy) {
496
+ const { params, query, headers: headerArgs, body } = unflattenArgs(args, tool.flat);
497
+ const path = tool.path.split(/(\{[^}]+\})/).map((part) => {
498
+ if (!/^\{[^}]+\}$/.test(part))
499
+ return encodeStatic(part);
500
+ const name = part.slice(1, -1);
501
+ const value = params[name];
502
+ if (value === undefined || value === null || value === "") {
503
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Missing required path parameter "${name}" for tool ${tool.name}`);
504
+ }
505
+ const text = String(value);
506
+ if (text === "." || text === "..") {
507
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid path parameter "${name}" for tool ${tool.name}: "${text}" is not allowed`);
508
+ }
509
+ return encodeURIComponent(text);
510
+ }).join("");
511
+ const origin = new URL(original.url).origin;
512
+ const url = new URL(`${origin}${path}${toQueryString(query)}`);
513
+ if (url.pathname !== path) {
514
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Path parameters for tool ${tool.name} resolve outside the tool's route`);
515
+ }
516
+ const headers = new Headers(headerPolicy(original.headers));
517
+ headers.set("accept", "application/json, text/plain;q=0.9, */*;q=0.8");
518
+ for (const [name, value] of Object.entries(headerArgs)) {
519
+ if (value === undefined || value === null)
520
+ continue;
521
+ const text = Array.isArray(value) ? value.join(",") : typeof value === "object" ? JSON.stringify(value) : String(value);
522
+ try {
523
+ headers.set(name, text);
524
+ } catch {
525
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid value for header parameter "${name}" for tool ${tool.name}`);
526
+ }
527
+ }
528
+ let bodyText;
529
+ if (body !== undefined && tool.method !== "GET") {
530
+ bodyText = JSON.stringify(body);
531
+ headers.set("content-type", "application/json");
532
+ }
533
+ const request = new Request(url, { method: tool.method, headers, body: bodyText });
534
+ toolRequests.add(request);
535
+ return request;
536
+ }
537
+ var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
538
+ async function readBody(res) {
539
+ const text = await res.text();
540
+ const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
541
+ const looksJson = type === "application/json" || type.endsWith("+json");
542
+ if (looksJson || !type && text && /^[[{"\d\-tfn]/.test(text.trimStart())) {
543
+ try {
544
+ return { text, parsed: JSON.parse(text), isJson: true };
545
+ } catch {}
546
+ }
547
+ return { text, parsed: text, isJson: false };
548
+ }
549
+ async function toCallToolResult(tool, res) {
550
+ const { text, parsed, isJson } = await readBody(res);
551
+ const display = isJson ? JSON.stringify(parsed) : text;
552
+ if (!res.ok) {
553
+ return {
554
+ isError: true,
555
+ content: [{ type: "text", text: `HTTP ${res.status}${display ? `: ${display}` : ""}` }]
556
+ };
557
+ }
558
+ const result = { content: [{ type: "text", text: display }] };
559
+ if (tool.output) {
560
+ if (tool.output.wrapped)
561
+ result.structuredContent = { [WRAPPED_RESULT_KEY]: parsed };
562
+ else if (isPlainObject(parsed))
563
+ result.structuredContent = parsed;
564
+ else {
565
+ return {
566
+ isError: true,
567
+ content: [
568
+ {
569
+ type: "text",
570
+ text: `Tool ${tool.name} declares an object output but the response (HTTP ${res.status}) was ${isJson ? "JSON that is not an object" : "not a JSON object"}${display ? `: ${display}` : ""}`
571
+ }
572
+ ]
573
+ };
574
+ }
575
+ }
576
+ return result;
577
+ }
578
+ async function callTool(app, tool, args, original, headerPolicy, onToolCall) {
579
+ const request = buildToolRequest(tool, args, original, headerPolicy);
580
+ const started = performance.now();
581
+ const response = await app.handle(request);
582
+ const durationMs = performance.now() - started;
583
+ const copy = onToolCall ? response.clone() : undefined;
584
+ const result = await toCallToolResult(tool, response);
585
+ if (onToolCall)
586
+ await onToolCall({ tool, args, request, response: copy, durationMs });
587
+ return result;
588
+ }
589
+
590
+ // src/openapi/naming.ts
591
+ var METHOD_VERB = {
592
+ POST: "create",
593
+ PUT: "update",
594
+ PATCH: "update",
595
+ DELETE: "delete"
596
+ };
597
+ function isParamSegment(segment) {
598
+ return segment.startsWith("{") || segment.startsWith(":") || segment === "*" || segment === "**";
599
+ }
600
+ function templateParams(path) {
601
+ const out = [];
602
+ for (const m of path.matchAll(/\{([^}]+)\}/g))
603
+ out.push(m[1]);
604
+ return out;
605
+ }
606
+ function toSnake(word) {
607
+ return word.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").toLowerCase().replace(/^_+|_+$/g, "");
608
+ }
609
+ function singular(word) {
610
+ if (word.length <= 2)
611
+ return word;
612
+ if (/(ss|us|is|ews)$/.test(word))
613
+ return word;
614
+ if (word.endsWith("ies") && word.length > 3)
615
+ return word.slice(0, -3) + "y";
616
+ if (/(sses|shes|ches|xes|zes)$/.test(word))
617
+ return word.slice(0, -2);
618
+ if (word.endsWith("s"))
619
+ return word.slice(0, -1);
620
+ return word;
621
+ }
622
+ function sanitizeToolName(name) {
623
+ const cleaned = name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
624
+ return (cleaned || "tool").slice(0, 64);
625
+ }
626
+ function deriveToolName(method, path) {
627
+ const verbMethod = method.toUpperCase();
628
+ const segments = path.split("/").filter(Boolean);
629
+ let start = 0;
630
+ while (start < segments.length && !isParamSegment(segments[start]) && /^(api|v\d+)$/i.test(segments[start])) {
631
+ start++;
632
+ }
633
+ const words = [];
634
+ let trailingParam = false;
635
+ for (let i = start;i < segments.length; i++) {
636
+ const seg = segments[i];
637
+ if (isParamSegment(seg)) {
638
+ trailingParam = i === segments.length - 1;
639
+ continue;
640
+ }
641
+ const next = segments[i + 1];
642
+ let word = toSnake(seg);
643
+ if (next !== undefined && isParamSegment(next))
644
+ word = singular(word);
645
+ if (word)
646
+ words.push(word);
647
+ }
648
+ let verb;
649
+ if (verbMethod === "GET")
650
+ verb = trailingParam ? "get" : "list";
651
+ else
652
+ verb = METHOD_VERB[verbMethod] ?? verbMethod.toLowerCase();
653
+ if (verbMethod !== "GET" && !trailingParam && words.length > 0) {
654
+ words[words.length - 1] = singular(words[words.length - 1]);
655
+ }
656
+ const resource = words.length > 0 ? words.join("_") : "root";
657
+ return sanitizeToolName(`${verb}_${resource}`);
658
+ }
659
+ var capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1);
660
+ function elysiaDefaultOperationId(method, openapiPath) {
661
+ const path = openapiPath.replace(/\{([^}]+)\}/g, ":$1");
662
+ let id = method.toLowerCase();
663
+ if (!path || path === "/")
664
+ return id + "Index";
665
+ for (const seg of path.split("/")) {
666
+ id += seg.includes(":") ? "By" + capitalize(seg.replace(":", "")) : capitalize(seg);
667
+ }
668
+ return id.replace(/\?/g, "Optional");
669
+ }
670
+
671
+ // src/openapi/types.ts
672
+ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
673
+ function isOperation(value) {
674
+ return typeof value === "object" && value !== null && !Array.isArray(value);
675
+ }
676
+
677
+ // src/openapi/derive.ts
678
+ var DEFAULT_EXCLUDED_PATHS = [
679
+ /^\/\.well-known(\/|$)/,
680
+ "/authorize",
681
+ "/token",
682
+ "/register",
683
+ "/revoke",
684
+ "/introspect",
685
+ "/userinfo"
686
+ ];
687
+ function isExcluded(path, exclude) {
688
+ return exclude.some((rule) => typeof rule === "string" ? rule === path : rule.test(path));
689
+ }
690
+ function annotationsFor(method, summary) {
691
+ const base = summary ? { title: summary } : {};
692
+ switch (method) {
693
+ case "GET":
694
+ return { ...base, readOnlyHint: true, idempotentHint: true, destructiveHint: false };
695
+ case "PUT":
696
+ return { ...base, readOnlyHint: false, idempotentHint: true, destructiveHint: false };
697
+ case "PATCH":
698
+ return { ...base, readOnlyHint: false, idempotentHint: false, destructiveHint: false };
699
+ case "DELETE":
700
+ return { ...base, readOnlyHint: false, idempotentHint: true, destructiveHint: true };
701
+ default:
702
+ return { ...base, readOnlyHint: false };
703
+ }
704
+ }
705
+ function describe(op, method, path) {
706
+ const summary = op.summary?.trim();
707
+ const description = op.description?.trim();
708
+ if (summary && description && summary !== description)
709
+ return `${summary}
710
+
711
+ ${description}`;
712
+ return summary || description || `${method} ${path}`;
713
+ }
714
+ function stripPrefix(path, prefixes) {
715
+ for (const raw of prefixes) {
716
+ const prefix = raw.replace(/\/+$/, "");
717
+ if (prefix && path.startsWith(`${prefix}/`))
718
+ return path.slice(prefix.length);
719
+ }
720
+ return path;
721
+ }
722
+ function toolNameFor(op, method, path, stripPrefixes = []) {
723
+ const id = op.operationId;
724
+ if (typeof id === "string" && id.trim() && id !== elysiaDefaultOperationId(method, path)) {
725
+ return sanitizeToolName(id);
726
+ }
727
+ return deriveToolName(method, stripPrefix(path, stripPrefixes));
728
+ }
729
+ function routeOptions(mcp, where, warn) {
730
+ if (typeof mcp !== "object" || mcp === null)
731
+ return { scopes: [], public: false };
732
+ const o = mcp;
733
+ let scopes = [];
734
+ if (o.scopes !== undefined) {
735
+ const valid = (s) => typeof s === "string" && /^[\x21\x23-\x5b\x5d-\x7e]+$/.test(s);
736
+ if (Array.isArray(o.scopes) && o.scopes.every(valid)) {
737
+ scopes = [...new Set(o.scopes)];
738
+ } else {
739
+ warn({
740
+ kind: "invalid-scopes",
741
+ message: `[mcpify] ${where}: detail.mcp.scopes must be an array of OAuth scope tokens; ignored`
742
+ });
743
+ }
744
+ }
745
+ let output;
746
+ if (o.output !== undefined) {
747
+ if (typeof o.output === "object" && o.output !== null && !Array.isArray(o.output)) {
748
+ output = o.output;
749
+ } else {
750
+ warn({
751
+ kind: "no-output-schema",
752
+ message: `[mcpify] ${where}: detail.mcp.output must be a JSON Schema object; ignored`
753
+ });
754
+ }
755
+ }
756
+ return { scopes, public: o.public === true, ...output ? { output } : {} };
757
+ }
758
+ function deriveTools(doc, o) {
759
+ const tools = [];
760
+ const warnings = [];
761
+ const components = doc.components?.schemas ?? {};
762
+ const seen = new Map;
763
+ const exclude = o.exclude ?? DEFAULT_EXCLUDED_PATHS;
764
+ for (const [path, item] of Object.entries(doc.paths ?? {})) {
765
+ if (!isOperation(item) || isExcluded(path, exclude))
766
+ continue;
767
+ for (const method of HTTP_METHODS) {
768
+ const op = item[method];
769
+ if (!isOperation(op))
770
+ continue;
771
+ if (op.hide === true || op.mcp === false)
772
+ continue;
773
+ const optedIn = op.mcp === true || typeof op.mcp === "object" && op.mcp !== null;
774
+ if (!o.allRoutes && !optedIn)
775
+ continue;
776
+ const tags = Array.isArray(op.tags) ? op.tags.filter((t) => typeof t === "string") : [];
777
+ if (o.tags && !tags.some((t) => o.tags.includes(t)))
778
+ continue;
779
+ const METHOD = method.toUpperCase();
780
+ if (hasNonJsonBodyOnly(op)) {
781
+ warnings.push({
782
+ kind: "non-json-body",
783
+ message: `[mcpify] skipped ${METHOD} ${path}: its request body has no JSON media type (${Object.keys(op.requestBody.content).join(", ")}), which tools cannot send`
784
+ });
785
+ continue;
786
+ }
787
+ let name = toolNameFor(op, METHOD, path, o.stripPrefixes ?? []);
788
+ const count = seen.get(name) ?? 0;
789
+ seen.set(name, count + 1);
790
+ if (count > 0) {
791
+ const renamed = sanitizeToolName(`${name}_${count + 1}`);
792
+ warnings.push({
793
+ kind: "duplicate-name",
794
+ message: `[mcpify] duplicate tool name "${name}" (${METHOD} ${path}) \u2014 exposed as "${renamed}"; set detail.operationId to pick names explicitly`
795
+ });
796
+ name = renamed;
797
+ }
798
+ const flat = flattenOperation(name, op, components, templateParams(path), {
799
+ headerParams: o.headerParams
800
+ });
801
+ warnings.push(...flat.diagnostics);
802
+ const { output: declared, ...access } = routeOptions(op.mcp, `tool "${name}"`, (m) => warnings.push(m));
803
+ const report = (reason) => warnings.push({
804
+ kind: "no-output-schema",
805
+ message: `[mcpify] tool "${name}": no outputSchema emitted; ${reason}`
806
+ });
807
+ let output;
808
+ if (declared) {
809
+ output = toOutputSchema(dereference(declared, components), o.wrapNonObjectOutput);
810
+ if (!output)
811
+ report("detail.mcp.output is not an object schema and wrapNonObjectOutput is off");
812
+ } else {
813
+ output = outputSchemaFor(op, components, o.wrapNonObjectOutput, report);
814
+ }
815
+ tools.push({
816
+ name,
817
+ title: op.summary?.trim() || undefined,
818
+ description: describe(op, METHOD, path),
819
+ method: METHOD,
820
+ path,
821
+ flat,
822
+ output,
823
+ tags,
824
+ annotations: annotationsFor(METHOD, op.summary?.trim() || undefined),
825
+ ...access
826
+ });
827
+ }
828
+ }
829
+ if (tools.length === 0) {
830
+ warnings.push({
831
+ kind: "no-tools",
832
+ message: "[mcpify] no MCP-eligible operations found in the OpenAPI document \u2014 tools/list is empty"
833
+ });
834
+ }
835
+ return { tools, warnings: warnings.map((w) => w.message), diagnostics: warnings };
836
+ }
837
+ function toMcpTool(spec) {
838
+ const tool = {
839
+ name: spec.name,
840
+ description: spec.description,
841
+ inputSchema: spec.flat.schema,
842
+ annotations: spec.annotations
843
+ };
844
+ if (spec.title)
845
+ tool.title = spec.title;
846
+ if (spec.output)
847
+ tool.outputSchema = spec.output.schema;
848
+ return tool;
849
+ }
850
+
851
+ // src/transport.ts
852
+ import {
853
+ createMcpHandler,
854
+ isLegacyRequest,
855
+ McpServer,
856
+ ProtocolError as ProtocolError2,
857
+ ProtocolErrorCode as ProtocolErrorCode2,
858
+ WebStandardStreamableHTTPServerTransport
859
+ } from "@modelcontextprotocol/server";
860
+ function createServer(o) {
861
+ const mcp = new McpServer(o.serverInfo, {
862
+ capabilities: { tools: {} },
863
+ ...o.instructions === undefined ? {} : { instructions: o.instructions }
864
+ });
865
+ mcp.server.setRequestHandler("tools/list", () => ({ tools: o.tools.list }));
866
+ mcp.server.setRequestHandler("tools/call", async (req) => {
867
+ const tool = o.tools.byName.get(req.params.name);
868
+ if (!tool) {
869
+ throw new ProtocolError2(ProtocolErrorCode2.InvalidParams, `Tool ${req.params.name} not found`);
870
+ }
871
+ const result = await callTool(o.app, tool, req.params.arguments ?? {}, o.request, o.headerPolicy, o.onToolCall);
872
+ return mcp.server.projectCallToolResult(result, tool.output?.schema);
873
+ });
874
+ return mcp;
875
+ }
876
+ async function serveLegacy(o) {
877
+ const mcp = createServer(o);
878
+ const transport = new WebStandardStreamableHTTPServerTransport({
879
+ sessionIdGenerator: undefined,
880
+ enableJsonResponse: true
881
+ });
882
+ await mcp.connect(transport);
883
+ try {
884
+ return await transport.handleRequest(o.request, {
885
+ authInfo: o.authInfo,
886
+ parsedBody: o.parsedBody
887
+ });
888
+ } finally {
889
+ await transport.close();
890
+ }
891
+ }
892
+ async function serveModern(o) {
893
+ const handler = createMcpHandler(() => createServer(o), { legacy: "reject" });
894
+ let response;
895
+ try {
896
+ response = await handler.fetch(o.request, {
897
+ ...o.authInfo === undefined ? {} : { authInfo: o.authInfo },
898
+ ...o.parsedBody === undefined ? {} : { parsedBody: o.parsedBody }
899
+ });
900
+ } catch (e) {
901
+ await handler.close();
902
+ throw e;
903
+ }
904
+ if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
905
+ await handler.close();
906
+ }
907
+ return response;
908
+ }
909
+ async function serveMcp(o) {
910
+ return await isLegacyRequest(o.request, o.parsedBody) ? serveLegacy(o) : serveModern(o);
911
+ }
912
+
913
+ // src/warnings.ts
914
+ var MCPIFY_WARNING_KINDS = [
915
+ "unauthenticated",
916
+ "path-param-description",
917
+ "argument-description",
918
+ "argument-collision",
919
+ "duplicate-name",
920
+ "stray-path-param",
921
+ "header-param",
922
+ "non-json-body",
923
+ "no-output-schema",
924
+ "invalid-scopes",
925
+ "scopes-not-enforced",
926
+ "tool-hidden",
927
+ "no-tools",
928
+ "document",
929
+ "verify-error",
930
+ "on-tool-call-error",
931
+ "cors-reflects-origin"
932
+ ];
933
+ function silencedKinds(option) {
934
+ const off = new Set;
935
+ for (const [kind, on] of Object.entries(option ?? {})) {
936
+ if (!MCPIFY_WARNING_KINDS.includes(kind)) {
937
+ throw new TypeError(`[mcpify] unknown warning kind "${kind}" in \`warnings\`; known: ${MCPIFY_WARNING_KINDS.join(", ")}`);
938
+ }
939
+ if (!on)
940
+ off.add(kind);
941
+ }
942
+ return off;
943
+ }
944
+
945
+ // src/plugin.ts
946
+ var DEFAULT_SPEC_PATH = "/openapi/json";
947
+ var UNAUTHENTICATED_WARNING = `
948
+ [mcpify] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
949
+ [mcpify] \u2502 WARNING: MCP endpoint mounted WITHOUT authorization. \u2502
950
+ [mcpify] \u2502 unsafeNoAuth: any client that can reach it can list the tools, \u2502
951
+ [mcpify] \u2502 and calls are guarded only by your routes. Pass \u2502
952
+ [mcpify] \u2502 \`auth: { verify }\` or \`auth: { resource, authorizationServers }\`\u2502
953
+ [mcpify] \u2502 instead; \`warnings: { unauthenticated: false }\` hushes this. \u2502
954
+ [mcpify] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518`;
955
+ function originPolicy(option) {
956
+ if (option === true)
957
+ return () => true;
958
+ if (option === false)
959
+ return null;
960
+ if (typeof option !== "object" || option === null) {
961
+ throw new TypeError("[mcpify] cors must be a boolean or { origins }");
962
+ }
963
+ const { origins } = option;
964
+ if (typeof origins === "function") {
965
+ return (origin) => {
966
+ try {
967
+ return origins(origin);
968
+ } catch {
969
+ return false;
970
+ }
971
+ };
972
+ }
973
+ if (!Array.isArray(origins) || !origins.every((o) => typeof o === "string")) {
974
+ throw new TypeError("[mcpify] cors.origins must be an array of origins or a predicate");
975
+ }
976
+ const normalize = (o) => {
977
+ try {
978
+ return new URL(o).origin;
979
+ } catch {
980
+ return o;
981
+ }
982
+ };
983
+ const allowed = new Set(origins.map(normalize));
984
+ return (origin) => allowed.has(origin);
985
+ }
986
+ function corsHeaders(request, policy) {
987
+ if (!policy)
988
+ return {};
989
+ const origin = request.headers.get("origin");
990
+ if (!origin)
991
+ return {};
992
+ if (!policy(origin))
993
+ return { vary: "Origin" };
994
+ return {
995
+ "access-control-allow-origin": origin,
996
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
997
+ "access-control-allow-headers": request.headers.get("access-control-request-headers") ?? "Authorization, Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Mcp-Method, Mcp-Name, Last-Event-ID",
998
+ "access-control-expose-headers": "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version",
999
+ "access-control-max-age": "86400",
1000
+ vary: "Origin, Access-Control-Request-Headers"
1001
+ };
1002
+ }
1003
+ function withHeaders(res, extra) {
1004
+ const keys = Object.keys(extra);
1005
+ if (keys.length === 0)
1006
+ return res;
1007
+ const headers = new Headers(res.headers);
1008
+ for (const key of keys)
1009
+ if (!headers.has(key))
1010
+ headers.set(key, extra[key]);
1011
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
1012
+ }
1013
+ var MAX_BODY_BYTES = 4 * 1024 * 1024;
1014
+ var rpcError = (status, code, message, headers) => Response.json({ jsonrpc: "2.0", error: { code, message }, id: null }, { status, headers });
1015
+ var unauthorized = () => rpcError(401, -32001, "Unauthorized.", NO_STORE);
1016
+ async function readJsonBody(request, body) {
1017
+ const tooLarge = {
1018
+ ok: false,
1019
+ response: rpcError(413, -32600, "Request body too large.")
1020
+ };
1021
+ let text;
1022
+ if (request.bodyUsed) {
1023
+ if (typeof body !== "string")
1024
+ return { ok: true, value: body };
1025
+ text = body;
1026
+ } else {
1027
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_BODY_BYTES)
1028
+ return tooLarge;
1029
+ text = await request.text();
1030
+ }
1031
+ if (text.length > MAX_BODY_BYTES)
1032
+ return tooLarge;
1033
+ try {
1034
+ return { ok: true, value: JSON.parse(text) };
1035
+ } catch {
1036
+ return { ok: false, response: rpcError(400, -32700, "Parse error: Invalid JSON") };
1037
+ }
1038
+ }
1039
+ function resolveAuthMode(options) {
1040
+ const auth = options?.auth;
1041
+ const unsafe = options?.unsafeNoAuth === true;
1042
+ if (auth !== undefined && unsafe) {
1043
+ throw new TypeError("[mcpify] pass either `auth` or `unsafeNoAuth: true`, not both");
1044
+ }
1045
+ if (auth !== undefined) {
1046
+ if (typeof auth !== "object" || auth === null) {
1047
+ throw new TypeError("[mcpify] auth must be an object");
1048
+ }
1049
+ return isRequestAuth(auth) ? { auth: null, guard: auth.verify.bind(auth) } : { auth: resolveAuth(auth), guard: null };
1050
+ }
1051
+ if (unsafe)
1052
+ return { auth: null, guard: null };
1053
+ throw new TypeError("[mcpify] refusing to mount an unauthenticated MCP endpoint: pass `auth: { verify(request) }`, " + "`auth: { resource, authorizationServers }`, or `unsafeNoAuth: true` for local development");
1054
+ }
1055
+ var printed = new Set;
1056
+ var printOnce = (message) => {
1057
+ if (printed.has(message))
1058
+ return;
1059
+ printed.add(message);
1060
+ console.warn(message);
1061
+ };
1062
+ var ADMISSION_KEYS = ["scopes", "tools", "readOnly"];
1063
+ function decide(value) {
1064
+ if (value === true)
1065
+ return { admit: true, admission: null };
1066
+ const denied = (problem) => ({
1067
+ admit: false,
1068
+ response: unauthorized(),
1069
+ ...problem ? { problem } : {}
1070
+ });
1071
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1072
+ return denied();
1073
+ const v = value;
1074
+ if ("status" in v) {
1075
+ const { status, code, message } = v;
1076
+ if (!Number.isInteger(status) || status < 400 || status > 599 || typeof message !== "string" || !message || code !== undefined && !Number.isInteger(code)) {
1077
+ return denied("returned a malformed refusal (want { status: 400-599, code?: integer, message })");
1078
+ }
1079
+ return {
1080
+ admit: false,
1081
+ response: rpcError(status, code ?? -32001, message, NO_STORE)
1082
+ };
1083
+ }
1084
+ if (!ADMISSION_KEYS.some((k) => (k in v))) {
1085
+ return denied("returned an object that is neither a refusal nor an admission (answered 401)");
1086
+ }
1087
+ const { scopes, tools, readOnly } = v;
1088
+ if (scopes !== undefined && !(Array.isArray(scopes) && scopes.every((s) => typeof s === "string")) || tools !== undefined && typeof tools !== "function" || readOnly !== undefined && typeof readOnly !== "boolean") {
1089
+ return denied("returned a malformed admission (want { scopes?: string[], tools?: (tool) => boolean, readOnly?: boolean })");
1090
+ }
1091
+ return { admit: true, admission: v };
1092
+ }
1093
+ var PLACEHOLDER_INFO = { title: "Elysia Documentation", version: "0.0.0" };
1094
+ var isDocument = (v) => typeof v === "object" && v !== null && typeof v.paths === "object" && v.paths !== null;
1095
+ var openapiModule;
1096
+ async function buildInProcess(app) {
1097
+ openapiModule ??= import("@elysiajs/openapi").catch(() => null);
1098
+ const mod = await openapiModule;
1099
+ if (!mod)
1100
+ return null;
1101
+ try {
1102
+ const doc = mod.toOpenAPISchema(app);
1103
+ return isDocument(doc) ? doc : null;
1104
+ } catch {
1105
+ return null;
1106
+ }
1107
+ }
1108
+ function mcpify(options) {
1109
+ const { auth, guard } = resolveAuthMode(options);
1110
+ const path = options.path ?? "/mcp";
1111
+ if (!path.startsWith("/"))
1112
+ throw new TypeError('[mcpify] path must start with "/"');
1113
+ const specPath = options.specPath ?? DEFAULT_SPEC_PATH;
1114
+ const serverInfoFor = (doc) => {
1115
+ const title = doc.info?.title;
1116
+ const version = doc.info?.version;
1117
+ return {
1118
+ name: options.name ?? (typeof title === "string" && title.trim() && title !== PLACEHOLDER_INFO.title ? title.trim() : "@20baht/elysia-openapi-mcp"),
1119
+ version: options.version ?? (typeof version === "string" && version.trim() && version !== PLACEHOLDER_INFO.version ? version.trim() : "1.0.0")
1120
+ };
1121
+ };
1122
+ const allRoutes = options.allRoutes ?? true;
1123
+ const wrapNonObjectOutput = options.wrapNonObjectOutput ?? true;
1124
+ const headerPolicy = options.headers ?? defaultHeaderPolicy;
1125
+ const cors = originPolicy(options.cors ?? guard === null);
1126
+ const sink = options.warn ?? printOnce;
1127
+ const silenced = silencedKinds(options.warnings);
1128
+ const emit = (w) => {
1129
+ if (!silenced.has(w.kind))
1130
+ sink(w.message, w.kind);
1131
+ };
1132
+ if (!auth && !guard)
1133
+ emit({ kind: "unauthenticated", message: UNAUTHENTICATED_WARNING });
1134
+ if (guard && options.cors === true) {
1135
+ emit({
1136
+ kind: "cors-reflects-origin",
1137
+ message: "[mcpify] cors: true with auth: { verify } reflects any Origin; if verify trusts cookies, any site can call your tools from a signed-in browser. Pass cors: { origins: [...] } instead."
1138
+ });
1139
+ }
1140
+ return (app) => {
1141
+ const emitted = new Set;
1142
+ const warnOnce = (w) => {
1143
+ if (emitted.has(w.message))
1144
+ return;
1145
+ emitted.add(w.message);
1146
+ emit(w);
1147
+ };
1148
+ const userHook = options.onToolCall;
1149
+ const onToolCall = userHook ? async (event) => {
1150
+ try {
1151
+ await userHook(event);
1152
+ } catch (e) {
1153
+ warnOnce({
1154
+ kind: "on-tool-call-error",
1155
+ message: `[mcpify] onToolCall threw for tool "${event.tool.name}": ${e instanceof Error ? e.message : String(e)}`
1156
+ });
1157
+ }
1158
+ } : undefined;
1159
+ let cached = null;
1160
+ let inflight = null;
1161
+ const loadDocument = async (origin) => {
1162
+ const source = options.document;
1163
+ if (typeof source === "function")
1164
+ return source({ origin, app });
1165
+ if (source)
1166
+ return source;
1167
+ let failure;
1168
+ try {
1169
+ const res = await app.handle(new Request(`${origin}${specPath}`, { headers: { accept: "application/json" } }));
1170
+ const doc = res.ok ? await res.json().catch(() => {
1171
+ return;
1172
+ }) : undefined;
1173
+ if (isDocument(doc))
1174
+ return doc;
1175
+ failure = res.ok ? "not an OpenAPI document" : `HTTP ${res.status}`;
1176
+ } catch (e) {
1177
+ failure = e instanceof Error ? e.message : String(e);
1178
+ }
1179
+ if (app.routes.some((r) => r.path === specPath)) {
1180
+ const built = await buildInProcess(app);
1181
+ if (built)
1182
+ return built;
1183
+ }
1184
+ throw new Error(`[mcpify] could not load the OpenAPI document from ${specPath} (${failure}). Mount @elysiajs/openapi (or pass \`document\`) before mcpify().`);
1185
+ };
1186
+ const buildTools = async (origin) => {
1187
+ const doc = await loadDocument(origin);
1188
+ const exclude = [
1189
+ ...options.excludeDefaults === false ? [] : DEFAULT_EXCLUDED_PATHS,
1190
+ ...options.exclude ?? [],
1191
+ path
1192
+ ];
1193
+ if (auth)
1194
+ exclude.push(auth.prmPath);
1195
+ const { tools, diagnostics } = deriveTools(doc, {
1196
+ allRoutes,
1197
+ tags: options.tags,
1198
+ wrapNonObjectOutput,
1199
+ headerParams: options.headerParams ?? false,
1200
+ exclude,
1201
+ stripPrefixes: [path]
1202
+ });
1203
+ for (const w of diagnostics)
1204
+ warnOnce(w);
1205
+ const exposed = auth?.requireToolScopes ? tools.filter((t) => {
1206
+ if (t.public || t.scopes.length > 0)
1207
+ return true;
1208
+ warnOnce({
1209
+ kind: "tool-hidden",
1210
+ message: `[mcpify] tool "${t.name}" hidden: requireToolScopes is set and it declares neither detail.mcp.scopes nor detail.mcp.public`
1211
+ });
1212
+ return false;
1213
+ }) : tools;
1214
+ if (!auth && !guard) {
1215
+ for (const t of tools) {
1216
+ if (t.scopes.length > 0) {
1217
+ warnOnce({
1218
+ kind: "scopes-not-enforced",
1219
+ message: `[mcpify] tool "${t.name}": detail.mcp.scopes is not enforced without OAuth \`auth\``
1220
+ });
1221
+ }
1222
+ }
1223
+ }
1224
+ return {
1225
+ tools: { list: exposed.map(toMcpTool), byName: new Map(exposed.map((t) => [t.name, t])) },
1226
+ serverInfo: serverInfoFor(doc)
1227
+ };
1228
+ };
1229
+ const getTools = (origin) => {
1230
+ const key = options.document && typeof options.document !== "function" ? 0 : app.routes.length;
1231
+ if (cached?.key === key)
1232
+ return Promise.resolve(cached.loaded);
1233
+ if (!inflight) {
1234
+ inflight = buildTools(origin).then((loaded) => {
1235
+ cached = { key, loaded };
1236
+ return loaded;
1237
+ }).finally(() => {
1238
+ inflight = null;
1239
+ });
1240
+ }
1241
+ return inflight;
1242
+ };
1243
+ const restrict = (tools, admission) => {
1244
+ if (!admission?.scopes) {
1245
+ for (const t of tools.byName.values()) {
1246
+ if (t.scopes.length > 0) {
1247
+ warnOnce({
1248
+ kind: "scopes-not-enforced",
1249
+ message: `[mcpify] tool "${t.name}": detail.mcp.scopes is not enforced: auth.verify admitted a request without returning { scopes }`
1250
+ });
1251
+ }
1252
+ }
1253
+ }
1254
+ if (!admission)
1255
+ return tools;
1256
+ const { scopes, tools: pick, readOnly } = admission;
1257
+ const keep = (t) => {
1258
+ if (scopes && !holdsToolScopes(t, scopes))
1259
+ return false;
1260
+ if (readOnly && t.annotations.readOnlyHint !== true)
1261
+ return false;
1262
+ if (!pick)
1263
+ return true;
1264
+ try {
1265
+ return pick(t);
1266
+ } catch (e) {
1267
+ warnOnce({
1268
+ kind: "verify-error",
1269
+ message: `[mcpify] the tools filter auth.verify returned threw for "${t.name}" (tool hidden): ${e instanceof Error ? e.message : String(e)}`
1270
+ });
1271
+ return false;
1272
+ }
1273
+ };
1274
+ const byName = new Map([...tools.byName].filter(([, t]) => keep(t)));
1275
+ return { list: tools.list.filter((t) => byName.has(t.name)), byName };
1276
+ };
1277
+ const handleMcp = async (request, rawBody) => {
1278
+ const extra = corsHeaders(request, cors);
1279
+ if (request.method === "OPTIONS")
1280
+ return new Response(null, { status: 204, headers: extra });
1281
+ let admission = null;
1282
+ if (guard) {
1283
+ let decision;
1284
+ try {
1285
+ decision = decide(await guard(request));
1286
+ } catch (e) {
1287
+ decision = {
1288
+ admit: false,
1289
+ response: unauthorized(),
1290
+ problem: `threw (answered 401): ${e instanceof Error ? e.message : String(e)}`
1291
+ };
1292
+ }
1293
+ if (!decision.admit) {
1294
+ if (decision.problem) {
1295
+ warnOnce({ kind: "verify-error", message: `[mcpify] auth.verify ${decision.problem}` });
1296
+ }
1297
+ return withHeaders(decision.response, extra);
1298
+ }
1299
+ admission = decision.admission;
1300
+ }
1301
+ let authInfo;
1302
+ if (auth && !(auth.allowAnonymous && !request.headers.has("authorization"))) {
1303
+ const outcome = await authenticate(request, auth);
1304
+ if (!outcome.ok)
1305
+ return withHeaders(outcome.response, extra);
1306
+ authInfo = outcome.authInfo;
1307
+ }
1308
+ if (request.method === "GET" || request.method === "DELETE") {
1309
+ return withHeaders(Response.json({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null }, { status: 405, headers: { allow: "POST" } }), extra);
1310
+ }
1311
+ const read = await readJsonBody(request, rawBody);
1312
+ if (!read.ok)
1313
+ return withHeaders(read.response, extra);
1314
+ const parsedBody = read.value;
1315
+ let loaded;
1316
+ try {
1317
+ loaded = await getTools(new URL(request.url).origin);
1318
+ } catch (e) {
1319
+ warnOnce({ kind: "document", message: e instanceof Error ? e.message : String(e) });
1320
+ return withHeaders(Response.json({ error: "server_error", error_description: "Could not load the tool definitions" }, { status: 500 }), extra);
1321
+ }
1322
+ const { serverInfo } = loaded;
1323
+ const tools = guard ? restrict(loaded.tools, admission) : loaded.tools;
1324
+ if (auth) {
1325
+ const denied = checkAccess(parsedBody, tools.byName, auth, authInfo);
1326
+ if (denied)
1327
+ return withHeaders(denied, extra);
1328
+ }
1329
+ const response = await serveMcp({
1330
+ request,
1331
+ app,
1332
+ tools,
1333
+ serverInfo,
1334
+ instructions: options.instructions,
1335
+ headerPolicy,
1336
+ authInfo,
1337
+ parsedBody,
1338
+ onToolCall
1339
+ });
1340
+ return withHeaders(response, extra);
1341
+ };
1342
+ const hidden = { hide: true, mcp: false };
1343
+ const root = app;
1344
+ root.all(path, ({ request, body }) => handleMcp(request, body), {
1345
+ parse: () => true,
1346
+ detail: hidden
1347
+ });
1348
+ if (auth) {
1349
+ const prm = protectedResourceMetadata(auth);
1350
+ root.get(auth.prmPath, ({ request }) => Response.json(prm, {
1351
+ headers: {
1352
+ ...corsHeaders(request, cors),
1353
+ "cache-control": "public, max-age=300"
1354
+ }
1355
+ }), { detail: hidden });
1356
+ root.options(auth.prmPath, ({ request }) => new Response(null, {
1357
+ status: 204,
1358
+ headers: { ...corsHeaders(request, cors), ...NO_STORE }
1359
+ }), { detail: hidden });
1360
+ }
1361
+ return app;
1362
+ };
1363
+ }
1364
+ export {
1365
+ verifyWithOAuthProvider,
1366
+ validateResourceUri,
1367
+ unflattenArgs,
1368
+ toolNameFor,
1369
+ toMcpTool,
1370
+ toCallToolResult,
1371
+ templateParams,
1372
+ simplifyNumeric,
1373
+ serveMcp,
1374
+ sanitizeToolName,
1375
+ resourcesEqual,
1376
+ resolveAuth,
1377
+ protectedResourceMetadata,
1378
+ outputSchemaFor,
1379
+ normalizeResource,
1380
+ metadataCandidates,
1381
+ mcpify,
1382
+ isToolCall,
1383
+ isExcluded,
1384
+ flattenOperation,
1385
+ extractBearer,
1386
+ elysiaDefaultOperationId,
1387
+ deriveTools,
1388
+ deriveToolName,
1389
+ dereference,
1390
+ defaultHeaderPolicy,
1391
+ createJwksVerifier,
1392
+ callTool,
1393
+ buildToolRequest,
1394
+ bearerChallenge,
1395
+ authenticate,
1396
+ audienceMatches,
1397
+ WRAPPED_RESULT_KEY,
1398
+ MCPIFY_WARNING_KINDS,
1399
+ DEFAULT_SPEC_PATH,
1400
+ DEFAULT_EXCLUDED_PATHS
1401
+ };
1402
+
1403
+ //# debugId=C5EE4AFDAF16E9E364756E2164756E21
1404
+ //# sourceMappingURL=index.js.map