@kubb/plugin-mcp 5.5.0-canary.20261111T122007 → 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,42 +282,6 @@ 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
@@ -309,36 +303,6 @@ function operationKey(node, ...scope) {
309
303
  ...scope.map(String)
310
304
  ];
311
305
  }
312
- // ../../internals/shared/src/group.ts
313
- /**
314
- * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
315
- * shared default naming so every plugin groups output consistently:
316
- *
317
- * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
318
- * - other groups use the camelCased group (`pet store` → `petStore`).
319
- *
320
- * A user-provided `group.name` always wins over the default namer, so callers stay in
321
- * control of their output folders. Returns `null` when grouping is disabled, matching the
322
- * per-plugin convention.
323
- *
324
- * @param group - The user-supplied group option, or `undefined` to disable grouping.
325
- *
326
- * @example
327
- * ```ts
328
- * createGroupConfig(group) // shared across every plugin
329
- * ```
330
- */
331
- function createGroupConfig(group) {
332
- if (!group) return null;
333
- const defaultName = (ctx) => {
334
- if (group.type === "path") return `${ctx.group.split("/")[1]}`;
335
- return camelCase(ctx.group);
336
- };
337
- return {
338
- ...group,
339
- name: group.name ? group.name : defaultName
340
- };
341
- }
342
306
  // src/components/McpHandler.tsx
343
307
  function McpHandler({ name, clientName, node, resolver, returnType = "full" }) {
344
308
  const { signature, names: callArgs } = buildRequestParamsSignature(node, resolver, { isConfigurable: false });
@@ -392,7 +356,7 @@ function Server({ serverName, serverVersion, operations }) {
392
356
  });
393
357
  if (zod.queryParams) entries.push({
394
358
  key: "query",
395
- value: zodObject(zod.queryParams)
359
+ value: typeof zod.queryParams === "string" ? zod.queryParams : zodObject(zod.queryParams)
396
360
  });
397
361
  if (zod.headerParams) entries.push({
398
362
  key: "headers",
@@ -439,8 +403,8 @@ server.registerTool(${JSON.stringify(tool.name)}, {
439
403
  name: "getServer",
440
404
  export: true,
441
405
  children: `const server = new McpServer({
442
- name: '${serverName}',
443
- version: '${serverVersion}',
406
+ name: ${text.quote(serverName)},
407
+ version: ${text.quote(serverVersion)},
444
408
  })
445
409
  ${registrations}
446
410
  return server`
@@ -640,7 +604,8 @@ function resolveClientOperation(options) {
640
604
  operationFile: file.path
641
605
  }),
642
606
  clientPathIsFile: importPath === void 0 || isRelativeImport(importPath),
643
- returnType: operationOptions.returnType ?? "full"
607
+ returnType: operationOptions.returnType ?? "full",
608
+ typedHeaders: importPath === void 0
644
609
  };
645
610
  });
646
611
  }
@@ -668,6 +633,7 @@ function toZodTypeResolver(resolver) {
668
633
  status: (node, statusCode) => type(resolver.response.status(node, statusCode)),
669
634
  response: (node) => type(resolver.response.response(node)),
670
635
  responses: (node) => type(resolver.response.responses(node)),
636
+ headers: (node, statusCode) => type(resolver.response.headers(node, statusCode)),
671
637
  options: (node) => resolver.response.options(node)
672
638
  }
673
639
  };
