@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.js CHANGED
@@ -1,9 +1,41 @@
1
- import { Diagnostics, Resolver, addGenerator, ast, camelCase, createResolver, defineExtension, defineGenerator, setMacros, setResolver, useConfig } from "@kubb/kit";
1
+ import { Diagnostics, Resolver, addGenerator, ast, casing, createResolver, defineExtension, defineGenerator, setMacros, setResolver, text, useConfig } from "@kubb/kit";
2
2
  import path, { posix } from "node:path";
3
3
  import { Const, File, Function, jsxRenderer } from "@kubb/renderer-jsx";
4
4
  import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
5
5
  import { pluginTsName } from "@kubb/plugin-ts";
6
6
  import { pluginZodName } from "@kubb/plugin-zod";
7
+ // ../../internals/utils/src/fs.ts
8
+ function toSlash(p) {
9
+ if (p.startsWith("\\\\?\\")) return p;
10
+ return p.replaceAll("\\", "/");
11
+ }
12
+ /**
13
+ * Returns the relative path from `rootDir` to `filePath`, always using forward slashes
14
+ * and prefixed with `./` when not already traversing upward.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'
19
+ * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'
20
+ * ```
21
+ */
22
+ function getRelativePath(rootDir, filePath) {
23
+ const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath));
24
+ return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
25
+ }
26
+ // ../../internals/utils/src/strings.ts
27
+ /**
28
+ * Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
29
+ * Editors render `\@` as `@` in hovers.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
34
+ * ```
35
+ */
36
+ function jsDocEscape(input) {
37
+ return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
38
+ }
7
39
  // ../../internals/shared/src/operation.ts
8
40
  /**
9
41
  * Builds the `ResolverFileParams` every operation generator passes to
@@ -73,7 +105,7 @@ function resolveOperationFile(options) {
73
105
  * The operation's method and path as plain text, such as `` `GET /pet/{petId}` ``. A path is not a valid `{@link}` target.
74
106
  */
75
107
  function getOperationRequestLine(node) {
76
- return ast.isHttpOperationNode(node) && node.path ? `\`${node.method.toUpperCase()} ${node.path}\`` : null;
108
+ return ast.http.isOperation(node) && node.path ? `\`${node.method.toUpperCase()} ${node.path}\`` : null;
77
109
  }
78
110
  /**
79
111
  * Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several
@@ -97,7 +129,48 @@ function getContentTypeInfo(node) {
97
129
  * whether several are present, so the client can let a caller pick which one to accept.
98
130
  */
99
131
  function getResponseContentTypeInfo(node) {
100
- return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? []);
132
+ return buildContentTypeInfo(ast.http.responses.findPrimary(node)?.content?.map((e) => e.contentType) ?? []);
133
+ }
134
+ /**
135
+ * How an operation streams its primary success response item by item, when that response declares one content type:
136
+ * - `'event'` for `text/event-stream` whose `itemSchema` types the whole event with its own `event` and `data`
137
+ * - `'data'` for `text/event-stream` typed by its payload only
138
+ * - `'line'` for JSON Lines, one parsed JSON value per line
139
+ *
140
+ * Returns `null` for any other response, and for a response that also declares another content type, which stays a normal
141
+ * call with its query hooks.
142
+ */
143
+ function getEventStream(node) {
144
+ const content = ast.http.responses.findPrimary(node)?.content ?? [];
145
+ if (content.length !== 1) return null;
146
+ const entry = content[0];
147
+ const framing = getStreamFraming(entry);
148
+ if (framing === "events") return entry.stream?.shape ?? "data";
149
+ return framing === "lines" ? "line" : null;
150
+ }
151
+ /**
152
+ * How a content entry is framed as a stream: `'events'` for Server-Sent Events, `'lines'` for JSON Lines.
153
+ */
154
+ function getStreamFraming(entry) {
155
+ if (ast.mediaType.getBase(entry) === "text/event-stream") return "events";
156
+ return entry.stream && ast.mediaType.isStream(entry) ? "lines" : void 0;
157
+ }
158
+ /**
159
+ * Whether an operation streams its primary success response, as Server-Sent Events or JSON Lines. The client generator uses
160
+ * this to return a typed stream of items instead of a one-shot `RequestResult`.
161
+ */
162
+ function isEventStream(node) {
163
+ return getEventStream(node) !== null;
164
+ }
165
+ /**
166
+ * Whether a success response offers a stream media type next to other content types. The client returns that variant's
167
+ * body as a `ReadableStream`, so the stream runtime is registered and a hook's data type includes the stream.
168
+ */
169
+ function hasStreamVariant(node) {
170
+ return ast.http.responses.filterSuccess(node).some((response) => {
171
+ const variants = (response.content ?? []).filter((entry) => entry.schema);
172
+ return variants.length > 1 && variants.some((entry) => ast.mediaType.isStream(entry));
173
+ });
101
174
  }
