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