@kubb/plugin-mcp 5.0.0-alpha.9 → 5.0.0-beta.10

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 CHANGED
@@ -1,122 +1,1005 @@
1
1
  import "./chunk--u3MIqq1.js";
2
- import { n as camelCase } from "./Server-KWLMg0Lm.js";
3
- import { n as mcpGenerator, t as serverGenerator } from "./generators-TtEOkDB1.js";
4
2
  import path from "node:path";
5
- import { createPlugin, getBarrelFiles, getMode } from "@kubb/core";
3
+ import { ast, defineGenerator, definePlugin, defineResolver } from "@kubb/core";
4
+ import { functionPrinter, pluginTsName } from "@kubb/plugin-ts";
5
+ import { Const, File, Function, jsxRenderer } from "@kubb/renderer-jsx";
6
+ import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
7
+ import { pluginZodName } from "@kubb/plugin-zod";
6
8
  import { pluginClientName } from "@kubb/plugin-client";
7
9
  import { source } from "@kubb/plugin-client/templates/clients/axios.source";
8
10
  import { source as source$1 } from "@kubb/plugin-client/templates/clients/fetch.source";
9
11
  import { source as source$2 } from "@kubb/plugin-client/templates/config.source";
10
- import { OperationGenerator, pluginOasName } from "@kubb/plugin-oas";
11
- import { pluginTsName } from "@kubb/plugin-ts";
12
- import { pluginZodName } from "@kubb/plugin-zod";
12
+ //#region ../../internals/utils/src/casing.ts
13
+ /**
14
+ * Shared implementation for camelCase and PascalCase conversion.
15
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
16
+ * and capitalizes each word according to `pascal`.
17
+ *
18
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
19
+ */
20
+ function toCamelOrPascal(text, pascal) {
21
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
22
+ if (word.length > 1 && word === word.toUpperCase()) return word;
23
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
24
+ return word.charAt(0).toUpperCase() + word.slice(1);
25
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
26
+ }
27
+ /**
28
+ * Splits `text` on `.` and applies `transformPart` to each segment.
29
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
30
+ * Segments are joined with `/` to form a file path.
31
+ *
32
+ * Only splits on dots followed by a letter so that version numbers
33
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
34
+ */
35
+ function applyToFileParts(text, transformPart) {
36
+ const parts = text.split(/\.(?=[a-zA-Z])/);
37
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
38
+ }
39
+ /**
40
+ * Converts `text` to camelCase.
41
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
42
+ *
43
+ * @example
44
+ * camelCase('hello-world') // 'helloWorld'
45
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
46
+ */
47
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
48
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
49
+ prefix,
50
+ suffix
51
+ } : {}));
52
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
53
+ }
54
+ //#endregion
55
+ //#region ../../internals/utils/src/reserved.ts
56
+ /**
57
+ * JavaScript and Java reserved words.
58
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
59
+ */
60
+ const reservedWords = new Set([
61
+ "abstract",
62
+ "arguments",
63
+ "boolean",
64
+ "break",
65
+ "byte",
66
+ "case",
67
+ "catch",
68
+ "char",
69
+ "class",
70
+ "const",
71
+ "continue",
72
+ "debugger",
73
+ "default",
74
+ "delete",
75
+ "do",
76
+ "double",
77
+ "else",
78
+ "enum",
79
+ "eval",
80
+ "export",
81
+ "extends",
82
+ "false",
83
+ "final",
84
+ "finally",
85
+ "float",
86
+ "for",
87
+ "function",
88
+ "goto",
89
+ "if",
90
+ "implements",
91
+ "import",
92
+ "in",
93
+ "instanceof",
94
+ "int",
95
+ "interface",
96
+ "let",
97
+ "long",
98
+ "native",
99
+ "new",
100
+ "null",
101
+ "package",
102
+ "private",
103
+ "protected",
104
+ "public",
105
+ "return",
106
+ "short",
107
+ "static",
108
+ "super",
109
+ "switch",
110
+ "synchronized",
111
+ "this",
112
+ "throw",
113
+ "throws",
114
+ "transient",
115
+ "true",
116
+ "try",
117
+ "typeof",
118
+ "var",
119
+ "void",
120
+ "volatile",
121
+ "while",
122
+ "with",
123
+ "yield",
124
+ "Array",
125
+ "Date",
126
+ "hasOwnProperty",
127
+ "Infinity",
128
+ "isFinite",
129
+ "isNaN",
130
+ "isPrototypeOf",
131
+ "length",
132
+ "Math",
133
+ "name",
134
+ "NaN",
135
+ "Number",
136
+ "Object",
137
+ "prototype",
138
+ "String",
139
+ "toString",
140
+ "undefined",
141
+ "valueOf"
142
+ ]);
143
+ /**
144
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * isValidVarName('status') // true
149
+ * isValidVarName('class') // false (reserved word)
150
+ * isValidVarName('42foo') // false (starts with digit)
151
+ * ```
152
+ */
153
+ function isValidVarName(name) {
154
+ if (!name || reservedWords.has(name)) return false;
155
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
156
+ }
157
+ //#endregion
158
+ //#region ../../internals/utils/src/urlPath.ts
159
+ /**
160
+ * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
161
+ *
162
+ * @example
163
+ * const p = new URLPath('/pet/{petId}')
164
+ * p.URL // '/pet/:petId'
165
+ * p.template // '`/pet/${petId}`'
166
+ */
167
+ var URLPath = class {
168
+ /**
169
+ * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
170
+ */
171
+ path;
172
+ #options;
173
+ constructor(path, options = {}) {
174
+ this.path = path;
175
+ this.#options = options;
176
+ }
177
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * new URLPath('/pet/{petId}').URL // '/pet/:petId'
182
+ * ```
183
+ */
184
+ get URL() {
185
+ return this.toURLPath();
186
+ }
187
+ /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
192
+ * new URLPath('/pet/{petId}').isURL // false
193
+ * ```
194
+ */
195
+ get isURL() {
196
+ try {
197
+ return !!new URL(this.path).href;
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+ /**
203
+ * Converts the OpenAPI path to a TypeScript template literal string.
204
+ *
205
+ * @example
206
+ * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
207
+ * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
208
+ */
209
+ get template() {
210
+ return this.toTemplateString();
211
+ }
212
+ /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * new URLPath('/pet/{petId}').object
217
+ * // { url: '/pet/:petId', params: { petId: 'petId' } }
218
+ * ```
219
+ */
220
+ get object() {
221
+ return this.toObject();
222
+ }
223
+ /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
224
+ *
225
+ * @example
226
+ * ```ts
227
+ * new URLPath('/pet/{petId}').params // { petId: 'petId' }
228
+ * new URLPath('/pet').params // undefined
229
+ * ```
230
+ */
231
+ get params() {
232
+ return this.toParamsObject();
233
+ }
234
+ #transformParam(raw) {
235
+ const param = isValidVarName(raw) ? raw : camelCase(raw);
236
+ return this.#options.casing === "camelcase" ? camelCase(param) : param;
237
+ }
238
+ /**
239
+ * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
240
+ */
241
+ #eachParam(fn) {
242
+ for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
243
+ const raw = match[1];
244
+ fn(raw, this.#transformParam(raw));
245
+ }
246
+ }
247
+ toObject({ type = "path", replacer, stringify } = {}) {
248
+ const object = {
249
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
250
+ params: this.toParamsObject()
251
+ };
252
+ if (stringify) {
253
+ if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
254
+ if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
255
+ return `{ url: '${object.url}' }`;
256
+ }
257
+ return object;
258
+ }
259
+ /**
260
+ * Converts the OpenAPI path to a TypeScript template literal string.
261
+ * An optional `replacer` can transform each extracted parameter name before interpolation.
262
+ *
263
+ * @example
264
+ * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
265
+ */
266
+ toTemplateString({ prefix = "", replacer } = {}) {
267
+ return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
268
+ if (i % 2 === 0) return part;
269
+ const param = this.#transformParam(part);
270
+ return `\${${replacer ? replacer(param) : param}}`;
271
+ }).join("")}\``;
272
+ }
273
+ /**
274
+ * Extracts all `{param}` segments from the path and returns them as a key-value map.
275
+ * An optional `replacer` transforms each parameter name in both key and value positions.
276
+ * Returns `undefined` when no path parameters are found.
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * new URLPath('/pet/{petId}/tag/{tagId}').toParamsObject()
281
+ * // { petId: 'petId', tagId: 'tagId' }
282
+ * ```
283
+ */
284
+ toParamsObject(replacer) {
285
+ const params = {};
286
+ this.#eachParam((_raw, param) => {
287
+ const key = replacer ? replacer(param) : param;
288
+ params[key] = key;
289
+ });
290
+ return Object.keys(params).length > 0 ? params : void 0;
291
+ }
292
+ /** Converts the OpenAPI path to Express-style colon syntax.
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
297
+ * ```
298
+ */
299
+ toURLPath() {
300
+ return this.path.replace(/\{([^}]+)\}/g, ":$1");
301
+ }
302
+ };
303
+ //#endregion
304
+ //#region ../../internals/shared/src/operation.ts
305
+ function getOperationLink(node, link) {
306
+ if (!link) return;
307
+ if (typeof link === "function") return link(node);
308
+ if (link === "urlPath") return node.path ? `{@link ${new URLPath(node.path).URL}}` : void 0;
309
+ return `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}`;
310
+ }
311
+ function buildOperationComments(node, options = {}) {
312
+ const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
313
+ const linkComment = getOperationLink(node, link);
314
+ const filteredComments = (linkPosition === "beforeDeprecated" ? [
315
+ node.description && `@description ${node.description}`,
316
+ node.summary && `@summary ${node.summary}`,
317
+ linkComment,
318
+ node.deprecated && "@deprecated"
319
+ ] : [
320
+ node.description && `@description ${node.description}`,
321
+ node.summary && `@summary ${node.summary}`,
322
+ node.deprecated && "@deprecated",
323
+ linkComment
324
+ ]).filter((comment) => Boolean(comment));
325
+ if (!splitLines) return filteredComments;
326
+ return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
327
+ }
328
+ function getOperationParameters(node, options = {}) {
329
+ const params = ast.caseParams(node.parameters, options.paramsCasing);
330
+ return {
331
+ path: params.filter((param) => param.in === "path"),
332
+ query: params.filter((param) => param.in === "query"),
333
+ header: params.filter((param) => param.in === "header"),
334
+ cookie: params.filter((param) => param.in === "cookie")
335
+ };
336
+ }
337
+ function getStatusCodeNumber(statusCode) {
338
+ const code = Number(statusCode);
339
+ return Number.isNaN(code) ? void 0 : code;
340
+ }
341
+ function isSuccessStatusCode(statusCode) {
342
+ const code = getStatusCodeNumber(statusCode);
343
+ return code !== void 0 && code >= 200 && code < 300;
344
+ }
345
+ function isErrorStatusCode(statusCode) {
346
+ const code = getStatusCodeNumber(statusCode);
347
+ return code !== void 0 && code >= 400;
348
+ }
349
+ function resolveErrorNames(node, resolver) {
350
+ return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
351
+ }
352
+ function resolveStatusCodeNames(node, resolver) {
353
+ return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
354
+ }
355
+ function resolveOperationTypeNames(node, resolver, options = {}) {
356
+ const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
357
+ const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
358
+ const exclude = new Set(options.exclude ?? []);
359
+ const paramNames = [
360
+ ...path.map((param) => resolver.resolvePathParamsName(node, param)),
361
+ ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
362
+ ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
363
+ ];
364
+ const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0, resolver.resolveResponseName(node)];
365
+ return (options.order === "body-response-first" ? [
366
+ ...bodyAndResponseNames,
367
+ ...paramNames,
368
+ ...responseStatusNames
369
+ ] : [
370
+ ...paramNames,
371
+ ...bodyAndResponseNames,
372
+ ...responseStatusNames
373
+ ]).filter((name) => Boolean(name) && !exclude.has(name));
374
+ }
375
+ function findSuccessStatusCode(responses) {
376
+ for (const response of responses) if (isSuccessStatusCode(response.statusCode)) return response.statusCode;
377
+ }
378
+ //#endregion
379
+ //#region ../../internals/shared/src/params.ts
380
+ function buildParamsMapping(originalParams, mappedParams) {
381
+ const mapping = {};
382
+ let hasChanged = false;
383
+ originalParams.forEach((param, i) => {
384
+ const mappedName = mappedParams[i]?.name ?? param.name;
385
+ mapping[param.name] = mappedName;
386
+ if (param.name !== mappedName) hasChanged = true;
387
+ });
388
+ return hasChanged ? mapping : void 0;
389
+ }
390
+ function buildTransformedParamsMapping(params, transformName) {
391
+ if (!params.length) return;
392
+ return buildParamsMapping(params, params.map((param) => ({
393
+ ...param,
394
+ name: transformName(param.name)
395
+ })));
396
+ }
397
+ //#endregion
398
+ //#region src/components/McpHandler.tsx
399
+ /**
400
+ * Generate a remapping statement: `const mappedX = x ? { "orig": x.camel, ... } : undefined`
401
+ */
402
+ function buildRemappingCode(mapping, varName, sourceName) {
403
+ return `const ${varName} = ${sourceName} ? { ${Object.entries(mapping).map(([orig, camel]) => `"${orig}": ${sourceName}.${camel}`).join(", ")} } : undefined`;
404
+ }
405
+ const declarationPrinter = functionPrinter({ mode: "declaration" });
406
+ function McpHandler({ name, node, resolver, baseURL, dataReturnType, paramsCasing }) {
407
+ const urlPath = new URLPath(node.path);
408
+ const contentType = node.requestBody?.content?.[0]?.contentType;
409
+ const isFormData = contentType === "multipart/form-data";
410
+ const { query: queryParams, header: headerParams } = getOperationParameters(node, { paramsCasing });
411
+ const { path: originalPathParams, query: originalQueryParams, header: originalHeaderParams } = getOperationParameters(node);
412
+ const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
413
+ const responseName = resolver.resolveResponseName(node);
414
+ const errorResponses = node.responses.filter((r) => Number(r.statusCode) >= 400).map((r) => resolver.resolveResponseStatusName(node, r.statusCode));
415
+ const generics = [
416
+ responseName,
417
+ `ResponseErrorConfig<${errorResponses.length > 0 ? errorResponses.join(" | ") : "Error"}>`,
418
+ requestName || "unknown"
419
+ ].filter(Boolean);
420
+ const paramsNode = ast.createOperationParams(node, {
421
+ paramsType: "object",
422
+ pathParamsType: "inline",
423
+ resolver,
424
+ paramsCasing
425
+ });
426
+ const baseParamsSignature = declarationPrinter.print(paramsNode) ?? "";
427
+ const paramsSignature = baseParamsSignature ? `${baseParamsSignature}, request: RequestHandlerExtra<ServerRequest, ServerNotification>` : "request: RequestHandlerExtra<ServerRequest, ServerNotification>";
428
+ const pathParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalPathParams, camelCase) : void 0;
429
+ const queryParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalQueryParams, camelCase) : void 0;
430
+ const headerParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalHeaderParams, camelCase) : void 0;
431
+ const contentTypeHeader = contentType && contentType !== "application/json" && contentType !== "multipart/form-data" ? `'Content-Type': '${contentType}'` : void 0;
432
+ const headers = [headerParams.length ? headerParamsMapping ? "...mappedHeaders" : "...headers" : void 0, contentTypeHeader].filter(Boolean);
433
+ const fetchConfig = [];
434
+ fetchConfig.push(`method: ${JSON.stringify(node.method.toUpperCase())}`);
435
+ fetchConfig.push(`url: ${urlPath.template}`);
436
+ if (baseURL) fetchConfig.push(`baseURL: \`${baseURL}\``);
437
+ if (queryParams.length) fetchConfig.push(queryParamsMapping ? "params: mappedParams" : "params");
438
+ if (requestName) fetchConfig.push(`data: ${isFormData ? "formData as FormData" : "requestData"}`);
439
+ if (headers.length) fetchConfig.push(`headers: { ${headers.join(", ")} }`);
440
+ const callToolResult = dataReturnType === "data" ? `return {
441
+ content: [
442
+ {
443
+ type: 'text',
444
+ text: JSON.stringify(res.data)
445
+ }
446
+ ],
447
+ structuredContent: { data: res.data }
448
+ }` : `return {
449
+ content: [
450
+ {
451
+ type: 'text',
452
+ text: JSON.stringify(res)
453
+ }
454
+ ],
455
+ structuredContent: { data: res.data }
456
+ }`;
457
+ return /* @__PURE__ */ jsx(File.Source, {
458
+ name,
459
+ isExportable: true,
460
+ isIndexable: true,
461
+ children: /* @__PURE__ */ jsxs(Function, {
462
+ name,
463
+ async: true,
464
+ export: true,
465
+ params: paramsSignature,
466
+ JSDoc: { comments: buildOperationComments(node) },
467
+ returnType: "Promise<CallToolResult>",
468
+ children: [
469
+ "",
470
+ /* @__PURE__ */ jsx("br", {}),
471
+ /* @__PURE__ */ jsx("br", {}),
472
+ pathParamsMapping && Object.entries(pathParamsMapping).filter(([originalName, camelCaseName]) => originalName !== camelCaseName && isValidVarName(originalName)).map(([originalName, camelCaseName]) => `const ${originalName} = ${camelCaseName}`).join("\n"),
473
+ pathParamsMapping && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("br", {}), /* @__PURE__ */ jsx("br", {})] }),
474
+ queryParamsMapping && queryParams.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
475
+ buildRemappingCode(queryParamsMapping, "mappedParams", "params"),
476
+ /* @__PURE__ */ jsx("br", {}),
477
+ /* @__PURE__ */ jsx("br", {})
478
+ ] }),
479
+ headerParamsMapping && headerParams.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
480
+ buildRemappingCode(headerParamsMapping, "mappedHeaders", "headers"),
481
+ /* @__PURE__ */ jsx("br", {}),
482
+ /* @__PURE__ */ jsx("br", {})
483
+ ] }),
484
+ requestName && "const requestData = data",
485
+ /* @__PURE__ */ jsx("br", {}),
486
+ isFormData && requestName && "const formData = buildFormData(requestData)",
487
+ /* @__PURE__ */ jsx("br", {}),
488
+ `const res = await fetch<${generics.join(", ")}>({ ${fetchConfig.join(", ")} }, request)`,
489
+ /* @__PURE__ */ jsx("br", {}),
490
+ callToolResult
491
+ ]
492
+ })
493
+ });
494
+ }
495
+ //#endregion
496
+ //#region src/utils.ts
497
+ /**
498
+ * Render a group param value — compose individual schemas into `z.object({ ... })`,
499
+ * or use a schema name string directly.
500
+ */
501
+ function zodGroupExpr(entry) {
502
+ if (typeof entry === "string") return entry;
503
+ return `z.object({ ${entry.map((p) => `${JSON.stringify(p.name)}: ${p.schemaName}`).join(", ")} })`;
504
+ }
505
+ /**
506
+ * Convert a SchemaNode type to an inline Zod expression string.
507
+ * Used as fallback when no named zod schema is available for a path parameter.
508
+ */
509
+ function zodExprFromSchemaNode(schema) {
510
+ let expr;
511
+ switch (schema.type) {
512
+ case "enum": {
513
+ const rawValues = schema.namedEnumValues?.length ? schema.namedEnumValues.map((v) => v.value) : (schema.enumValues ?? []).filter((v) => v !== null);
514
+ if (rawValues.length > 0 && rawValues.every((v) => typeof v === "string")) expr = `z.enum([${rawValues.map((v) => JSON.stringify(v)).join(", ")}])`;
515
+ else if (rawValues.length > 0) {
516
+ const literals = rawValues.map((v) => `z.literal(${JSON.stringify(v)})`);
517
+ expr = literals.length === 1 ? literals[0] : `z.union([${literals.join(", ")}])`;
518
+ } else expr = "z.string()";
519
+ break;
520
+ }
521
+ case "integer":
522
+ expr = "z.coerce.number()";
523
+ break;
524
+ case "number":
525
+ expr = "z.number()";
526
+ break;
527
+ case "boolean":
528
+ expr = "z.boolean()";
529
+ break;
530
+ case "array":
531
+ expr = "z.array(z.unknown())";
532
+ break;
533
+ default: expr = "z.string()";
534
+ }
535
+ if (schema.nullable) expr = `${expr}.nullable()`;
536
+ return expr;
537
+ }
538
+ //#endregion
539
+ //#region src/components/Server.tsx
540
+ const keysPrinter = functionPrinter({ mode: "keys" });
541
+ function Server({ name, serverName, serverVersion, paramsCasing, operations }) {
542
+ return /* @__PURE__ */ jsxs(File.Source, {
543
+ name,
544
+ isExportable: true,
545
+ isIndexable: true,
546
+ children: [
547
+ /* @__PURE__ */ jsx(Const, {
548
+ name: "server",
549
+ export: true,
550
+ children: `
551
+ new McpServer({
552
+ name: '${serverName}',
553
+ version: '${serverVersion}',
554
+ })
555
+ `
556
+ }),
557
+ operations.map(({ tool, mcp, zod, node }) => {
558
+ const { path: pathParams } = getOperationParameters(node, { paramsCasing });
559
+ const pathEntries = [];
560
+ const otherEntries = [];
561
+ for (const p of pathParams) {
562
+ const zodParam = zod.pathParams.find((zp) => zp.name === p.name);
563
+ pathEntries.push({
564
+ key: p.name,
565
+ value: zodParam ? zodParam.schemaName : zodExprFromSchemaNode(p.schema)
566
+ });
567
+ }
568
+ if (zod.requestName) otherEntries.push({
569
+ key: "data",
570
+ value: zod.requestName
571
+ });
572
+ if (zod.queryParams) otherEntries.push({
573
+ key: "params",
574
+ value: zodGroupExpr(zod.queryParams)
575
+ });
576
+ if (zod.headerParams) otherEntries.push({
577
+ key: "headers",
578
+ value: zodGroupExpr(zod.headerParams)
579
+ });
580
+ otherEntries.sort((a, b) => a.key.localeCompare(b.key));
581
+ const entries = [...pathEntries, ...otherEntries];
582
+ const paramsNode = entries.length ? ast.createFunctionParameters({ params: [ast.createParameterGroup({ properties: entries.map((e) => ast.createFunctionParameter({
583
+ name: e.key,
584
+ optional: false
585
+ })) })] }) : void 0;
586
+ const destructured = paramsNode ? keysPrinter.print(paramsNode) ?? "" : "";
587
+ const inputSchema = entries.length ? `{ ${entries.map((e) => `${e.key}: ${e.value}`).join(", ")} }` : void 0;
588
+ const outputSchema = zod.responseName;
589
+ const config = [
590
+ tool.title ? `title: ${JSON.stringify(tool.title)}` : null,
591
+ `description: ${JSON.stringify(tool.description)}`,
592
+ outputSchema ? `outputSchema: { data: ${outputSchema} }` : null
593
+ ].filter(Boolean).join(",\n ");
594
+ if (inputSchema) return `
595
+ server.registerTool(${JSON.stringify(tool.name)}, {
596
+ ${config},
597
+ inputSchema: ${inputSchema},
598
+ }, async (${destructured}, request) => {
599
+ return ${mcp.name}(${destructured}, request)
600
+ })
601
+ `;
602
+ return `
603
+ server.registerTool(${JSON.stringify(tool.name)}, {
604
+ ${config},
605
+ }, async (request) => {
606
+ return ${mcp.name}(request)
607
+ })
608
+ `;
609
+ }).filter(Boolean),
610
+ /* @__PURE__ */ jsx(Function, {
611
+ name: "startServer",
612
+ async: true,
613
+ export: true,
614
+ children: `try {
615
+ const transport = new StdioServerTransport()
616
+ await server.connect(transport)
617
+
618
+ } catch (error) {
619
+ console.error('Failed to start server:', error)
620
+ process.exit(1)
621
+ }`
622
+ })
623
+ ]
624
+ });
625
+ }
626
+ //#endregion
627
+ //#region src/generators/mcpGenerator.tsx
628
+ const mcpGenerator = defineGenerator({
629
+ name: "mcp",
630
+ renderer: jsxRenderer,
631
+ operation(node, ctx) {
632
+ const { resolver, driver, root } = ctx;
633
+ const { output, client, paramsCasing, group } = ctx.options;
634
+ const pluginTs = driver.getPlugin(pluginTsName);
635
+ if (!pluginTs) return null;
636
+ const tsResolver = driver.getResolver(pluginTsName);
637
+ const importedTypeNames = resolveOperationTypeNames(node, tsResolver, {
638
+ paramsCasing,
639
+ responseStatusNames: "error"
640
+ });
641
+ const meta = {
642
+ name: resolver.resolveHandlerName(node),
643
+ file: resolver.resolveFile({
644
+ name: node.operationId,
645
+ extname: ".ts",
646
+ tag: node.tags[0] ?? "default",
647
+ path: node.path
648
+ }, {
649
+ root,
650
+ output,
651
+ group
652
+ }),
653
+ fileTs: tsResolver.resolveFile({
654
+ name: node.operationId,
655
+ extname: ".ts",
656
+ tag: node.tags[0] ?? "default",
657
+ path: node.path
658
+ }, {
659
+ root,
660
+ output: pluginTs.options?.output ?? output,
661
+ group: pluginTs.options?.group
662
+ })
663
+ };
664
+ return /* @__PURE__ */ jsxs(File, {
665
+ baseName: meta.file.baseName,
666
+ path: meta.file.path,
667
+ meta: meta.file.meta,
668
+ children: [
669
+ meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
670
+ name: Array.from(new Set(importedTypeNames)).sort(),
671
+ root: meta.file.path,
672
+ path: meta.fileTs.path,
673
+ isTypeOnly: true
674
+ }),
675
+ /* @__PURE__ */ jsx(File.Import, {
676
+ name: [
677
+ "CallToolResult",
678
+ "ServerNotification",
679
+ "ServerRequest"
680
+ ],
681
+ path: "@modelcontextprotocol/sdk/types",
682
+ isTypeOnly: true
683
+ }),
684
+ /* @__PURE__ */ jsx(File.Import, {
685
+ name: ["RequestHandlerExtra"],
686
+ path: "@modelcontextprotocol/sdk/shared/protocol",
687
+ isTypeOnly: true
688
+ }),
689
+ /* @__PURE__ */ jsx(File.Import, {
690
+ name: ["buildFormData"],
691
+ root: meta.file.path,
692
+ path: path.resolve(root, ".kubb/config.ts")
693
+ }),
694
+ client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
695
+ /* @__PURE__ */ jsx(File.Import, {
696
+ name: [
697
+ "Client",
698
+ "RequestConfig",
699
+ "ResponseErrorConfig"
700
+ ],
701
+ path: client.importPath,
702
+ isTypeOnly: true
703
+ }),
704
+ /* @__PURE__ */ jsx(File.Import, {
705
+ name: "fetch",
706
+ path: client.importPath
707
+ }),
708
+ client.dataReturnType === "full" && /* @__PURE__ */ jsx(File.Import, {
709
+ name: ["ResponseConfig"],
710
+ path: client.importPath,
711
+ isTypeOnly: true
712
+ })
713
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
714
+ /* @__PURE__ */ jsx(File.Import, {
715
+ name: [
716
+ "Client",
717
+ "RequestConfig",
718
+ "ResponseErrorConfig"
719
+ ],
720
+ root: meta.file.path,
721
+ path: path.resolve(root, ".kubb/fetch.ts"),
722
+ isTypeOnly: true
723
+ }),
724
+ /* @__PURE__ */ jsx(File.Import, {
725
+ name: ["fetch"],
726
+ root: meta.file.path,
727
+ path: path.resolve(root, ".kubb/fetch.ts")
728
+ }),
729
+ client.dataReturnType === "full" && /* @__PURE__ */ jsx(File.Import, {
730
+ name: ["ResponseConfig"],
731
+ root: meta.file.path,
732
+ path: path.resolve(root, ".kubb/fetch.ts"),
733
+ isTypeOnly: true
734
+ })
735
+ ] }),
736
+ /* @__PURE__ */ jsx(McpHandler, {
737
+ name: meta.name,
738
+ node,
739
+ resolver: tsResolver,
740
+ baseURL: client.baseURL,
741
+ dataReturnType: client.dataReturnType || "data",
742
+ paramsCasing
743
+ })
744
+ ]
745
+ });
746
+ }
747
+ });
748
+ //#endregion
749
+ //#region src/generators/serverGenerator.tsx
750
+ /**
751
+ * Default v5 server generator for `@kubb/plugin-mcp`.
752
+ *
753
+ * Uses individual zod schemas for each param (e.g. `createPetsPathUuidSchema`, `createPetsQueryOffsetSchema`)
754
+ * and `resolveResponseStatusName` for per-status response schemas.
755
+ * Query and header params are composed into `z.object({ ... })` from individual schemas.
756
+ */
757
+ const serverGenerator = defineGenerator({
758
+ name: "operations",
759
+ renderer: jsxRenderer,
760
+ operations(nodes, ctx) {
761
+ const { adapter, config, resolver, plugin, driver, root } = ctx;
762
+ const { output, paramsCasing, group } = ctx.options;
763
+ const pluginZod = driver.getPlugin(pluginZodName);
764
+ if (!pluginZod) return;
765
+ const zodResolver = driver.getResolver(pluginZodName);
766
+ const name = "server";
767
+ const serverFile = {
768
+ baseName: "server.ts",
769
+ path: path.resolve(root, output.path, "server.ts"),
770
+ meta: { pluginName: plugin.name }
771
+ };
772
+ const jsonFile = {
773
+ baseName: ".mcp.json",
774
+ path: path.resolve(root, output.path, ".mcp.json"),
775
+ meta: { pluginName: plugin.name }
776
+ };
777
+ const operationsMapped = nodes.map((node) => {
778
+ const { path: pathParams, query: queryParams, header: headerParams } = getOperationParameters(node, { paramsCasing });
779
+ const mcpFile = resolver.resolveFile({
780
+ name: node.operationId,
781
+ extname: ".ts",
782
+ tag: node.tags[0] ?? "default",
783
+ path: node.path
784
+ }, {
785
+ root,
786
+ output,
787
+ group
788
+ });
789
+ const zodFile = zodResolver.resolveFile({
790
+ name: node.operationId,
791
+ extname: ".ts",
792
+ tag: node.tags[0] ?? "default",
793
+ path: node.path
794
+ }, {
795
+ root,
796
+ output: pluginZod.options?.output ?? output,
797
+ group: pluginZod.options?.group
798
+ });
799
+ const requestName = node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName(node) : void 0;
800
+ const successStatus = findSuccessStatusCode(node.responses);
801
+ const responseName = successStatus ? zodResolver.resolveResponseStatusName(node, successStatus) : void 0;
802
+ const resolveParams = (params) => params.map((p) => ({
803
+ name: p.name,
804
+ schemaName: zodResolver.resolveParamName(node, p)
805
+ }));
806
+ return {
807
+ tool: {
808
+ name: node.operationId,
809
+ title: node.summary || void 0,
810
+ description: node.description || `Make a ${node.method.toUpperCase()} request to ${node.path}`
811
+ },
812
+ mcp: {
813
+ name: resolver.resolveHandlerName(node),
814
+ file: mcpFile
815
+ },
816
+ zod: {
817
+ pathParams: resolveParams(pathParams),
818
+ queryParams: queryParams.length ? resolveParams(queryParams) : void 0,
819
+ headerParams: headerParams.length ? resolveParams(headerParams) : void 0,
820
+ requestName,
821
+ responseName,
822
+ file: zodFile
823
+ },
824
+ node
825
+ };
826
+ });
827
+ const imports = operationsMapped.flatMap(({ mcp, zod }) => {
828
+ const zodNames = [
829
+ ...zod.pathParams.map((p) => p.schemaName),
830
+ ...(zod.queryParams ?? []).map((p) => p.schemaName),
831
+ ...(zod.headerParams ?? []).map((p) => p.schemaName),
832
+ zod.requestName,
833
+ zod.responseName
834
+ ].filter((name) => Boolean(name));
835
+ const uniqueNames = [...new Set(zodNames)].sort();
836
+ return [/* @__PURE__ */ jsx(File.Import, {
837
+ name: [mcp.name],
838
+ root: serverFile.path,
839
+ path: mcp.file.path
840
+ }, mcp.name), uniqueNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
841
+ name: uniqueNames,
842
+ root: serverFile.path,
843
+ path: zod.file.path
844
+ }, `zod-${mcp.name}`)].filter(Boolean);
845
+ });
846
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(File, {
847
+ baseName: serverFile.baseName,
848
+ path: serverFile.path,
849
+ meta: serverFile.meta,
850
+ banner: resolver.resolveBanner(adapter.inputNode, {
851
+ output,
852
+ config
853
+ }),
854
+ footer: resolver.resolveFooter(adapter.inputNode, {
855
+ output,
856
+ config
857
+ }),
858
+ children: [
859
+ /* @__PURE__ */ jsx(File.Import, {
860
+ name: ["McpServer"],
861
+ path: "@modelcontextprotocol/sdk/server/mcp"
862
+ }),
863
+ /* @__PURE__ */ jsx(File.Import, {
864
+ name: ["z"],
865
+ path: "zod"
866
+ }),
867
+ /* @__PURE__ */ jsx(File.Import, {
868
+ name: ["StdioServerTransport"],
869
+ path: "@modelcontextprotocol/sdk/server/stdio"
870
+ }),
871
+ imports,
872
+ /* @__PURE__ */ jsx(Server, {
873
+ name,
874
+ serverName: adapter.inputNode?.meta?.title ?? "server",
875
+ serverVersion: adapter.inputNode?.meta?.version ?? "0.0.0",
876
+ paramsCasing,
877
+ operations: operationsMapped
878
+ })
879
+ ]
880
+ }), /* @__PURE__ */ jsx(File, {
881
+ baseName: jsonFile.baseName,
882
+ path: jsonFile.path,
883
+ meta: jsonFile.meta,
884
+ children: /* @__PURE__ */ jsx(File.Source, {
885
+ name,
886
+ children: `
887
+ {
888
+ "mcpServers": {
889
+ "${adapter.inputNode?.meta?.title || "server"}": {
890
+ "type": "stdio",
891
+ "command": "npx",
892
+ "args": ["tsx", "${path.relative(path.dirname(jsonFile.path), serverFile.path)}"]
893
+ }
894
+ }
895
+ }
896
+ `
897
+ })
898
+ })] });
899
+ }
900
+ });
901
+ //#endregion
902
+ //#region src/resolvers/resolverMcp.ts
903
+ /**
904
+ * Naming convention resolver for MCP plugin.
905
+ *
906
+ * Provides default naming helpers using camelCase with a `handler` suffix for functions.
907
+ *
908
+ * @example
909
+ * `resolverMcp.default('addPet', 'function') // → 'addPetHandler'`
910
+ */
911
+ const resolverMcp = defineResolver(() => ({
912
+ name: "default",
913
+ pluginName: "plugin-mcp",
914
+ default(name, type) {
915
+ if (type === "file") return camelCase(name, { isFile: true });
916
+ return camelCase(name, { suffix: "handler" });
917
+ },
918
+ resolveName(name) {
919
+ return this.default(name, "function");
920
+ },
921
+ resolvePathName(name, type) {
922
+ return this.default(name, type);
923
+ },
924
+ resolveHandlerName(node) {
925
+ return this.resolveName(node.operationId);
926
+ }
927
+ }));
928
+ //#endregion
13
929
  //#region src/plugin.ts