102
175
  /**
103
176
  * Builds the `client?:` option type shared by the generated query hooks (`useQuery`,
@@ -140,11 +213,11 @@ const requestGroupOrder = [
140
213
  * Which of the grouped request options an operation carries.
141
214
  */
142
215
  function getRequestGroups(node) {
143
- const { path, query, header, cookie } = getOperationParameters(node);
216
+ const { path, query, header, cookie } = ast.http.groupParameters(node);
144
217
  return {
145
218
  path: path.length > 0,
146
219
  query: query.length > 0,
147
- body: Boolean(node.requestBody?.content?.[0]?.schema),
220
+ body: Boolean(ast.http.requestBody.getSchema(node)),
148
221
  headers: header.length > 0,
149
222
  cookies: cookie.length > 0
150
223
  };
@@ -156,7 +229,7 @@ function getRequestGroups(node) {
156
229
  */
157
230
  function getRequestGroupOptionality(node) {
158
231
  const groups = getRequestGroups(node);
159
- const { path, query, header } = getOperationParameters(node);
232
+ const { path, query, header } = ast.http.groupParameters(node);
160
233
  const hasRequiredPath = path.some((param) => param.required);
161
234
  const hasRequiredQuery = query.some((param) => param.required);
162
235
  const hasRequiredHeader = header.some((param) => param.required);
@@ -191,55 +264,12 @@ function buildOperationComments(node, options = {}) {
191
264
  getOperationRequestLine(node),
192
265
  node.description && `@description ${node.description}`,
193
266
  node.summary && `@summary ${node.summary}`,
194
- node.deprecated && "@deprecated"
267
+ node.deprecated && "@deprecated",
268
+ node.externalDocs && `@see ${jsDocEscape([node.externalDocs.url, node.externalDocs.description].filter(Boolean).join(" "))}`
195
269
  ].filter((comment) => Boolean(comment));
196
270
  if (!splitLines) return filteredComments;
197
271
  return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
198
272
  }
199
- const operationParameterGroupsByNode = /* @__PURE__ */ new WeakMap();
200
- /**
201
- * An OpenAPI 3.2 `querystring` parameter is the whole query string, so a form-encoded object becomes one query parameter
202
- * per property, typed and serialized like any other.
203
- * Another content type, such as JSON, stays one parameter named after it, and the runtime sends its value as the whole query string.
204
- */
205
- function spreadQuerystring(param) {
206
- const schema = param.schema.type === "ref" ? param.schema.schema : param.schema;
207
- const formEncoded = !param.contentType || param.contentType.split(";")[0].trim().toLowerCase() === "application/x-www-form-urlencoded";
208
- if (schema?.type !== "object" || !formEncoded) return [param];
209
- return schema.properties.map((property) => ast.factory.createParameter({
210
- name: property.name,
211
- in: "query",
212
- schema: property.schema,
213
- required: param.required && property.required
214
- }));
215
- }
216
- /**
217
- * Groups an operation's parameters by location (`path`/`query`/`header`/`cookie`), deduping each
218
- * group by name. Every plugin generator visiting the same `OperationNode` shares one AST instance
219
- * (see `KubbDriver`), so the result is cached per node to avoid re-filtering and re-deduping the
220
- * same parameters once per plugin.
221
- */
222
- function getOperationParameters(node) {
223
- const cached = operationParameterGroupsByNode.get(node);
224
- if (cached) return cached;
225
- const dedupe = (params) => {
226
- const seen = /* @__PURE__ */ new Set();
227
- return params.filter((param) => {
228
- if (seen.has(param.name)) return false;
229
- seen.add(param.name);
230
- return true;
231
- });
232
- };
233
- const group = (location) => dedupe(node.parameters.filter((param) => param.in === location));
234
- const groups = {
235
- path: group("path"),
236
- query: dedupe([...group("query"), ...group("querystring").flatMap(spreadQuerystring)]),
237
- header: group("header"),
238
- cookie: group("cookie")
239
- };
240
- operationParameterGroupsByNode.set(node, groups);
241
- return groups;
242
- }
243
273
  /**
244
274
  * Whether the operation declares more than one request media type with a schema, so a caller must pick one on `contentType`.
245
275
  */
@@ -252,48 +282,15 @@ function hasRequestContentTypeChoice(node) {
252
282
  function castToClientOptions(callArg, clientName, returnType = "full") {
253
283
  return `${callArg} as Parameters<typeof ${clientName}${returnType === "plain" ? "" : "<true>"}>[0]`;
254
284
  }
255
- function getStatusCodeNumber(statusCode) {
256
- const code = Number(statusCode);
257
- return Number.isNaN(code) ? null : code;
258
- }
259
- function isSuccessStatusCode(statusCode) {
260
- const code = getStatusCodeNumber(statusCode);
261
- return code !== null && code >= 200 && code < 300;
262
- }
263
- function getSuccessResponses(responses) {
264
- return responses.filter((response) => isSuccessStatusCode(response.statusCode));
265
- }
266
- function getOperationSuccessResponses(node) {
267
- return getSuccessResponses(node.responses);
268
- }
269
- function getPrimarySuccessResponse(node) {
270
- return getOperationSuccessResponses(node)[0] ?? null;
271
- }
272
- // ../../internals/utils/src/fs.ts
273
- function toSlash(p) {
274
- if (p.startsWith("\\\\?\\")) return p;
275
- return p.replaceAll("\\", "/");
276
- }
277
- /**
278
- * Returns the relative path from `rootDir` to `filePath`, always using forward slashes
279
- * and prefixed with `./` when not already traversing upward.
280
- *
281
- * @example
282
- * ```ts
283
- * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'
284
- * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'
285
- * ```
286
- */
287
- function getRelativePath(rootDir, filePath) {
288
- const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath));
289
- return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
290
- }
291
285
  // ../../internals/shared/src/resolver.ts
292
286
  /**
293
287
  * Builds the allocation key for a declaration an operation owns. `scope` names which declaration
294
288
  * it is, so two of them never share an allocation even when a custom resolver gives both the same
295
289
  * name. Leave `scope` empty for the operation's own declaration.
296
290
  *
291
+ * The key starts from the operation's input `pointer`, which macros keep, so a plugin whose macro
292
+ * rewrites the method or path still resolves another plugin's names for the same operation.
293
+ *
297
294
  * @example
298
295
  * ```ts
299
296
  * resolver.resolveName({ key: operationKey(node, 'response', 'status', 404), name })
@@ -302,41 +299,10 @@ function getRelativePath(rootDir, filePath) {
302
299
  function operationKey(node, ...scope) {
303
300
  return [
304
301
  "operation",
305
- node.method,
306
- node.path,
302
+ ...node.pointer ? [node.pointer] : [node.method, node.path],
307
303
  ...scope.map(String)
308
304
  ];
309
305
  }
310
- // ../../internals/shared/src/group.ts
311
- /**
312
- * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
313
- * shared default naming so every plugin groups output consistently:
314
- *
315
- * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
316
- * - other groups use the camelCased group (`pet store` → `petStore`).
317
- *
318
- * A user-provided `group.name` always wins over the default namer, so callers stay in
319
- * control of their output folders. Returns `null` when grouping is disabled, matching the
320
- * per-plugin convention.
321
- *
322
- * @param group - The user-supplied group option, or `undefined` to disable grouping.
323
- *
324
- * @example
325
- * ```ts
326
- * createGroupConfig(group) // shared across every plugin
327
- * ```
328
- */
329
- function createGroupConfig(group) {
330
- if (!group) return null;
331
- const defaultName = (ctx) => {
332
- if (group.type === "path") return `${ctx.group.split("/")[1]}`;
333
- return camelCase(ctx.group);
334
- };
335
- return {
336
- ...group,
337
- name: group.name ? group.name : defaultName
338
- };
339
- }
340
306
  // src/components/McpHandler.tsx
341
307
  function McpHandler({ name, clientName, node, resolver, returnType = "full" }) {
342
308
  const { signature, names: callArgs } = buildRequestParamsSignature(node, resolver, { isConfigurable: false });
@@ -390,7 +356,7 @@ function Server({ serverName, serverVersion, operations }) {
390
356
  });
391
357
  if (zod.queryParams) entries.push({
392
358
  key: "query",
393
- value: zodObject(zod.queryParams)
359
+ value: typeof zod.queryParams === "string" ? zod.queryParams : zodObject(zod.queryParams)
394
360
  });
395
361
  if (zod.headerParams) entries.push({
396
362
  key: "headers",
@@ -437,8 +403,8 @@ server.registerTool(${JSON.stringify(tool.name)}, {
437
403
  name: "getServer",
438
404
  export: true,
439
405
  children: `const server = new McpServer({
440
- name: '${serverName}',
441
- version: '${serverVersion}',
406
+ name: ${text.quote(serverName)},
407
+ version: ${text.quote(serverVersion)},
442
408
  })
443
409
  ${registrations}
444
410
  return server`
@@ -638,7 +604,8 @@ function resolveClientOperation(options) {
638
604
  operationFile: file.path
639
605
  }),
640
606
  clientPathIsFile: importPath === void 0 || isRelativeImport(importPath),
641
- returnType: operationOptions.returnType ?? "full"
607
+ returnType: operationOptions.returnType ?? "full",
608
+ typedHeaders: importPath === void 0
642
609
  };
643
610
  });
644
611
  }
