@kubb/plugin-mcp 5.0.0-beta.10 → 5.0.0-beta.103

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/extension.yaml DELETED
@@ -1,463 +0,0 @@
1
- $schema: https://kubb.dev/schemas/extension.json
2
- kind: plugin
3
- id: plugin-mcp
4
- name: MCP
5
- description: Generate Model Context Protocol (MCP) servers from OpenAPI specifications for AI assistants to call your API.
6
- category: ai
7
- type: official
8
- npmPackage: '@kubb/plugin-mcp'
9
- docsPath: /plugins/plugin-mcp
10
- repo: https://github.com/kubb-labs/plugins
11
- maintainers:
12
- - name: Stijn Van Hulle
13
- github: stijnvanhulle
14
- compatibility:
15
- kubb: '>=5.0.0'
16
- node: '>=22'
17
- tags:
18
- - mcp
19
- - model-context-protocol
20
- - ai
21
- - claude
22
- - llm
23
- - codegen
24
- - openapi
25
- dependencies:
26
- - plugin-ts
27
- - plugin-client
28
- - plugin-zod
29
- resources:
30
- documentation: https://kubb.dev/plugins/plugin-mcp
31
- repository: https://github.com/kubb-labs/plugins
32
- issues: https://github.com/kubb-labs/plugins/issues
33
- changelog: https://github.com/kubb-labs/plugins/blob/main/packages/plugin-mcp/CHANGELOG.md
34
- codesandbox: https://codesandbox.io/p/github/kubb-labs/plugins/main/examples/mcp
35
- featured: false
36
- icon:
37
- light: https://kubb.dev/feature/mcp-light.svg
38
- dark: https://kubb.dev/feature/mcp-dark.svg
39
- intro: |
40
- # @kubb/plugin-mcp
41
-
42
- Generate [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers from your OpenAPI schema. AI assistants like Claude can now call your API through conversational interfaces.
43
-
44
- ```mermaid
45
- graph TD
46
- A[Kubb<br/>Generates code from OpenAPI] --> B[MCP Server<br/>Handles tool calls]
47
- B --> C[Claude<br/>Conversational AI]
48
- C -->|Sends tool request| B
49
- B -->|Uses generated code| A
50
- ```
51
- notes:
52
- - type: tip
53
- body: |
54
- See [Setup Claude with Kubb](https://modelcontextprotocol.io/docs/tools/claude-desktop) for configuration instructions.
55
- options:
56
- - name: output
57
- type: Output
58
- required: false
59
- default: "{ path: 'mcp', barrel: { type: 'named' } }"
60
- description: Specify the export location for the files and define the behavior of the output.
61
- properties:
62
- - name: path
63
- type: string
64
- required: true
65
- description: Output directory or file for the generated code, relative to the global `output.path`.
66
- tip: |
67
- if `output.path` is a file, `group` cannot be used.
68
- default: "'mcp'"
69
- - name: barrel
70
- type: "{ type: 'named' | 'all', nested?: boolean } | false"
71
- required: false
72
- default: "{ type: 'named' }"
73
- description: "Configure barrel file export strategy. Use `type` to control named vs. wildcard exports; set `nested: true` to generate hierarchical barrels in subdirectories."
74
- examples:
75
- - name: all
76
- files:
77
- - lang: typescript
78
- code: |
79
- export * from './gen/petService.ts'
80
- twoslash: false
81
- - name: named
82
- files:
83
- - lang: typescript
84
- code: |
85
- export { PetService } from './gen/petService.ts'
86
- twoslash: false
87
- - name: 'false'
88
- files:
89
- - lang: typescript
90
- code: ''
91
- twoslash: false
92
- - name: banner
93
- type: 'string | ((node: RootNode) => string)'
94
- required: false
95
- description: Add a banner comment at the top of every generated file. Accepts a static string or a function that receives the `RootNode` and returns a string.
96
- - name: footer
97
- type: 'string | ((node: RootNode) => string)'
98
- required: false
99
- description: Add a footer comment at the end of every generated file. Accepts a static string or a function that receives the `RootNode` and returns a string.
100
- - name: override
101
- type: boolean
102
- required: false
103
- default: 'false'
104
- description: Whether Kubb overrides existing external files that can be generated if they already exist.
105
- - name: resolver
106
- type: Partial<ResolverMcp> & ThisType<ResolverMcp>
107
- required: false
108
- description: |
109
- A single resolver that overrides the naming and path-resolution conventions. Each method you provide replaces the corresponding built-in one. When a method returns `null` or `undefined`, the resolver's result is used as the fallback, so you only need to supply the methods you want to change.
110
-
111
- `this` inside each method is bound to the **full** resolver, so you can call other resolver methods (e.g. `this.default(name, 'function')`) without losing context.
112
- body: |
113
- Each plugin ships a built-in resolver:
114
-
115
- | Plugin | Default resolver |
116
- | --- | --- |
117
- | `@kubb/plugin-ts` | `resolverTs` |
118
- | `@kubb/plugin-zod` | `resolverZod` |
119
- | `@kubb/plugin-cypress` | `resolverCypress` |
120
- | `@kubb/plugin-mcp` | `resolverMcp` |
121
- codeBlock:
122
- lang: typescript
123
- title: Custom resolver (plugin-mcp example)
124
- code: |
125
- import { pluginMcp } from '@kubb/plugin-mcp'
126
-
127
- pluginMcp({
128
- resolver: {
129
- resolveName(name) {
130
- return `Mcp${this.default(name, 'function')}`
131
- },
132
- },
133
- })
134
- tip: |
135
- Use `resolver` for fine-grained control over naming conventions.
136
- - name: group
137
- type: Group
138
- required: false
139
- description: |
140
- Grouping combines files in a folder based on a specific `type`.
141
- examples:
142
- - name: kubb.config.ts
143
- files:
144
- - lang: typescript
145
- code: |
146
- group: {
147
- type: 'tag',
148
- name({ group }) {
149
- return `${group}Controller`
150
- }
151
- }
152
- twoslash: false
153
- body: |
154
- With the configuration above, the generator emits:
155
-
156
- ```text
157
- .
158
- ├── src/
159
- │ └── petController/
160
- │ │ ├── addPet.ts
161
- │ │ └── getPet.ts
162
- │ └── storeController/
163
- │ ├── createStore.ts
164
- │ └── getStoreById.ts
165
- ├── petStore.yaml
166
- ├── kubb.config.ts
167
- └── package.json
168
- ```
169
- properties:
170
- - name: type
171
- type: "'tag'"
172
- required: true
173
- description: Specify the property to group files by. Required when `group` is defined.
174
- note: |
175
- `Required: true*` means this is required only when the `group` option is used. The `group` option itself is optional.
176
- body: |
177
- - `'tag'`: Uses the first tag from `operation.getTags().at(0)?.name`
178
- - name: name
179
- type: '(context: GroupContext) => string'
180
- required: false
181
- default: (ctx) => `${ctx.group}Requests`
182
- description: Return the name of a group based on the group name. This is used for file and identifier generation.
183
- - name: paramsCasing
184
- type: "'camelcase'"
185
- required: false
186
- description: Transform parameter names to camelCase in generated MCP handlers.
187
- important: |
188
- When using `paramsCasing`, ensure that `@kubb/plugin-ts` also has the same `paramsCasing` setting. This option automatically maps transformed parameter names back to their original API names in HTTP requests.
189
- body: |
190
- - `'camelcase'` transforms parameter names to camelCase.
191
- examples:
192
- - name: With paramsCasing camelcase
193
- files:
194
- - lang: typescript
195
- code: |
196
- // Handler uses camelCase parameters
197
- export async function findPetsByStatusHandler({
198
- stepId // ✓ camelCase
199
- }: {
200
- stepId: FindPetsByStatusPathParams['stepId']
201
- }): Promise<Promise<CallToolResult>> {
202
- // Automatically maps back to original name
203
- const step_id = stepId
204
-
205
- const res = await fetch({
206
- method: 'GET',
207
- url: `/pet/findByStatus/${step_id}`, // Uses original API name
208
- ...
209
- })
210
- ...
211
- }
212
- twoslash: false
213
- - name: Without paramsCasing
214
- files:
215
- - lang: typescript
216
- code: |
217
- // Handler uses original API naming
218
- export async function findPetsByStatusHandler({
219
- step_id // Original naming
220
- }: {
221
- step_id: FindPetsByStatusPathParams['step_id']
222
- }): Promise<Promise<CallToolResult>> {
223
- const res = await fetch({
224
- method: 'GET',
225
- url: `/pet/findByStatus/${step_id}`,
226
- ...
227
- })
228
- ...
229
- }
230
- twoslash: false
231
- - name: client
232
- type: ClientImportPath & { clientType?, dataReturnType?, baseURL?, bundle?, paramsCasing? }
233
- required: false
234
- description: Client configuration for HTTP request generation, including client type, data return type, base URL, and bundling options.
235
- properties:
236
- - name: importPath
237
- type: string
238
- required: false
239
- description: Path to the client used for API calls. Supports both relative and absolute paths.
240
- details:
241
- - title: When to use `importPath`
242
- body: |
243
- Use `importPath` when you want to:
244
-
245
- - **Customize the HTTP client**: Provide your own client implementation with custom configurations (e.g., baseURL, headers, interceptors)
246
- - **Add authentication**: Include authentication tokens or other security mechanisms in your client
247
- - **Override default behavior**: Replace the default Kubb client with your own implementation
248
- - title: Default behavior
249
- body: |
250
- When `importPath` is not specified:
251
-
252
- - If `bundle: false` (default): Uses `@kubb/plugin-client/clients/${client}` where client is either `axios` or `fetch`.
253
- - If `bundle: true`: Bundles the client into `.kubb/fetch.ts`.
254
- - title: Import structure
255
- body: 'Generated code imports the client as a default import and the runtime types as named type imports:'
256
- codeBlock:
257
- lang: typescript
258
- code: |-
259
- /**
260
- * Generated by Kubb (https://kubb.dev/).
261
- * Do not edit manually.
262
- */
263
- import client from '${client.importPath}'
264
- import type { RequestConfig, ResponseErrorConfig } from '${client.importPath}'
265
- // ... rest of generated file
266
- important: |
267
- When using `importPath` with query plugins such as `@kubb/plugin-react-query` or `@kubb/plugin-vue-query`, the generated hooks also import a `Client` type alongside `RequestConfig` and `ResponseErrorConfig` from the custom module. Your custom client module **must** export all three types — if any is missing, TypeScript will report an unresolvable import error.
268
- codeBlock:
269
- lang: typescript
270
- title: client.ts
271
- code: |
272
- export type RequestConfig<TData = unknown> = {
273
- url?: string
274
- method: 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE'
275
- params?: object
276
- data?: TData | FormData
277
- responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'
278
- signal?: AbortSignal
279
- headers?: HeadersInit
280
- }
281
-
282
- export type ResponseConfig<TData = unknown> = {
283
- data: TData
284
- status: number
285
- statusText: string
286
- }
287
-
288
- export type ResponseErrorConfig<TError = unknown> = TError
289
-
290
- // The Client type alias is required when using query plugins
291
- export type Client = <TData, _TError = unknown, TVariables = unknown>(
292
- config: RequestConfig<TVariables>
293
- ) => Promise<ResponseConfig<TData>>
294
-
295
- export const client: Client = async (config) => { /* ... */ }
296
- export default client
297
- examples:
298
- - name: kubb.config.ts
299
- files:
300
- - lang: typescript
301
- code: |
302
- import { defineConfig } from 'kubb'
303
- import { pluginClient } from '@kubb/plugin-client'
304
-
305
- export default defineConfig({
306
- // ...
307
- plugins: [
308
- pluginClient({
309
- importPath: './src/client.ts', // Path to your custom client
310
- }),
311
- ],
312
- })
313
- twoslash: false
314
- tip: |
315
- Learn more about defining a custom client [here](https://kubb.dev/plugins/plugin-client#importpath).
316
- - name: dataReturnType
317
- type: "'data' | 'full'"
318
- required: false
319
- default: "'data'"
320
- description: |
321
- Return type used when calling the client.
322
-
323
- - `'data'` returns `ResponseConfig['data']`.
324
- - `'full'` returns the full `ResponseConfig`.
325
- examples:
326
- - name: data
327
- files:
328
- - lang: typescript
329
- code: |
330
- export async function getPetById<TData>(
331
- petId: GetPetByIdPathParams,
332
- ): Promise<ResponseConfig<TData>['data']> {
333
- ...
334
- }
335
- twoslash: false
336
- - name: full
337
- files:
338
- - lang: typescript
339
- code: |
340
- export async function getPetById<TData>(
341
- petId: GetPetByIdPathParams,
342
- ): Promise<ResponseConfig<TData>> {
343
- ...
344
- }
345
- twoslash: false
346
- - name: baseURL
347
- type: string
348
- required: false
349
- description: Sets a custom base URL for all generated calls. When not set, the base URL is automatically taken from the OAS spec via the adapter (e.g. the `servers[0].url` field).
350
- - name: include
351
- type: Array<Include>
352
- required: false
353
- description: Array containing include parameters to include tags, operations, methods, paths, or content types.
354
- codeBlock:
355
- lang: typescript
356
- title: Include
357
- code: |
358
- export type Include = {
359
- type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
360
- pattern: string | RegExp
361
- }
362
- - name: exclude
363
- type: Array<Exclude>
364
- required: false
365
- description: Array containing exclude parameters to exclude or skip tags, operations, methods, paths, or content types.
366
- codeBlock:
367
- lang: typescript
368
- title: Exclude
369
- code: |
370
- export type Exclude = {
371
- type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
372
- pattern: string | RegExp
373
- }
374
- - name: override
375
- type: Array<Override>
376
- required: false
377
- description: Array containing override parameters to override `options` based on tags, operations, methods, paths, or content types.
378
- codeBlock:
379
- lang: typescript
380
- title: Override
381
- code: |
382
- export type Override = {
383
- type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
384
- pattern: string | RegExp
385
- options: PluginOptions
386
- }
387
- - name: generators
388
- type: Array<Generator<PluginMcp>>
389
- required: false
390
- experimental: true
391
- description: |
392
- Define additional generators next to the built-in generators.
393
-
394
- See [Generators](https://kubb.dev/docs/5.x/guides/creating-plugins) for more information on how to use generators.
395
- - name: transformer
396
- type: Visitor
397
- required: false
398
- description: |
399
- A single AST visitor applied to every node before code is printed. Each method you provide replaces the corresponding built-in one. When a method returns `null` or `undefined`, the preset transformer's result is used as the fallback — so you only need to supply the methods you want to change.
400
-
401
- Visitor methods receive the node and a context object. Return a modified node to replace it, or return `undefined`/`void` to leave it unchanged.
402
- examples:
403
- - name: Strip descriptions before printing
404
- files:
405
- - lang: typescript
406
- code: |
407
- import { pluginTs } from '@kubb/plugin-ts'
408
-
409
- pluginTs({
410
- transformer: {
411
- schema(node) {
412
- return { ...node, description: undefined }
413
- },
414
- },
415
- })
416
- twoslash: false
417
- - name: Prefix every operationId
418
- files:
419
- - lang: typescript
420
- code: |
421
- import { pluginTs } from '@kubb/plugin-ts'
422
-
423
- pluginTs({
424
- transformer: {
425
- operation(node) {
426
- return { ...node, operationId: `api_${node.operationId}` }
427
- },
428
- },
429
- })
430
- twoslash: false
431
- tip: |
432
- Use `transformer` to rewrite node properties before printing. For output naming customization, use `resolver` instead.
433
- examples:
434
- - name: kubb.config.ts
435
- files:
436
- - lang: typescript
437
- code: |
438
- import { defineConfig } from 'kubb'
439
- import { pluginTs } from '@kubb/plugin-ts'
440
- import { pluginClient } from '@kubb/plugin-client'
441
- import { pluginZod } from '@kubb/plugin-zod'
442
- import { pluginMcp } from '@kubb/plugin-mcp'
443
-
444
- export default defineConfig({
445
- input: { path: './petStore.yaml' },
446
- output: { path: './src/gen' },
447
- plugins: [
448
- pluginTs(),
449
- pluginClient(),
450
- pluginZod(),
451
- pluginMcp({
452
- output: { path: 'mcp', barrel: { type: 'named' } },
453
- client: {
454
- baseURL: 'https://petstore.swagger.io/v2',
455
- },
456
- group: {
457
- type: 'tag',
458
- name: ({ group }) => `${group}Handlers`,
459
- },
460
- }),
461
- ],
462
- })
463
- twoslash: false
@@ -1,167 +0,0 @@
1
- import { buildOperationComments, buildTransformedParamsMapping, getOperationParameters } from '@internals/shared'
2
- import { camelCase, isValidVarName, URLPath } from '@internals/utils'
3
- import { ast } from '@kubb/core'
4
- import type { ResolverTs } from '@kubb/plugin-ts'
5
- import { functionPrinter } from '@kubb/plugin-ts'
6
- import { File, Function } from '@kubb/renderer-jsx'
7
- import type { KubbReactNode } from '@kubb/renderer-jsx/types'
8
- import type { PluginMcp } from '../types.ts'
9
-
10
- type Props = {
11
- /**
12
- * Name of the handler function.
13
- */
14
- name: string
15
- /**
16
- * AST operation node.
17
- */
18
- node: ast.OperationNode
19
- /**
20
- * TypeScript resolver for resolving param/data/response type names.
21
- */
22
- resolver: ResolverTs
23
- /**
24
- * Base URL prepended to every generated request URL.
25
- */
26
- baseURL: string | undefined
27
- /**
28
- * Return type when calling fetch.
29
- * - 'data' returns response data only.
30
- * - 'full' returns the full response object.
31
- * @default 'data'
32
- */
33
- dataReturnType: PluginMcp['resolvedOptions']['client']['dataReturnType']
34
- /**
35
- * How to style your params.
36
- */
37
- paramsCasing?: PluginMcp['resolvedOptions']['paramsCasing']
38
- }
39
-
40
- /**
41
- * Generate a remapping statement: `const mappedX = x ? { "orig": x.camel, ... } : undefined`
42
- */
43
- function buildRemappingCode(mapping: Record<string, string>, varName: string, sourceName: string): string {
44
- const pairs = Object.entries(mapping)
45
- .map(([orig, camel]) => `"${orig}": ${sourceName}.${camel}`)
46
- .join(', ')
47
- return `const ${varName} = ${sourceName} ? { ${pairs} } : undefined`
48
- }
49
-
50
- const declarationPrinter = functionPrinter({ mode: 'declaration' })
51
-
52
- export function McpHandler({ name, node, resolver, baseURL, dataReturnType, paramsCasing }: Props): KubbReactNode {
53
- const urlPath = new URLPath(node.path)
54
- const contentType = node.requestBody?.content?.[0]?.contentType
55
- const isFormData = contentType === 'multipart/form-data'
56
-
57
- const { query: queryParams, header: headerParams } = getOperationParameters(node, { paramsCasing })
58
- const { path: originalPathParams, query: originalQueryParams, header: originalHeaderParams } = getOperationParameters(node)
59
-
60
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : undefined
61
- const responseName = resolver.resolveResponseName(node)
62
-
63
- const errorResponses = node.responses.filter((r) => Number(r.statusCode) >= 400).map((r) => resolver.resolveResponseStatusName(node, r.statusCode))
64
- const errorType = errorResponses.length > 0 ? errorResponses.join(' | ') : 'Error'
65
-
66
- const TError = `ResponseErrorConfig<${errorType}>`
67
- const generics = [responseName, TError, requestName || 'unknown'].filter(Boolean)
68
-
69
- const paramsNode = ast.createOperationParams(node, {
70
- paramsType: 'object',
71
- pathParamsType: 'inline',
72
- resolver,
73
- paramsCasing,
74
- })
75
- const baseParamsSignature = declarationPrinter.print(paramsNode) ?? ''
76
- const paramsSignature = baseParamsSignature
77
- ? `${baseParamsSignature}, request: RequestHandlerExtra<ServerRequest, ServerNotification>`
78
- : 'request: RequestHandlerExtra<ServerRequest, ServerNotification>'
79
-
80
- const pathParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalPathParams, camelCase) : undefined
81
- const queryParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalQueryParams, camelCase) : undefined
82
- const headerParamsMapping = paramsCasing ? buildTransformedParamsMapping(originalHeaderParams, camelCase) : undefined
83
-
84
- const contentTypeHeader =
85
- contentType && contentType !== 'application/json' && contentType !== 'multipart/form-data' ? `'Content-Type': '${contentType}'` : undefined
86
- const headers = [headerParams.length ? (headerParamsMapping ? '...mappedHeaders' : '...headers') : undefined, contentTypeHeader].filter(Boolean)
87
-
88
- const fetchConfig: string[] = []
89
- fetchConfig.push(`method: ${JSON.stringify(node.method.toUpperCase())}`)
90
- fetchConfig.push(`url: ${urlPath.template}`)
91
- if (baseURL) fetchConfig.push(`baseURL: \`${baseURL}\``)
92
- if (queryParams.length) fetchConfig.push(queryParamsMapping ? 'params: mappedParams' : 'params')
93
- if (requestName) fetchConfig.push(`data: ${isFormData ? 'formData as FormData' : 'requestData'}`)
94
- if (headers.length) fetchConfig.push(`headers: { ${headers.join(', ')} }`)
95
-
96
- const callToolResult =
97
- dataReturnType === 'data'
98
- ? `return {
99
- content: [
100
- {
101
- type: 'text',
102
- text: JSON.stringify(res.data)
103
- }
104
- ],
105
- structuredContent: { data: res.data }
106
- }`
107
- : `return {
108
- content: [
109
- {
110
- type: 'text',
111
- text: JSON.stringify(res)
112
- }
113
- ],
114
- structuredContent: { data: res.data }
115
- }`
116
-
117
- return (
118
- <File.Source name={name} isExportable isIndexable>
119
- <Function
120
- name={name}
121
- async
122
- export
123
- params={paramsSignature}
124
- JSDoc={{
125
- comments: buildOperationComments(node),
126
- }}
127
- returnType={'Promise<CallToolResult>'}
128
- >
129
- {''}
130
- <br />
131
- <br />
132
- {pathParamsMapping &&
133
- Object.entries(pathParamsMapping)
134
- .filter(([originalName, camelCaseName]) => originalName !== camelCaseName && isValidVarName(originalName))
135
- .map(([originalName, camelCaseName]) => `const ${originalName} = ${camelCaseName}`)
136
- .join('\n')}
137
- {pathParamsMapping && (
138
- <>
139
- <br />
140
- <br />
141
- </>
142
- )}
143
- {queryParamsMapping && queryParams.length > 0 && (
144
- <>
145
- {buildRemappingCode(queryParamsMapping, 'mappedParams', 'params')}
146
- <br />
147
- <br />
148
- </>
149
- )}
150
- {headerParamsMapping && headerParams.length > 0 && (
151
- <>
152
- {buildRemappingCode(headerParamsMapping, 'mappedHeaders', 'headers')}
153
- <br />
154
- <br />
155
- </>
156
- )}
157
- {requestName && 'const requestData = data'}
158
- <br />
159
- {isFormData && requestName && 'const formData = buildFormData(requestData)'}
160
- <br />
161
- {`const res = await fetch<${generics.join(', ')}>({ ${fetchConfig.join(', ')} }, request)`}
162
- <br />
163
- {callToolResult}
164
- </Function>
165
- </File.Source>
166
- )
167
- }