@kubb/plugin-mcp 5.5.0-canary.20261111T115959 → 5.5.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.cjs CHANGED
@@ -30,6 +30,38 @@ let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
30
30
  let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
31
31
  let _kubb_plugin_ts = require("@kubb/plugin-ts");
32
32
  let _kubb_plugin_zod = require("@kubb/plugin-zod");
33
+ // ../../internals/utils/src/fs.ts
34
+ function toSlash(p) {
35
+ if (p.startsWith("\\\\?\\")) return p;
36
+ return p.replaceAll("\\", "/");
37
+ }
38
+ /**
39
+ * Returns the relative path from `rootDir` to `filePath`, always using forward slashes
40
+ * and prefixed with `./` when not already traversing upward.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'
45
+ * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'
46
+ * ```
47
+ */
48
+ function getRelativePath(rootDir, filePath) {
49
+ const relativePath = node_path.posix.relative(toSlash(rootDir), toSlash(filePath));
50
+ return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
51
+ }
52
+ // ../../internals/utils/src/strings.ts
53
+ /**
54
+ * Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
55
+ * Editors render `\@` as `@` in hovers.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
60
+ * ```
61
+ */
62
+ function jsDocEscape(input) {
63
+ return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
64
+ }
33
65
  // ../../internals/shared/src/operation.ts
34
66
  /**
35
67
  * Builds the `ResolverFileParams` every operation generator passes to
@@ -99,7 +131,7 @@ function resolveOperationFile(options) {
99
131
  * The operation's method and path as plain text, such as `` `GET /pet/{petId}` ``. A path is not a valid `{@link}` target.
100
132
  */
101
133
  function getOperationRequestLine(node) {
102
- return _kubb_kit.ast.isHttpOperationNode(node) && node.path ? `\`${node.method.toUpperCase()} ${node.path}\`` : null;
134
+ return _kubb_kit.ast.http.isOperation(node) && node.path ? `\`${node.method.toUpperCase()} ${node.path}\`` : null;
103
135
  }
104
136
  /**
105
137
  * Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several
@@ -123,7 +155,48 @@ function getContentTypeInfo(node) {
123
155
  * whether several are present, so the client can let a caller pick which one to accept.
124
156
  */
125
157
  function getResponseContentTypeInfo(node) {
126
- return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? []);
158
+ return buildContentTypeInfo(_kubb_kit.ast.http.responses.findPrimary(node)?.content?.map((e) => e.contentType) ?? []);
159
+ }
160
+ /**
161
+ * How an operation streams its primary success response item by item, when that response declares one content type:
162
+ * - `'event'` for `text/event-stream` whose `itemSchema` types the whole event with its own `event` and `data`
163
+ * - `'data'` for `text/event-stream` typed by its payload only
164
+ * - `'line'` for JSON Lines, one parsed JSON value per line
165
+ *
166
+ * Returns `null` for any other response, and for a response that also declares another content type, which stays a normal
167
+ * call with its query hooks.
168
+ */
169
+ function getEventStream(node) {
170
+ const content = _kubb_kit.ast.http.responses.findPrimary(node)?.content ?? [];
171
+ if (content.length !== 1) return null;
172
+ const entry = content[0];
173
+ const framing = getStreamFraming(entry);
174
+ if (framing === "events") return entry.stream?.shape ?? "data";
175
+ return framing === "lines" ? "line" : null;
176
+ }
177
+ /**
178
+ * How a content entry is framed as a stream: `'events'` for Server-Sent Events, `'lines'` for JSON Lines.
179
+ */
180
+ function getStreamFraming(entry) {
181
+ if (_kubb_kit.ast.mediaType.getBase(entry) === "text/event-stream") return "events";
182
+ return entry.stream && _kubb_kit.ast.mediaType.isStream(entry) ? "lines" : void 0;
183
+ }
184
+ /**
185
+ * Whether an operation streams its primary success response, as Server-Sent Events or JSON Lines. The client generator uses
186
+ * this to return a typed stream of items instead of a one-shot `RequestResult`.
187
+ */
188
+ function isEventStream(node) {
189
+ return getEventStream(node) !== null;
190
+ }
191
+ /**
192
+ * Whether a success response offers a stream media type next to other content types. The client returns that variant's
193
+ * body as a `ReadableStream`, so the stream runtime is registered and a hook's data type includes the stream.
194
+ */
195
+ function hasStreamVariant(node) {
196
+ return _kubb_kit.ast.http.responses.filterSuccess(node).some((response) => {
197
+ const variants = (response.content ?? []).filter((entry) => entry.schema);
198
+ return variants.length > 1 && variants.some((entry) => _kubb_kit.ast.mediaType.isStream(entry));
199
+ });
127
200
  }