@@ -726,7 +692,8 @@ const mcpGenerator = defineGenerator({
726
692
  name: "mcp",
727
693
  renderer: jsxRenderer,
728
694
  operation(node, ctx) {
729
- if (!ast.isHttpOperationNode(node)) return null;
695
+ if (!ast.http.isOperation(node)) return null;
696
+ if (isEventStream(node) || hasStreamVariant(node)) return null;
730
697
  const { resolver, driver, root, config } = ctx;
731
698
  const { output, client, group } = ctx.options;
732
699
  const types = resolveOperationTypes(driver, resolver.pluginName);
@@ -835,8 +802,8 @@ const serverGenerator = defineGenerator({
835
802
  command: "npx",
836
803
  args: ["tsx", getRelativePath(path.resolve(config.root), startFile.path)]
837
804
  } } };
838
- const operationsMapped = nodes.filter(ast.isHttpOperationNode).map((node) => {
839
- 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);
840
807
  const mcpFile = resolver.file({
841
808
  ...operationFileEntry(node, node.operationId),
842
809
  root,
@@ -851,13 +818,14 @@ const serverGenerator = defineGenerator({
851
818
  output: pluginZod.options?.output ?? output,
852
819
  group: pluginZod.options?.group ?? void 0
853
820
  });
854
- const requestName = node.requestBody?.content?.[0]?.schema ? zodResolver.response.body(node) : null;
855
- 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;
856
823
  const responseName = successStatus ? zodResolver.response.status(node, successStatus) : null;
857
824
  const resolveParams = (params) => params.map((p) => ({
858
825
  name: p.name,
859
826
  schemaName: zodResolver.param.name(node, p)
860
827
  }));
828
+ const resolveOptional = (params) => params.length ? resolveParams(params) : null;
861
829
  return {
862
830
  tool: {
863
831
  name: node.operationId,
@@ -870,9 +838,9 @@ const serverGenerator = defineGenerator({
870
838
  },
871
839
  zod: {
872
840
  pathParams: resolveParams(pathParams),
873
- queryParams: queryParams.length ? resolveParams(queryParams) : null,
874
- headerParams: headerParams.length ? resolveParams(headerParams) : null,
875
- cookieParams: cookieParams.length ? resolveParams(cookieParams) : null,
841
+ queryParams: resolveOptional(queryParams),
842
+ headerParams: resolveOptional(headerParams),
843
+ cookieParams: resolveOptional(cookieParams),
876
844
  requestName,
877
845
  responseName,
878
846
  file: zodFile
@@ -882,7 +850,7 @@ const serverGenerator = defineGenerator({
882
850
  const imports = operationsMapped.flatMap(({ mcp, zod }) => {
883
851
  const zodNames = [
884
852
  ...zod.pathParams.map((p) => p.schemaName),
885
- ...(zod.queryParams ?? []).map((p) => p.schemaName),
853
+ ...typeof zod.queryParams === "string" ? [zod.queryParams] : (zod.queryParams ?? []).map((p) => p.schemaName),
886
854
  ...(zod.headerParams ?? []).map((p) => p.schemaName),
887
855
  ...(zod.cookieParams ?? []).map((p) => p.schemaName),
888
856
  zod.requestName,
@@ -984,11 +952,11 @@ const serverGenerator = defineGenerator({
984
952
  });
985
953
  // kubb-extension.json
986
954
  var compatibility = {
987
- "kubb": ">=5.16.0",
955
+ "kubb": ">=5.18.4",
988
956
  "node": ">=22.22"
989
957
  };
990
958
  // package.json
991
- var version = "5.5.0-canary.20261111T122007";
959
+ var version = "5.5.0";
992
960
  // src/resolvers/resolverMcp.ts
993
961
  /**
994
962
  * Default resolver used by `@kubb/plugin-mcp`. Decides the names and file
@@ -1005,7 +973,7 @@ var version = "5.5.0-canary.20261111T122007";
1005
973
  const resolverMcp = createResolver({
1006
974
  pluginName: "plugin-mcp",
1007
975
  name(name) {
1008
- return this.memo(`name:${name}`, () => camelCase(name, { suffix: "handler" }));
976
+ return this.memo(`name:${name}`, () => casing.camel(name, { suffix: "handler" }));
1009
977
  },
1010
978
  handler: { name(node) {
1011
979
  const name = this.name(node.operationId);
@@ -1074,7 +1042,7 @@ const pluginMcp = defineExtension({
1074
1042
  exclude,
1075
1043
  include,
1076
1044
  override,
1077
- group: createGroupConfig(group),
1045
+ group: group ?? null,
1078
1046
  client: resolveContractClient({
1079
1047
  plugin: pluginMcpName,
1080
1048
  client,