14
930
  const pluginMcpName = "plugin-mcp";
15
- const pluginMcp = createPlugin((options) => {
931
+ const pluginMcp = definePlugin((options) => {
16
932
  const { output = {
17
933
  path: "mcp",
18
934
  barrelType: "named"
19
- }, group, exclude = [], include, override = [], transformers = {}, generators = [mcpGenerator, serverGenerator].filter(Boolean), contentType, paramsCasing, client } = options;
935
+ }, group, exclude = [], include, override = [], paramsCasing, client, resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = options;
20
936
  const clientName = client?.client ?? "axios";
21
937
  const clientImportPath = client?.importPath ?? (!client?.bundle ? `@kubb/plugin-client/clients/${clientName}` : void 0);
938
+ const groupConfig = group ? {
939
+ ...group,
940
+ name: group.name ? group.name : (ctx) => {
941
+ if (group.type === "path") return `${ctx.group.split("/")[1]}`;
942
+ return `${camelCase(ctx.group)}Requests`;
943
+ }
944
+ } : void 0;
22
945
  return {
23
946
  name: pluginMcpName,
24
- options: {
25
- output,
26
- group,
27
- paramsCasing,
28
- client: {
29
- client: clientName,
30
- clientType: client?.clientType ?? "function",
31
- importPath: clientImportPath,
32
- dataReturnType: client?.dataReturnType ?? "data",
33
- bundle: client?.bundle,
34
- baseURL: client?.baseURL,
35
- paramsCasing: client?.paramsCasing
36
- }
37
- },
38
- pre: [
39
- pluginOasName,
40
- pluginTsName,
41
- pluginZodName
42
- ].filter(Boolean),
43
- resolvePath(baseName, pathMode, options) {
44
- const root = path.resolve(this.config.root, this.config.output.path);
45
- if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single")
46
- /**
47
- * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
48
- * Other plugins then need to call addOrAppend instead of just add from the fileManager class
49
- */
50
- return path.resolve(root, output.path);
51
- if (group && (options?.group?.path || options?.group?.tag)) {
52
- const groupName = group?.name ? group.name : (ctx) => {
53
- if (group?.type === "path") return `${ctx.group.split("/")[1]}`;
54
- return `${camelCase(ctx.group)}Requests`;
55
- };
56
- return path.resolve(root, output.path, groupName({ group: group.type === "path" ? options.group.path : options.group.tag }), baseName);
57
- }
58
- return path.resolve(root, output.path, baseName);
59
- },
60
- resolveName(name, type) {
61
- const resolvedName = camelCase(name, { isFile: type === "file" });
62
- if (type) return transformers?.name?.(resolvedName, type) || resolvedName;
63
- return resolvedName;
64
- },
65
- async install() {
66
- const root = path.resolve(this.config.root, this.config.output.path);
67
- const mode = getMode(path.resolve(root, output.path));
68
- const oas = await this.getOas();
69
- const baseURL = await this.getBaseURL();
70
- if (baseURL) this.plugin.options.client.baseURL = baseURL;
71
- const hasClientPlugin = !!this.driver.getPluginByName(pluginClientName);
72
- if (this.plugin.options.client.bundle && !hasClientPlugin && !this.plugin.options.client.importPath) await this.addFile({
947
+ options,
948
+ dependencies: [pluginTsName, pluginZodName],
949
+ hooks: { "kubb:plugin:setup"(ctx) {
950
+ const resolver = userResolver ? {
951
+ ...resolverMcp,
952
+ ...userResolver
953
+ } : resolverMcp;
954
+ ctx.setOptions({
955
+ output,
956
+ exclude,
957
+ include,
958
+ override,
959
+ group: groupConfig,
960
+ paramsCasing,
961
+ client: {
962
+ client: clientName,
963
+ clientType: client?.clientType ?? "function",
964
+ importPath: clientImportPath,
965
+ dataReturnType: client?.dataReturnType ?? "data",
966
+ bundle: client?.bundle,
967
+ baseURL: client?.baseURL,
968
+ paramsCasing: client?.paramsCasing
969
+ },
970
+ resolver
971
+ });
972
+ ctx.setResolver(resolver);
973
+ if (userTransformer) ctx.setTransformer(userTransformer);
974
+ ctx.addGenerator(mcpGenerator);
975
+ ctx.addGenerator(serverGenerator);
976
+ for (const gen of userGenerators) ctx.addGenerator(gen);
977
+ const root = path.resolve(ctx.config.root, ctx.config.output.path);
978
+ const hasClientPlugin = ctx.config.plugins?.some((p) => p.name === pluginClientName);
979
+ if (client?.bundle && !hasClientPlugin && !clientImportPath) ctx.injectFile({
73
980
  baseName: "fetch.ts",
74
981
  path: path.resolve(root, ".kubb/fetch.ts"),
75
- sources: [{
982
+ sources: [ast.createSource({
76
983
  name: "fetch",
77
- value: this.plugin.options.client.client === "fetch" ? source$1 : source,
984
+ nodes: [ast.createText(clientName === "fetch" ? source$1 : source)],
78
985
  isExportable: true,
79
986
  isIndexable: true
80
- }],
81
- imports: [],
82
- exports: []
987
+ })]
83
988
  });
84
- if (!hasClientPlugin) await this.addFile({
989
+ if (!hasClientPlugin) ctx.injectFile({
85
990
  baseName: "config.ts",
86
991
  path: path.resolve(root, ".kubb/config.ts"),
87
- sources: [{
992
+ sources: [ast.createSource({
88
993
  name: "config",
89
- value: source$2,
994
+ nodes: [ast.createText(source$2)],
90
995
  isExportable: false,
91
996
  isIndexable: false
92
- }],
93
- imports: [],
94
- exports: []
997
+ })]
95
998
  });
96
- const files = await new OperationGenerator(this.plugin.options, {
97
- fabric: this.fabric,
98
- oas,
99
- driver: this.driver,
100
- events: this.events,
101
- plugin: this.plugin,
102
- contentType,
103
- exclude,
104
- include,
105
- override,
106
- mode
107
- }).build(...generators);
108
- await this.upsertFile(...files);
109
- const barrelFiles = await getBarrelFiles(this.fabric.files, {
110
- type: output.barrelType ?? "named",
111
- root,
112
- output,
113
- meta: { pluginName: this.plugin.name }
114
- });
115
- await this.upsertFile(...barrelFiles);
116
- }
999
+ } }
117
1000
  };
118
1001
  });
119
1002
  //#endregion
120
- export { pluginMcp, pluginMcpName };
1003
+ export { McpHandler, Server, pluginMcp as default, pluginMcp, mcpGenerator, pluginMcpName, resolverMcp, serverGenerator };
121
1004
 
122
1005
  //# sourceMappingURL=index.js.map