128
201
  /**
129
202
  * Builds the `client?:` option type shared by the generated query hooks (`useQuery`,
@@ -166,11 +239,11 @@ const requestGroupOrder = [
166
239
  * Which of the grouped request options an operation carries.
167
240
  */
168
241
  function getRequestGroups(node) {
169
- const { path, query, header, cookie } = getOperationParameters(node);
242
+ const { path, query, header, cookie } = _kubb_kit.ast.http.groupParameters(node);
170
243
  return {
171
244
  path: path.length > 0,
172
245
  query: query.length > 0,
173
- body: Boolean(node.requestBody?.content?.[0]?.schema),
246
+ body: Boolean(_kubb_kit.ast.http.requestBody.getSchema(node)),
174
247
  headers: header.length > 0,
175
248
  cookies: cookie.length > 0
176
249
  };
@@ -182,7 +255,7 @@ function getRequestGroups(node) {
182
255
  */
183
256
  function getRequestGroupOptionality(node) {
184
257
  const groups = getRequestGroups(node);
185
- const { path, query, header } = getOperationParameters(node);
258
+ const { path, query, header } = _kubb_kit.ast.http.groupParameters(node);
186
259
  const hasRequiredPath = path.some((param) => param.required);
187
260
  const hasRequiredQuery = query.some((param) => param.required);
188
261
  const hasRequiredHeader = header.some((param) => param.required);
@@ -217,55 +290,12 @@ function buildOperationComments(node, options = {}) {
217
290
  getOperationRequestLine(node),
218
291
  node.description && `@description ${node.description}`,
219
292
  node.summary && `@summary ${node.summary}`,
220
- node.deprecated && "@deprecated"
293
+ node.deprecated && "@deprecated",
294
+ node.externalDocs && `@see ${jsDocEscape([node.externalDocs.url, node.externalDocs.description].filter(Boolean).join(" "))}`
221
295
  ].filter((comment) => Boolean(comment));
222
296
  if (!splitLines) return filteredComments;
223
297
  return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
224
298
  }
225
- const operationParameterGroupsByNode = /* @__PURE__ */ new WeakMap();
226
- /**
227
- * An OpenAPI 3.2 `querystring` parameter is the whole query string, so a form-encoded object becomes one query parameter
228
- * per property, typed and serialized like any other.
229
- * Another content type, such as JSON, stays one parameter named after it, and the runtime sends its value as the whole query string.
230
- */
231
- function spreadQuerystring(param) {
232
- const schema = param.schema.type === "ref" ? param.schema.schema : param.schema;
233
- const formEncoded = !param.contentType || param.contentType.split(";")[0].trim().toLowerCase() === "application/x-www-form-urlencoded";
234
- if (schema?.type !== "object" || !formEncoded) return [param];
235
- return schema.properties.map((property) => _kubb_kit.ast.factory.createParameter({
236
- name: property.name,
237
- in: "query",
238
- schema: property.schema,
239
- required: param.required && property.required
240
- }));
241
- }
242
- /**
243
- * Groups an operation's parameters by location (`path`/`query`/`header`/`cookie`), deduping each
244
- * group by name. Every plugin generator visiting the same `OperationNode` shares one AST instance
245
- * (see `KubbDriver`), so the result is cached per node to avoid re-filtering and re-deduping the
246
- * same parameters once per plugin.
247
- */
248
- function getOperationParameters(node) {
249
- const cached = operationParameterGroupsByNode.get(node);
250
- if (cached) return cached;
251
- const dedupe = (params) => {
252
- const seen = /* @__PURE__ */ new Set();
253
- return params.filter((param) => {
254
- if (seen.has(param.name)) return false;
255
- seen.add(param.name);
256
- return true;
257
- });
258
- };
259
- const group = (location) => dedupe(node.parameters.filter((param) => param.in === location));
260
- const groups = {
261
- path: group("path"),
262
- query: dedupe([...group("query"), ...group("querystring").flatMap(spreadQuerystring)]),
263
- header: group("header"),
264
- cookie: group("cookie")
265
- };
266
- operationParameterGroupsByNode.set(node, groups);
267
- return groups;
268
- }
269
299
  /**
270
300
  * Whether the operation declares more than one request media type with a schema, so a caller must pick one on `contentType`.
271
301
  */
@@ -278,48 +308,15 @@ function hasRequestContentTypeChoice(node) {
278
308
  function castToClientOptions(callArg, clientName, returnType = "full") {
279
309
  return `${callArg} as Parameters<typeof ${clientName}${returnType === "plain" ? "" : "<true>"}>[0]`;
280
310
  }
281
- function getStatusCodeNumber(statusCode) {
282
- const code = Number(statusCode);
283
- return Number.isNaN(code) ? null : code;
284
- }
285
- function isSuccessStatusCode(statusCode) {
286
- const code = getStatusCodeNumber(statusCode);
287
- return code !== null && code >= 200 && code < 300;
288
- }
289
- function getSuccessResponses(responses) {
290
- return responses.filter((response) => isSuccessStatusCode(response.statusCode));
291
- }
292
- function getOperationSuccessResponses(node) {
293
- return getSuccessResponses(node.responses);
294
- }
295
- function getPrimarySuccessResponse(node) {
296
- return getOperationSuccessResponses(node)[0] ?? null;
297
- }
298
- // ../../internals/utils/src/fs.ts
299
- function toSlash(p) {
300
- if (p.startsWith("\\\\?\\")) return p;
301
- return p.replaceAll("\\", "/");
302
- }
303
- /**
304
- * Returns the relative path from `rootDir` to `filePath`, always using forward slashes
305
- * and prefixed with `./` when not already traversing upward.
306
- *
307
- * @example
308
- * ```ts
309
- * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'
310
- * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'
311
- * ```
312
- */
313
- function getRelativePath(rootDir, filePath) {
314
- const relativePath = node_path.posix.relative(toSlash(rootDir), toSlash(filePath));
315
- return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
316
- }
317
311
  // ../../internals/shared/src/resolver.ts
318
312
  /**
319
313
  * Builds the allocation key for a declaration an operation owns. `scope` names which declaration
320
314
  * it is, so two of them never share an allocation even when a custom resolver gives both the same
321
315
  * name. Leave `scope` empty for the operation's own declaration.
322
316
  *
317
+ * The key starts from the operation's input `pointer`, which macros keep, so a plugin whose macro
318
+ * rewrites the method or path still resolves another plugin's names for the same operation.
319
+ *
323
320
  * @example
324
321
  * ```ts
325
322
  * resolver.resolveName({ key: operationKey(node, 'response', 'status', 404), name })
@@ -328,41 +325,10 @@ function getRelativePath(rootDir, filePath) {
328
325
  function operationKey(node, ...scope) {
329
326
  return [
330
327
  "operation",
331
- node.method,
332
- node.path,
328
+ ...node.pointer ? [node.pointer] : [node.method, node.path],
333
329
  ...scope.map(String)
334
330
  ];
335
331
  }
336
- // ../../internals/shared/src/group.ts
337
- /**
338
- * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
339
- * shared default naming so every plugin groups output consistently:
340
- *
341
- * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
342
- * - other groups use the camelCased group (`pet store` → `petStore`).
343
- *
344
- * A user-provided `group.name` always wins over the default namer, so callers stay in
345
- * control of their output folders. Returns `null` when grouping is disabled, matching the
346
- * per-plugin convention.
347
- *
348
- * @param group - The user-supplied group option, or `undefined` to disable grouping.
349
- *
350
- * @example
351
- * ```ts
352
- * createGroupConfig(group) // shared across every plugin
353
- * ```
354
- */
355
- function createGroupConfig(group) {
356
- if (!group) return null;
357
- const defaultName = (ctx) => {
358
- if (group.type === "path") return `${ctx.group.split("/")[1]}`;
359
- return (0, _kubb_kit.camelCase)(ctx.group);
360
- };
361
- return {
362
- ...group,
363
- name: group.name ? group.name : defaultName
364
- };
365
- }
366
332
  // src/components/McpHandler.tsx
367
333
  function McpHandler({ name, clientName, node, resolver, returnType = "full" }) {
368
334
  const { signature, names: callArgs } = buildRequestParamsSignature(node, resolver, { isConfigurable: false });
@@ -416,7 +382,7 @@ function Server({ serverName, serverVersion, operations }) {
416
382
  });
417
383
  if (zod.queryParams) entries.push({
418
384
  key: "query",
419
- value: zodObject(zod.queryParams)
385
+ value: typeof zod.queryParams === "string" ? zod.queryParams : zodObject(zod.queryParams)
420
386
  });
421
387
  if (zod.headerParams) entries.push({
422
388
  key: "headers",
@@ -463,8 +429,8 @@ server.registerTool(${JSON.stringify(tool.name)}, {
463
429
  name: "getServer",
464
430
  export: true,
465
431
  children: `const server = new McpServer({
466
- name: '${serverName}',
467
- version: '${serverVersion}',
432
+ name: ${_kubb_kit.text.quote(serverName)},
433
+ version: ${_kubb_kit.text.quote(serverVersion)},
468
434
  })
469
435
  ${registrations}
470
436
  return server`
@@ -664,7 +630,8 @@ function resolveClientOperation(options) {
664
630
  operationFile: file.path
665
631
  }),
666
632
  clientPathIsFile: importPath === void 0 || isRelativeImport(importPath),
667
- returnType: operationOptions.returnType ?? "full"
633
+ returnType: operationOptions.returnType ?? "full",
634
+ typedHeaders: importPath === void 0
668
635
  };
669
636
  });
670
637
  }
@@ -692,6 +659,7 @@ function toZodTypeResolver(resolver) {
692
659
  status: (node, statusCode) => type(resolver.response.status(node, statusCode)),
693
660
  response: (node) => type(resolver.response.response(node)),
694
661
  responses: (node) => type(resolver.response.responses(node)),
662
+ headers: (node, statusCode) => type(resolver.response.headers(node, statusCode)),
695
663
  options: (node) => resolver.response.options(node)
696
664
  }
697
665
  };
@@ -750,7 +718,8 @@ const mcpGenerator = (0, _kubb_kit.defineGenerator)({
750
718
  name: "mcp",
751
719
  renderer: _kubb_renderer_jsx.jsxRenderer,
752
720
  operation(node, ctx) {
753
- if (!_kubb_kit.ast.isHttpOperationNode(node)) return null;
721
+ if (!_kubb_kit.ast.http.isOperation(node)) return null;
722
+ if (isEventStream(node) || hasStreamVariant(node)) return null;
754
723
  const { resolver, driver, root, config } = ctx;
755
724
  const { output, client, group } = ctx.options;
756
725
  const types = resolveOperationTypes(driver, resolver.pluginName);
@@ -859,8 +828,8 @@ const serverGenerator = (0, _kubb_kit.defineGenerator)({
859
828
  command: "npx",
860
829
  args: ["tsx", getRelativePath(node_path.default.resolve(config.root), startFile.path)]
861
830
  } } };
862
- const operationsMapped = nodes.filter(_kubb_kit.ast.isHttpOperationNode).map((node) => {
863
- const { path: pathParams, query: queryParams, header: headerParams, cookie: cookieParams } = getOperationParameters(node);
831
+ const operationsMapped = nodes.filter(_kubb_kit.ast.http.isOperation).filter((node) => !isEventStream(node) && !hasStreamVariant(node)).map((node) => {
832
+ const { path: pathParams, query: queryParams, header: headerParams, cookie: cookieParams } = _kubb_kit.ast.http.groupParameters(node);
864
833
  const mcpFile = resolver.file({
865
834
  ...operationFileEntry(node, node.operationId),
866
835
  root,
@@ -875,13 +844,14 @@ const serverGenerator = (0, _kubb_kit.defineGenerator)({
875
844
  output: pluginZod.options?.output ?? output,
876
845
  group: pluginZod.options?.group ?? void 0
877
846
  });
878
- const requestName = node.requestBody?.content?.[0]?.schema ? zodResolver.response.body(node) : null;
879
- const successStatus = getPrimarySuccessResponse(node)?.statusCode;
847
+ const requestName = _kubb_kit.ast.http.requestBody.getSchema(node) ? zodResolver.response.body(node) : null;
848
+ const successStatus = _kubb_kit.ast.http.responses.findPrimary(node)?.statusCode;
880
849
  const responseName = successStatus ? zodResolver.response.status(node, successStatus) : null;
881
850
  const resolveParams = (params) => params.map((p) => ({
882
851
  name: p.name,
883
852
  schemaName: zodResolver.param.name(node, p)
884
853
  }));
854
+ const resolveOptional = (params) => params.length ? resolveParams(params) : null;
885
855
  return {
886
856
  tool: {
887
857
  name: node.operationId,
@@ -894,9 +864,9 @@ const serverGenerator = (0, _kubb_kit.defineGenerator)({
894
864
  },
895
865
  zod: {
896
866
  pathParams: resolveParams(pathParams),
897
- queryParams: queryParams.length ? resolveParams(queryParams) : null,
898
- headerParams: headerParams.length ? resolveParams(headerParams) : null,
899
- cookieParams: cookieParams.length ? resolveParams(cookieParams) : null,
867
+ queryParams: resolveOptional(queryParams),
868
+ headerParams: resolveOptional(headerParams),
869
+ cookieParams: resolveOptional(cookieParams),
900
870
  requestName,
901
871
  responseName,
902
872
  file: zodFile
@@ -906,7 +876,7 @@ const serverGenerator = (0, _kubb_kit.defineGenerator)({
906
876
  const imports = operationsMapped.flatMap(({ mcp, zod }) => {
907
877
  const zodNames = [
908
878
  ...zod.pathParams.map((p) => p.schemaName),
909
- ...(zod.queryParams ?? []).map((p) => p.schemaName),
879
+ ...typeof zod.queryParams === "string" ? [zod.queryParams] : (zod.queryParams ?? []).map((p) => p.schemaName),
910
880
  ...(zod.headerParams ?? []).map((p) => p.schemaName),
911
881
  ...(zod.cookieParams ?? []).map((p) => p.schemaName),
912
882
  zod.requestName,
@@ -1008,11 +978,11 @@ const serverGenerator = (0, _kubb_kit.defineGenerator)({
1008
978
  });
1009
979
  // kubb-extension.json
1010
980
  var compatibility = {
1011
- "kubb": ">=5.16.0",
981
+ "kubb": ">=5.18.4",
1012
982
  "node": ">=22.22"
1013
983
  };
1014
984
  // package.json
1015
- var version = "5.5.0-canary.20261111T115959";
985
+ var version = "5.5.0";
1016
986
  // src/resolvers/resolverMcp.ts
1017
987
  /**
1018
988
  * Default resolver used by `@kubb/plugin-mcp`. Decides the names and file
@@ -1029,7 +999,7 @@ var version = "5.5.0-canary.20261111T115959";
1029
999
  const resolverMcp = (0, _kubb_kit.createResolver)({
1030
1000
  pluginName: "plugin-mcp",
1031
1001
  name(name) {
1032
- return this.memo(`name:${name}`, () => (0, _kubb_kit.camelCase)(name, { suffix: "handler" }));
1002
+ return this.memo(`name:${name}`, () => _kubb_kit.casing.camel(name, { suffix: "handler" }));
1033
1003
  },
1034
1004
  handler: { name(node) {
1035
1005
  const name = this.name(node.operationId);
@@ -1098,7 +1068,7 @@ const pluginMcp = (0, _kubb_kit.defineExtension)({
1098
1068
  exclude,
1099
1069
  include,
1100
1070
  override,
1101
- group: createGroupConfig(group),
1071
+ group: group ?? null,
1102
1072
  client: resolveContractClient({
1103
1073
  plugin: pluginMcpName,
1104
1074
  client,