@@ -666,6 +633,7 @@ function toZodTypeResolver(resolver) {
666
633
  status: (node, statusCode) => type(resolver.response.status(node, statusCode)),
667
634
  response: (node) => type(resolver.response.response(node)),
668
635
  responses: (node) => type(resolver.response.responses(node)),
636
+ headers: (node, statusCode) => type(resolver.response.headers(node, statusCode)),
669
637
  options: (node) => resolver.response.options(node)
670
638
  }
671
639
  };
@@ -724,7 +692,8 @@ const mcpGenerator = defineGenerator({
724
692
  name: "mcp",
725
693
  renderer: jsxRenderer,
726
694
  operation(node, ctx) {
727
- if (!ast.isHttpOperationNode(node)) return null;
695
+ if (!ast.http.isOperation(node)) return null;
696
+ if (isEventStream(node) || hasStreamVariant(node)) return null;
728
697
  const { resolver, driver, root, config } = ctx;
729
698
  const { output, client, group } = ctx.options;
730
699
  const types = resolveOperationTypes(driver, resolver.pluginName);
@@ -833,8 +802,8 @@ const serverGenerator = defineGenerator({
833
802
  command: "npx",
834
803
  args: ["tsx", getRelativePath(path.resolve(config.root), startFile.path)]
835
804
  } } };
836
- const operationsMapped = nodes.filter(ast.isHttpOperationNode).map((node) => {
837
- const { path: pathParams, query: queryParams, header: headerParams, cookie: cookieParams } = getOperationParameters(node);
805
+ const operationsMapped = nodes.filter(ast.http.isOperation).filter((node) => !isEventStream(node) && !hasStreamVariant(node)).map((node) => {
806
+ const { path: pathParams, query: queryParams, header: headerParams, cookie: cookieParams } = ast.http.groupParameters(node);
838
807
  const mcpFile = resolver.file({
839
808
  ...operationFileEntry(node, node.operationId),
840
809
  root,
@@ -849,13 +818,14 @@ const serverGenerator = defineGenerator({
849
818
  output: pluginZod.options?.output ?? output,
850
819
  group: pluginZod.options?.group ?? void 0
851
820
  });
852
- const requestName = node.requestBody?.content?.[0]?.schema ? zodResolver.response.body(node) : null;
853
- const successStatus = getPrimarySuccessResponse(node)?.statusCode;
821
+ const requestName = ast.http.requestBody.getSchema(node) ? zodResolver.response.body(node) : null;
822
+ const successStatus = ast.http.responses.findPrimary(node)?.statusCode;
854
823
  const responseName = successStatus ? zodResolver.response.status(node, successStatus) : null;
855
824
  const resolveParams = (params) => params.map((p) => ({
856
825
  name: p.name,
857
826
  schemaName: zodResolver.param.name(node, p)
858
827
  }));
828
+ const resolveOptional = (params) => params.length ? resolveParams(params) : null;
859
829
  return {
860
830
  tool: {
861
831
  name: node.operationId,
@@ -868,9 +838,9 @@ const serverGenerator = defineGenerator({
868
838
  },
869
839
  zod: {
870
840
  pathParams: resolveParams(pathParams),
871
- queryParams: queryParams.length ? resolveParams(queryParams) : null,
872
- headerParams: headerParams.length ? resolveParams(headerParams) : null,
873
- cookieParams: cookieParams.length ? resolveParams(cookieParams) : null,
841
+ queryParams: resolveOptional(queryParams),
842
+ headerParams: resolveOptional(headerParams),
843
+ cookieParams: resolveOptional(cookieParams),
874
844
  requestName,
875
845
  responseName,
876
846
  file: zodFile
@@ -880,7 +850,7 @@ const serverGenerator = defineGenerator({
880
850
  const imports = operationsMapped.flatMap(({ mcp, zod }) => {
881
851
  const zodNames = [
882
852
  ...zod.pathParams.map((p) => p.schemaName),
883
- ...(zod.queryParams ?? []).map((p) => p.schemaName),
853
+ ...typeof zod.queryParams === "string" ? [zod.queryParams] : (zod.queryParams ?? []).map((p) => p.schemaName),
884
854
  ...(zod.headerParams ?? []).map((p) => p.schemaName),
885
855
  ...(zod.cookieParams ?? []).map((p) => p.schemaName),
886
856
  zod.requestName,
@@ -982,11 +952,11 @@ const serverGenerator = defineGenerator({
982
952
  });
983
953
  // kubb-extension.json
984
954
  var compatibility = {
985
- "kubb": ">=5.16.0",
955
+ "kubb": ">=5.18.4",
986
956
  "node": ">=22.22"
987
957
  };
988
958
  // package.json
989
- var version = "5.5.0-canary.20261111T115959";
959
+ var version = "5.5.0";
990
960
  // src/resolvers/resolverMcp.ts
991
961
  /**
992
962
  * Default resolver used by `@kubb/plugin-mcp`. Decides the names and file
@@ -1003,7 +973,7 @@ var version = "5.5.0-canary.20261111T115959";
1003
973
  const resolverMcp = createResolver({
1004
974
  pluginName: "plugin-mcp",
1005
975
  name(name) {
1006
- return this.memo(`name:${name}`, () => camelCase(name, { suffix: "handler" }));
976
+ return this.memo(`name:${name}`, () => casing.camel(name, { suffix: "handler" }));
1007
977
  },
1008
978
  handler: { name(node) {
1009
979
  const name = this.name(node.operationId);
@@ -1072,7 +1042,7 @@ const pluginMcp = defineExtension({
1072
1042
  exclude,
1073
1043
  include,
1074
1044
  override,
1075
- group: createGroupConfig(group),
1045
+ group: group ?? null,
1076
1046
  client: resolveContractClient({
1077
1047
  plugin: pluginMcpName,
1078
1048
  client,