mcp-from-openapi 1.0.0 → 2.1.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/CHANGELOG.md +23 -0
- package/package.json +8 -5
- package/src/errors.js +2 -0
- package/src/errors.js.map +1 -1
- package/src/generator.js +27 -15
- package/src/generator.js.map +1 -1
- package/src/index.d.ts +3 -3
- package/src/index.js +2 -2
- package/src/index.js.map +1 -1
- package/src/parameter-resolver.d.ts +5 -2
- package/src/parameter-resolver.js +6 -8
- package/src/parameter-resolver.js.map +1 -1
- package/src/response-builder.d.ts +5 -2
- package/src/response-builder.js +3 -1
- package/src/response-builder.js.map +1 -1
- package/src/schema-builder.d.ts +27 -24
- package/src/schema-builder.js.map +1 -1
- package/src/types.d.ts +67 -5
- package/src/types.js +10 -10
- package/src/types.js.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
## [2.1.0] - 2025-12-19
|
|
2
|
+
|
|
3
|
+
### Added
|
|
4
|
+
|
|
5
|
+
- Introduced logger support within the OpenAPI adapter to improve observability.
|
|
6
|
+
- Expanded security handling with automatic auth type routing and enhanced documentation.
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- Refined security resolver examples and guidance for broader authentication scheme coverage.
|
|
11
|
+
|
|
12
|
+
## [2.0.0] - 2025-12-11
|
|
13
|
+
|
|
14
|
+
### Breaking
|
|
15
|
+
|
|
16
|
+
- Migrated to Zod v4 (now a peer dependency) and aligned JSON schema types with Zod’s v4 JSONSchema
|
|
17
|
+
- Renamed utility export `toJSONSchema7` to `toJsonSchema`, affecting consumers of the types/helpers
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- Updated SWC/Jest config to inline ES2022 settings and modernized tooling versions
|
|
22
|
+
- Adjusted exports formatting and minor parameter resolver refactors for consistency
|
|
23
|
+
|
|
1
24
|
# Changelog
|
|
2
25
|
|
|
3
26
|
## [1.0.0] - 2025-11-21
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-from-openapi",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Production-ready library for converting OpenAPI specifications into MCP tool definitions",
|
|
5
5
|
"author": "AgentFront <info@agentfront.dev>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
],
|
|
21
21
|
"repository": {
|
|
22
22
|
"type": "git",
|
|
23
|
-
"url": "git+https://github.com/agentfront/frontmcp.git"
|
|
23
|
+
"url": "git+https://github.com/agentfront/frontmcp.git",
|
|
24
|
+
"directory": "libs/mcp-from-openapi"
|
|
24
25
|
},
|
|
25
26
|
"bugs": {
|
|
26
27
|
"url": "https://github.com/agentfront/frontmcp/issues"
|
|
@@ -41,14 +42,16 @@
|
|
|
41
42
|
},
|
|
42
43
|
"dependencies": {
|
|
43
44
|
"@apidevtools/json-schema-ref-parser": "^11.5.4",
|
|
44
|
-
"@types/json-schema": "^7.0.15",
|
|
45
45
|
"openapi-types": "^12.1.3",
|
|
46
46
|
"yaml": "^2.8.1"
|
|
47
47
|
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"zod": "^4.0.0"
|
|
50
|
+
},
|
|
48
51
|
"devDependencies": {
|
|
49
|
-
"@types/node": "^
|
|
52
|
+
"@types/node": "^24.0.0",
|
|
50
53
|
"typescript": "^5.0.0",
|
|
51
|
-
"zod": "^
|
|
54
|
+
"zod": "^4.0.0"
|
|
52
55
|
},
|
|
53
56
|
"type": "commonjs"
|
|
54
57
|
}
|
package/src/errors.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.SchemaError = exports.GenerationError = exports.ValidationError = export
|
|
|
5
5
|
* Base error class for all library errors
|
|
6
6
|
*/
|
|
7
7
|
class OpenAPIToolError extends Error {
|
|
8
|
+
context;
|
|
8
9
|
constructor(message, context) {
|
|
9
10
|
super(message);
|
|
10
11
|
this.name = this.constructor.name;
|
|
@@ -38,6 +39,7 @@ exports.ParseError = ParseError;
|
|
|
38
39
|
* Error thrown when validating an OpenAPI specification fails
|
|
39
40
|
*/
|
|
40
41
|
class ValidationError extends OpenAPIToolError {
|
|
42
|
+
errors;
|
|
41
43
|
constructor(message, context) {
|
|
42
44
|
super(message, context);
|
|
43
45
|
this.errors = context?.['errors'];
|
package/src/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,gBAAiB,SAAQ,KAAK;
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,gBAAiB,SAAQ,KAAK;IACzB,OAAO,CAAuB;IAE9C,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAClC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QAEvB,6EAA6E;QAC7E,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC5B,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF;AAbD,4CAaC;AAED;;GAEG;AACH,MAAa,SAAU,SAAQ,gBAAgB;IAC7C,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAJD,8BAIC;AAED;;GAEG;AACH,MAAa,UAAW,SAAQ,gBAAgB;IAC9C,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAJD,gCAIC;AAED;;GAEG;AACH,MAAa,eAAgB,SAAQ,gBAAgB;IACnC,MAAM,CAAS;IAE/B,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;CACF;AAPD,0CAOC;AAED;;GAEG;AACH,MAAa,eAAgB,SAAQ,gBAAgB;IACnD,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAJD,0CAIC;AAED;;GAEG;AACH,MAAa,WAAY,SAAQ,gBAAgB;IAC/C,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAJD,kCAIC","sourcesContent":["/**\n * Base error class for all library errors\n */\nexport class OpenAPIToolError extends Error {\n public readonly context?: Record<string, any>;\n\n constructor(message: string, context?: Record<string, any>) {\n super(message);\n this.name = this.constructor.name;\n this.context = context;\n\n // captureStackTrace is Node.js-specific, guard against non-Node environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when loading an OpenAPI specification fails\n */\nexport class LoadError extends OpenAPIToolError {\n constructor(message: string, context?: Record<string, any>) {\n super(message, context);\n }\n}\n\n/**\n * Error thrown when parsing an OpenAPI specification fails\n */\nexport class ParseError extends OpenAPIToolError {\n constructor(message: string, context?: Record<string, any>) {\n super(message, context);\n }\n}\n\n/**\n * Error thrown when validating an OpenAPI specification fails\n */\nexport class ValidationError extends OpenAPIToolError {\n public readonly errors?: any[];\n\n constructor(message: string, context?: Record<string, any>) {\n super(message, context);\n this.errors = context?.['errors'];\n }\n}\n\n/**\n * Error thrown when generating a tool fails\n */\nexport class GenerationError extends OpenAPIToolError {\n constructor(message: string, context?: Record<string, any>) {\n super(message, context);\n }\n}\n\n/**\n * Error thrown when a schema is invalid\n */\nexport class SchemaError extends OpenAPIToolError {\n constructor(message: string, context?: Record<string, any>) {\n super(message, context);\n }\n}\n"]}
|
package/src/generator.js
CHANGED
|
@@ -15,6 +15,9 @@ const errors_1 = require("./errors");
|
|
|
15
15
|
* Main class for generating MCP tools from OpenAPI specifications
|
|
16
16
|
*/
|
|
17
17
|
class OpenAPIToolGenerator {
|
|
18
|
+
document;
|
|
19
|
+
dereferencedDocument;
|
|
20
|
+
options;
|
|
18
21
|
/**
|
|
19
22
|
* Private constructor - use static factory methods to create instances
|
|
20
23
|
*/
|
|
@@ -43,7 +46,10 @@ class OpenAPIToolGenerator {
|
|
|
43
46
|
});
|
|
44
47
|
clearTimeout(timeout);
|
|
45
48
|
if (!response.ok) {
|
|
46
|
-
throw new errors_1.LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, {
|
|
49
|
+
throw new errors_1.LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, {
|
|
50
|
+
url,
|
|
51
|
+
status: response.status,
|
|
52
|
+
});
|
|
47
53
|
}
|
|
48
54
|
const contentType = response.headers.get('content-type') || '';
|
|
49
55
|
const text = await response.text();
|
|
@@ -186,7 +192,8 @@ class OpenAPIToolGenerator {
|
|
|
186
192
|
tools.push(tool);
|
|
187
193
|
}
|
|
188
194
|
catch (error) {
|
|
189
|
-
|
|
195
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
196
|
+
console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, errorMessage);
|
|
190
197
|
}
|
|
191
198
|
}
|
|
192
199
|
}
|
|
@@ -262,7 +269,7 @@ class OpenAPIToolGenerator {
|
|
|
262
269
|
return options.filterFn({
|
|
263
270
|
...operation,
|
|
264
271
|
path,
|
|
265
|
-
method
|
|
272
|
+
method,
|
|
266
273
|
});
|
|
267
274
|
}
|
|
268
275
|
return true;
|
|
@@ -293,16 +300,19 @@ class OpenAPIToolGenerator {
|
|
|
293
300
|
path,
|
|
294
301
|
method,
|
|
295
302
|
operationId: operation.operationId,
|
|
303
|
+
operationSummary: operation.summary,
|
|
304
|
+
operationDescription: operation.description,
|
|
296
305
|
tags: operation.tags,
|
|
297
306
|
deprecated: operation.deprecated,
|
|
298
307
|
};
|
|
299
308
|
// Extract security requirements
|
|
300
309
|
if (operation.security || document.security) {
|
|
301
|
-
metadata.security = this.extractSecurityRequirements(operation.security ?? document.security, document);
|
|
310
|
+
metadata.security = this.extractSecurityRequirements((operation.security ?? document.security), document);
|
|
302
311
|
}
|
|
303
312
|
// Extract servers
|
|
304
|
-
|
|
305
|
-
|
|
313
|
+
const servers = operation.servers ?? document.servers;
|
|
314
|
+
if (servers) {
|
|
315
|
+
metadata.servers = servers.map((server) => ({
|
|
306
316
|
url: this.options.baseUrl || server.url,
|
|
307
317
|
description: server.description,
|
|
308
318
|
variables: server.variables,
|
|
@@ -312,23 +322,27 @@ class OpenAPIToolGenerator {
|
|
|
312
322
|
metadata.servers = [{ url: this.options.baseUrl }];
|
|
313
323
|
}
|
|
314
324
|
// Extract response status codes (preserve 0 for default responses)
|
|
315
|
-
|
|
316
|
-
|
|
325
|
+
const schemaObj = outputSchema;
|
|
326
|
+
if (schemaObj && Array.isArray(schemaObj['oneOf'])) {
|
|
327
|
+
const codes = schemaObj['oneOf']
|
|
317
328
|
.map((schema) => schema['x-status-code'])
|
|
318
329
|
.filter((code) => code !== undefined && code !== null);
|
|
319
330
|
if (codes.length > 0) {
|
|
320
331
|
metadata.responseStatusCodes = codes;
|
|
321
332
|
}
|
|
322
333
|
}
|
|
323
|
-
else if (
|
|
324
|
-
|
|
325
|
-
outputSchema['x-status-code'] !== null) {
|
|
326
|
-
metadata.responseStatusCodes = [outputSchema['x-status-code']];
|
|
334
|
+
else if (schemaObj && schemaObj['x-status-code'] !== undefined && schemaObj['x-status-code'] !== null) {
|
|
335
|
+
metadata.responseStatusCodes = [schemaObj['x-status-code']];
|
|
327
336
|
}
|
|
328
337
|
// External docs
|
|
329
338
|
if (operation.externalDocs) {
|
|
330
339
|
metadata.externalDocs = operation.externalDocs;
|
|
331
340
|
}
|
|
341
|
+
// FrontMCP extension (x-frontmcp)
|
|
342
|
+
const operationWithExt = operation;
|
|
343
|
+
if (operationWithExt['x-frontmcp']) {
|
|
344
|
+
metadata.frontmcp = operationWithExt['x-frontmcp'];
|
|
345
|
+
}
|
|
332
346
|
return metadata;
|
|
333
347
|
}
|
|
334
348
|
/**
|
|
@@ -350,9 +364,7 @@ class OpenAPIToolGenerator {
|
|
|
350
364
|
type: securityScheme.type,
|
|
351
365
|
scopes,
|
|
352
366
|
name: 'name' in securityScheme ? securityScheme.name : undefined,
|
|
353
|
-
in: apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie')
|
|
354
|
-
? apiKeyIn
|
|
355
|
-
: undefined,
|
|
367
|
+
in: apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie') ? apiKeyIn : undefined,
|
|
356
368
|
};
|
|
357
369
|
// Add HTTP-specific metadata
|
|
358
370
|
if (securityScheme.type === 'http') {
|
package/src/generator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../../src/generator.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,wDAAkC;AAClC,mDAA6B;AAC7B,yGAA6D;AAa7D,mCAA4C;AAC5C,6DAAyD;AACzD,yDAAqD;AACrD,2CAAwC;AACxC,qCAAiD;AAEjD;;GAEG;AACH,MAAa,oBAAoB;IAK/B;;OAEG;IACH,YAAoB,QAAyB,EAAE,UAAuB,EAAE;QACtE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG;YACb,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,IAAI;YACxC,OAAO,EAAE,OAAO,CAAC,OAAO,IA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AM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;YAC1C,CAAC;YAED,MAAM,QAAQ,GAAG,IAAI,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;YACxE,MAAM,MAAM,GAAwB;gBAClC,MAAM;gBACN,IAAI,EAAE,cAAc,CAAC,IAAgB;gBACrC,MAAM;gBACN,IAAI,EAAE,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;gBAChE,EAAE,EAAE,QAAQ,IAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ,CAAC;oBACtF,CAAC,CAAC,QAAQ;oBACV,CAAC,CAAC,SAAS;aACd,CAAC;YAEF,6BAA6B;YAC7B,IAAI,cAAc,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACnC,MAAM,CAAC,UAAU,GAAG,QAAQ,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;gBACnF,MAAM,CAAC,YAAY,GAAG,cAAc,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC;YACnG,CAAC;YAED,+BAA+B;YAC/B,MAAM,CAAC,WAAW,GAAG,aAAa,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;YAE9F,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF;AA3cD,oDA2cC","sourcesContent":["import * as yaml from 'yaml';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport $RefParser from '@apidevtools/json-schema-ref-parser';\nimport type {\n OpenAPIDocument,\n LoadOptions,\n GenerateOptions,\n McpOpenAPITool,\n ValidationResult,\n HTTPMethod,\n ParameterObject,\n SecurityRequirement,\n SecuritySchemeObject,\n AuthType,\n} from './types';\nimport { isReferenceObject } from './types';\nimport { ParameterResolver } from './parameter-resolver';\nimport { ResponseBuilder } from './response-builder';\nimport { Validator } from './validator';\nimport { LoadError, ParseError } from './errors';\n\n/**\n * Main class for generating MCP tools from OpenAPI specifications\n */\nexport class OpenAPIToolGenerator {\n private document: OpenAPIDocument;\n private dereferencedDocument?: OpenAPIDocument;\n private options: Required<LoadOptions>;\n\n /**\n * Private constructor - use static factory methods to create instances\n */\n private constructor(document: OpenAPIDocument, options: LoadOptions = {}) {\n this.document = document;\n this.options = {\n dereference: options.dereference ?? true,\n baseUrl: options.baseUrl ?? '',\n headers: options.headers ?? {},\n timeout: options.timeout ?? 30000,\n validate: options.validate ?? true,\n followRedirects: options.followRedirects ?? true,\n };\n }\n\n /**\n * Create generator from a URL\n */\n static async fromURL(\n url: string,\n options: LoadOptions = {}\n ): Promise<OpenAPIToolGenerator> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), options.timeout ?? 30000);\n\n const response = await fetch(url, {\n headers: options.headers,\n signal: controller.signal,\n redirect: options.followRedirects ?? true ? 'follow' : 'manual',\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n throw new LoadError(\n `Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`,\n { url, status: response.status }\n );\n }\n\n const contentType = response.headers.get('content-type') || '';\n const text = await response.text();\n\n let document: OpenAPIDocument;\n if (contentType.includes('yaml') || contentType.includes('yml') || url.match(/\\.ya?ml$/i)) {\n document = yaml.parse(text);\n } else {\n document = JSON.parse(text);\n }\n\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n if (error instanceof LoadError) {\n throw error;\n }\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new LoadError(`Failed to load OpenAPI spec from URL: ${errorMessage}`, {\n url,\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a file path\n */\n static async fromFile(\n filePath: string,\n options: LoadOptions = {}\n ): Promise<OpenAPIToolGenerator> {\n try {\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);\n const content = await fs.readFile(absolutePath, 'utf-8');\n const ext = path.extname(filePath).toLowerCase();\n\n let document: OpenAPIDocument;\n if (ext === '.yaml' || ext === '.yml') {\n document = yaml.parse(content);\n } else if (ext === '.json') {\n document = JSON.parse(content);\n } else {\n // Try to parse as JSON first, then YAML\n try {\n document = JSON.parse(content);\n } catch {\n document = yaml.parse(content);\n }\n }\n\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new LoadError(`Failed to load OpenAPI spec from file: ${errorMessage}`, {\n filePath,\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a YAML string\n */\n static async fromYAML(\n yamlString: string,\n options: LoadOptions = {}\n ): Promise<OpenAPIToolGenerator> {\n try {\n const document = yaml.parse(yamlString);\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ParseError(`Failed to parse YAML: ${errorMessage}`, {\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a JSON object\n */\n static async fromJSON(\n json: object,\n options: LoadOptions = {}\n ): Promise<OpenAPIToolGenerator> {\n // Clone to avoid mutations\n const document = JSON.parse(JSON.stringify(json));\n return new OpenAPIToolGenerator(document, options);\n }\n\n /**\n * Get the OpenAPI document\n */\n getDocument(): OpenAPIDocument {\n return this.dereferencedDocument ?? this.document;\n }\n\n /**\n * Validate the OpenAPI document\n */\n async validate(): Promise<ValidationResult> {\n const validator = new Validator();\n return validator.validate(this.document);\n }\n\n /**\n * Initialize the generator (dereference if needed)\n */\n private async initialize(): Promise<void> {\n if (this.options.validate) {\n const result = await this.validate();\n if (!result.valid) {\n throw new ParseError('Invalid OpenAPI document', { errors: result.errors });\n }\n }\n\n if (this.options.dereference && !this.dereferencedDocument) {\n try {\n this.dereferencedDocument = (await $RefParser.dereference(\n JSON.parse(JSON.stringify(this.document))\n )) as OpenAPIDocument;\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ParseError(`Failed to dereference OpenAPI document: ${errorMessage}`, {\n originalError: error,\n });\n }\n }\n }\n\n /**\n * Generate all tools from the OpenAPI specification\n */\n async generateTools(options: GenerateOptions = {}): Promise<McpOpenAPITool[]> {\n await this.initialize();\n\n const document = this.getDocument();\n const tools: McpOpenAPITool[] = [];\n\n if (!document.paths) {\n return tools;\n }\n\n for (const [pathStr, pathItem] of Object.entries(document.paths)) {\n if (!pathItem || '$ref' in pathItem) continue;\n\n const methods: HTTPMethod[] = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];\n\n for (const method of methods) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n // Apply filters\n if (!this.shouldIncludeOperation(operation, pathStr, method, options)) {\n continue;\n }\n\n try {\n const tool = await this.generateTool(pathStr, method, options);\n tools.push(tool);\n } catch (error: any) {\n console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, error.message);\n }\n }\n }\n\n return tools;\n }\n\n /**\n * Generate a specific tool for a path and method\n */\n async generateTool(\n pathStr: string,\n method: string,\n options: GenerateOptions = {}\n ): Promise<McpOpenAPITool> {\n await this.initialize();\n\n const document = this.getDocument();\n\n if (!document.paths) {\n throw new Error('No paths defined in OpenAPI document');\n }\n\n const pathItem = document.paths[pathStr];\n const operation = pathItem?.[method.toLowerCase() as HTTPMethod];\n\n if (!operation) {\n throw new Error(`Operation not found: ${method.toUpperCase()} ${pathStr}`);\n }\n\n // Resolve parameters\n const parameterResolver = new ParameterResolver(options.namingStrategy);\n\n // Filter out ReferenceObjects from parameters\n let pathParameters: ParameterObject[] | undefined = undefined;\n if (pathItem.parameters) {\n pathParameters = pathItem.parameters.filter(\n (p): p is ParameterObject => !isReferenceObject(p)\n ) as ParameterObject[];\n }\n\n // Extract security requirements\n let securityRequirements: SecurityRequirement[] | undefined = undefined;\n const securitySpec = operation.security ?? document.security;\n if (securitySpec) {\n securityRequirements = this.extractSecurityRequirements(\n securitySpec as Record<string, string[]>[],\n document\n );\n }\n\n const { inputSchema, mapper } = parameterResolver.resolve(\n operation,\n pathParameters,\n securityRequirements,\n options.includeSecurityInInput\n );\n\n // Build response schema\n const responseBuilder = new ResponseBuilder(options);\n const outputSchema = responseBuilder.build(operation.responses);\n\n // Generate tool name\n const name = this.generateToolName(pathStr, method as HTTPMethod, operation.operationId, options);\n\n // Generate description\n const description = operation.summary || operation.description || `${method.toUpperCase()} ${pathStr}`;\n\n // Extract metadata\n const metadata = this.extractMetadata(pathStr, method as HTTPMethod, operation, document, outputSchema);\n\n return {\n name,\n description,\n inputSchema,\n outputSchema,\n mapper,\n metadata,\n };\n }\n\n /**\n * Check if an operation should be included\n */\n private shouldIncludeOperation(\n operation: any,\n path: string,\n method: string,\n options: GenerateOptions\n ): boolean {\n // Check deprecated\n if (operation.deprecated && !options.includeDeprecated) {\n return false;\n }\n\n // Check operation ID filters\n if (options.includeOperations && operation.operationId) {\n if (!options.includeOperations.includes(operation.operationId)) {\n return false;\n }\n }\n\n if (options.excludeOperations && operation.operationId) {\n if (options.excludeOperations.includes(operation.operationId)) {\n return false;\n }\n }\n\n // Custom filter\n if (options.filterFn) {\n return options.filterFn({\n ...operation,\n path,\n method\n } as any);\n }\n\n return true;\n }\n\n /**\n * Generate a tool name\n */\n private generateToolName(\n path: string,\n method: HTTPMethod,\n operationId?: string,\n options: GenerateOptions = {}\n ): string {\n if (options.namingStrategy?.toolNameGenerator) {\n return options.namingStrategy.toolNameGenerator(path, method, operationId);\n }\n\n if (operationId) {\n return operationId;\n }\n\n // Generate from path and method\n const sanitized = path\n .replace(/\\{([^}]+)\\}/g, 'By_$1')\n .replace(/[^a-zA-Z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n\n return `${method}_${sanitized}`;\n }\n\n /**\n * Extract metadata from operation\n */\n private extractMetadata(\n path: string,\n method: HTTPMethod,\n operation: any,\n document: OpenAPIDocument,\n outputSchema?: any\n ): any {\n const metadata: any = {\n path,\n method,\n operationId: operation.operationId,\n tags: operation.tags,\n deprecated: operation.deprecated,\n };\n\n // Extract security requirements\n if (operation.security || document.security) {\n metadata.security = this.extractSecurityRequirements(\n operation.security ?? document.security,\n document\n );\n }\n\n // Extract servers\n if (operation.servers || document.servers) {\n metadata.servers = (operation.servers ?? document.servers).map((server: any) => ({\n url: this.options.baseUrl || server.url,\n description: server.description,\n variables: server.variables,\n }));\n } else if (this.options.baseUrl) {\n metadata.servers = [{ url: this.options.baseUrl }];\n }\n\n // Extract response status codes (preserve 0 for default responses)\n if (outputSchema && Array.isArray((outputSchema as any).oneOf)) {\n const codes = (outputSchema as any).oneOf\n .map((schema: any) => (schema as any)['x-status-code'])\n .filter((code: unknown) => code !== undefined && code !== null);\n if (codes.length > 0) {\n metadata.responseStatusCodes = codes;\n }\n } else if (\n outputSchema &&\n (outputSchema as any)['x-status-code'] !== undefined &&\n (outputSchema as any)['x-status-code'] !== null\n ) {\n metadata.responseStatusCodes = [(outputSchema as any)['x-status-code']];\n }\n\n // External docs\n if (operation.externalDocs) {\n metadata.externalDocs = operation.externalDocs;\n }\n\n return metadata;\n }\n\n /**\n * Extract security requirements\n */\n private extractSecurityRequirements(\n security: Record<string, string[]>[],\n document: OpenAPIDocument\n ): SecurityRequirement[] {\n if (!security || !document.components?.securitySchemes) {\n return [];\n }\n\n return security.flatMap((req) =>\n Object.entries(req).map(([scheme, scopes]): SecurityRequirement => {\n const securityScheme = document.components!.securitySchemes![scheme];\n\n // Skip if it's a reference object\n if (isReferenceObject(securityScheme)) {\n return { scheme, type: 'http', scopes };\n }\n\n const apiKeyIn = 'in' in securityScheme ? securityScheme.in : undefined;\n const result: SecurityRequirement = {\n scheme,\n type: securityScheme.type as AuthType,\n scopes,\n name: 'name' in securityScheme ? securityScheme.name : undefined,\n in: apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie')\n ? apiKeyIn\n : undefined,\n };\n\n // Add HTTP-specific metadata\n if (securityScheme.type === 'http') {\n result.httpScheme = 'scheme' in securityScheme ? securityScheme.scheme : undefined;\n result.bearerFormat = 'bearerFormat' in securityScheme ? securityScheme.bearerFormat : undefined;\n }\n\n // Add description if available\n result.description = 'description' in securityScheme ? securityScheme.description : undefined;\n\n return result;\n })\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../../src/generator.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,wDAAkC;AAClC,mDAA6B;AAC7B,yGAA6D;AAgB7D,mCAA4C;AAC5C,6DAAyD;AACzD,yDAAqD;AACrD,2CAAwC;AACxC,qCAAiD;AAEjD;;GAEG;AACH,MAAa,oBAAoB;IACvB,QAAQ,CAAkB;IAC1B,oBAAoB,CAAmB;IACvC,OAAO,CAAwB;IAEvC;;OAEG;IACH,YAAoB,QAAyB,EAAE,UAAuB,EAAE;QACtE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG;YACb,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,IAAI;YACxC,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE;YAC9B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE;YAC9B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,KAAK;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,IAAI;YAClC,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,IAAI;SACjD,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,GAAW,EAAE,UAAuB,EAAE;QACzD,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;YACzC,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE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tC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;YAC1C,CAAC;YAED,MAAM,QAAQ,GAAG,IAAI,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;YACxE,MAAM,MAAM,GAAwB;gBAClC,MAAM;gBACN,IAAI,EAAE,cAAc,CAAC,IAAgB;gBACrC,MAAM;gBACN,IAAI,EAAE,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;gBAChE,EAAE,EACA,QAAQ,IAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;aAC9G,CAAC;YAEF,6BAA6B;YAC7B,IAAI,cAAc,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACnC,MAAM,CAAC,UAAU,GAAG,QAAQ,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;gBACnF,MAAM,CAAC,YAAY,GAAG,cAAc,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC;YACnG,CAAC;YAED,+BAA+B;YAC/B,MAAM,CAAC,WAAW,GAAG,aAAa,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;YAE9F,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF;AA9bD,oDA8bC","sourcesContent":["import * as yaml from 'yaml';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport $RefParser from '@apidevtools/json-schema-ref-parser';\nimport type {\n OpenAPIDocument,\n LoadOptions,\n GenerateOptions,\n McpOpenAPITool,\n ValidationResult,\n HTTPMethod,\n ParameterObject,\n SecurityRequirement,\n AuthType,\n OperationObject,\n OperationWithContext,\n ToolMetadata,\n ServerObject,\n} from './types';\nimport { isReferenceObject } from './types';\nimport { ParameterResolver } from './parameter-resolver';\nimport { ResponseBuilder } from './response-builder';\nimport { Validator } from './validator';\nimport { LoadError, ParseError } from './errors';\n\n/**\n * Main class for generating MCP tools from OpenAPI specifications\n */\nexport class OpenAPIToolGenerator {\n private document: OpenAPIDocument;\n private dereferencedDocument?: OpenAPIDocument;\n private options: Required<LoadOptions>;\n\n /**\n * Private constructor - use static factory methods to create instances\n */\n private constructor(document: OpenAPIDocument, options: LoadOptions = {}) {\n this.document = document;\n this.options = {\n dereference: options.dereference ?? true,\n baseUrl: options.baseUrl ?? '',\n headers: options.headers ?? {},\n timeout: options.timeout ?? 30000,\n validate: options.validate ?? true,\n followRedirects: options.followRedirects ?? true,\n };\n }\n\n /**\n * Create generator from a URL\n */\n static async fromURL(url: string, options: LoadOptions = {}): Promise<OpenAPIToolGenerator> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), options.timeout ?? 30000);\n\n const response = await fetch(url, {\n headers: options.headers,\n signal: controller.signal,\n redirect: options.followRedirects ?? true ? 'follow' : 'manual',\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n throw new LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, {\n url,\n status: response.status,\n });\n }\n\n const contentType = response.headers.get('content-type') || '';\n const text = await response.text();\n\n let document: OpenAPIDocument;\n if (contentType.includes('yaml') || contentType.includes('yml') || url.match(/\\.ya?ml$/i)) {\n document = yaml.parse(text);\n } else {\n document = JSON.parse(text);\n }\n\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n if (error instanceof LoadError) {\n throw error;\n }\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new LoadError(`Failed to load OpenAPI spec from URL: ${errorMessage}`, {\n url,\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a file path\n */\n static async fromFile(filePath: string, options: LoadOptions = {}): Promise<OpenAPIToolGenerator> {\n try {\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);\n const content = await fs.readFile(absolutePath, 'utf-8');\n const ext = path.extname(filePath).toLowerCase();\n\n let document: OpenAPIDocument;\n if (ext === '.yaml' || ext === '.yml') {\n document = yaml.parse(content);\n } else if (ext === '.json') {\n document = JSON.parse(content);\n } else {\n // Try to parse as JSON first, then YAML\n try {\n document = JSON.parse(content);\n } catch {\n document = yaml.parse(content);\n }\n }\n\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new LoadError(`Failed to load OpenAPI spec from file: ${errorMessage}`, {\n filePath,\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a YAML string\n */\n static async fromYAML(yamlString: string, options: LoadOptions = {}): Promise<OpenAPIToolGenerator> {\n try {\n const document = yaml.parse(yamlString);\n return new OpenAPIToolGenerator(document, options);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ParseError(`Failed to parse YAML: ${errorMessage}`, {\n originalError: error,\n });\n }\n }\n\n /**\n * Create generator from a JSON object\n */\n static async fromJSON(json: object, options: LoadOptions = {}): Promise<OpenAPIToolGenerator> {\n // Clone to avoid mutations\n const document = JSON.parse(JSON.stringify(json));\n return new OpenAPIToolGenerator(document, options);\n }\n\n /**\n * Get the OpenAPI document\n */\n getDocument(): OpenAPIDocument {\n return this.dereferencedDocument ?? this.document;\n }\n\n /**\n * Validate the OpenAPI document\n */\n async validate(): Promise<ValidationResult> {\n const validator = new Validator();\n return validator.validate(this.document);\n }\n\n /**\n * Initialize the generator (dereference if needed)\n */\n private async initialize(): Promise<void> {\n if (this.options.validate) {\n const result = await this.validate();\n if (!result.valid) {\n throw new ParseError('Invalid OpenAPI document', { errors: result.errors });\n }\n }\n\n if (this.options.dereference && !this.dereferencedDocument) {\n try {\n this.dereferencedDocument = (await $RefParser.dereference(\n JSON.parse(JSON.stringify(this.document)),\n )) as OpenAPIDocument;\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ParseError(`Failed to dereference OpenAPI document: ${errorMessage}`, {\n originalError: error,\n });\n }\n }\n }\n\n /**\n * Generate all tools from the OpenAPI specification\n */\n async generateTools(options: GenerateOptions = {}): Promise<McpOpenAPITool[]> {\n await this.initialize();\n\n const document = this.getDocument();\n const tools: McpOpenAPITool[] = [];\n\n if (!document.paths) {\n return tools;\n }\n\n for (const [pathStr, pathItem] of Object.entries(document.paths)) {\n if (!pathItem || '$ref' in pathItem) continue;\n\n const methods: HTTPMethod[] = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];\n\n for (const method of methods) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n // Apply filters\n if (!this.shouldIncludeOperation(operation, pathStr, method, options)) {\n continue;\n }\n\n try {\n const tool = await this.generateTool(pathStr, method, options);\n tools.push(tool);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, errorMessage);\n }\n }\n }\n\n return tools;\n }\n\n /**\n * Generate a specific tool for a path and method\n */\n async generateTool(pathStr: string, method: string, options: GenerateOptions = {}): Promise<McpOpenAPITool> {\n await this.initialize();\n\n const document = this.getDocument();\n\n if (!document.paths) {\n throw new Error('No paths defined in OpenAPI document');\n }\n\n const pathItem = document.paths[pathStr];\n const operation = pathItem?.[method.toLowerCase() as HTTPMethod];\n\n if (!operation) {\n throw new Error(`Operation not found: ${method.toUpperCase()} ${pathStr}`);\n }\n\n // Resolve parameters\n const parameterResolver = new ParameterResolver(options.namingStrategy);\n\n // Filter out ReferenceObjects from parameters\n let pathParameters: ParameterObject[] | undefined = undefined;\n if (pathItem.parameters) {\n pathParameters = pathItem.parameters.filter(\n (p): p is ParameterObject => !isReferenceObject(p),\n ) as ParameterObject[];\n }\n\n // Extract security requirements\n let securityRequirements: SecurityRequirement[] | undefined = undefined;\n const securitySpec = operation.security ?? document.security;\n if (securitySpec) {\n securityRequirements = this.extractSecurityRequirements(securitySpec as Record<string, string[]>[], document);\n }\n\n const { inputSchema, mapper } = parameterResolver.resolve(\n operation,\n pathParameters,\n securityRequirements,\n options.includeSecurityInInput,\n );\n\n // Build response schema\n const responseBuilder = new ResponseBuilder(options);\n const outputSchema = responseBuilder.build(operation.responses);\n\n // Generate tool name\n const name = this.generateToolName(pathStr, method as HTTPMethod, operation.operationId, options);\n\n // Generate description\n const description = operation.summary || operation.description || `${method.toUpperCase()} ${pathStr}`;\n\n // Extract metadata\n const metadata = this.extractMetadata(pathStr, method as HTTPMethod, operation, document, outputSchema);\n\n return {\n name,\n description,\n inputSchema,\n outputSchema,\n mapper,\n metadata,\n };\n }\n\n /**\n * Check if an operation should be included\n */\n private shouldIncludeOperation(\n operation: OperationObject,\n path: string,\n method: string,\n options: GenerateOptions,\n ): boolean {\n // Check deprecated\n if (operation.deprecated && !options.includeDeprecated) {\n return false;\n }\n\n // Check operation ID filters\n if (options.includeOperations && operation.operationId) {\n if (!options.includeOperations.includes(operation.operationId)) {\n return false;\n }\n }\n\n if (options.excludeOperations && operation.operationId) {\n if (options.excludeOperations.includes(operation.operationId)) {\n return false;\n }\n }\n\n // Custom filter\n if (options.filterFn) {\n return options.filterFn({\n ...operation,\n path,\n method,\n } as OperationWithContext);\n }\n\n return true;\n }\n\n /**\n * Generate a tool name\n */\n private generateToolName(\n path: string,\n method: HTTPMethod,\n operationId?: string,\n options: GenerateOptions = {},\n ): string {\n if (options.namingStrategy?.toolNameGenerator) {\n return options.namingStrategy.toolNameGenerator(path, method, operationId);\n }\n\n if (operationId) {\n return operationId;\n }\n\n // Generate from path and method\n const sanitized = path\n .replace(/\\{([^}]+)\\}/g, 'By_$1')\n .replace(/[^a-zA-Z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n\n return `${method}_${sanitized}`;\n }\n\n /**\n * Extract metadata from operation\n */\n private extractMetadata(\n path: string,\n method: HTTPMethod,\n operation: OperationObject,\n document: OpenAPIDocument,\n outputSchema?: unknown,\n ): ToolMetadata {\n const metadata: ToolMetadata = {\n path,\n method,\n operationId: operation.operationId,\n operationSummary: operation.summary,\n operationDescription: operation.description,\n tags: operation.tags,\n deprecated: operation.deprecated,\n };\n\n // Extract security requirements\n if (operation.security || document.security) {\n metadata.security = this.extractSecurityRequirements(\n (operation.security ?? document.security) as Record<string, string[]>[],\n document,\n );\n }\n\n // Extract servers\n const servers = (operation as { servers?: ServerObject[] }).servers ?? document.servers;\n if (servers) {\n metadata.servers = servers.map((server: ServerObject) => ({\n url: this.options.baseUrl || server.url,\n description: server.description,\n variables: server.variables,\n }));\n } else if (this.options.baseUrl) {\n metadata.servers = [{ url: this.options.baseUrl }];\n }\n\n // Extract response status codes (preserve 0 for default responses)\n const schemaObj = outputSchema as Record<string, unknown> | undefined;\n if (schemaObj && Array.isArray(schemaObj['oneOf'])) {\n const codes = (schemaObj['oneOf'] as Record<string, unknown>[])\n .map((schema) => schema['x-status-code'])\n .filter((code): code is number => code !== undefined && code !== null);\n if (codes.length > 0) {\n metadata.responseStatusCodes = codes;\n }\n } else if (schemaObj && schemaObj['x-status-code'] !== undefined && schemaObj['x-status-code'] !== null) {\n metadata.responseStatusCodes = [schemaObj['x-status-code'] as number];\n }\n\n // External docs\n if (operation.externalDocs) {\n metadata.externalDocs = operation.externalDocs;\n }\n\n // FrontMCP extension (x-frontmcp)\n const operationWithExt = operation as Record<string, unknown>;\n if (operationWithExt['x-frontmcp']) {\n metadata.frontmcp = operationWithExt['x-frontmcp'] as ToolMetadata['frontmcp'];\n }\n\n return metadata;\n }\n\n /**\n * Extract security requirements\n */\n private extractSecurityRequirements(\n security: Record<string, string[]>[],\n document: OpenAPIDocument,\n ): SecurityRequirement[] {\n if (!security || !document.components?.securitySchemes) {\n return [];\n }\n\n return security.flatMap((req) =>\n Object.entries(req).map(([scheme, scopes]): SecurityRequirement => {\n const securityScheme = document.components!.securitySchemes![scheme];\n\n // Skip if it's a reference object\n if (isReferenceObject(securityScheme)) {\n return { scheme, type: 'http', scopes };\n }\n\n const apiKeyIn = 'in' in securityScheme ? securityScheme.in : undefined;\n const result: SecurityRequirement = {\n scheme,\n type: securityScheme.type as AuthType,\n scopes,\n name: 'name' in securityScheme ? securityScheme.name : undefined,\n in:\n apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie') ? apiKeyIn : undefined,\n };\n\n // Add HTTP-specific metadata\n if (securityScheme.type === 'http') {\n result.httpScheme = 'scheme' in securityScheme ? securityScheme.scheme : undefined;\n result.bearerFormat = 'bearerFormat' in securityScheme ? securityScheme.bearerFormat : undefined;\n }\n\n // Add description if available\n result.description = 'description' in securityScheme ? securityScheme.description : undefined;\n\n return result;\n }),\n );\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { ParameterResolver } from './parameter-resolver';
|
|
|
4
4
|
export { ResponseBuilder } from './response-builder';
|
|
5
5
|
export { Validator } from './validator';
|
|
6
6
|
export { SecurityResolver, createSecurityContext } from './security-resolver';
|
|
7
|
-
export { OpenAPIToolError, LoadError, ParseError, ValidationError, GenerationError, SchemaError
|
|
8
|
-
export type { McpOpenAPITool, ParameterMapper, ToolMetadata, SerializationInfo, SecurityRequirement, SecurityParameterInfo, ServerInfo, LoadOptions, GenerateOptions, NamingStrategy, OperationWithContext, OpenAPIDocument, OpenAPIVersion, HTTPMethod, ParameterLocation, AuthType, OperationObject, ParameterObject, RequestBodyObject, ResponseObject, ResponsesObject, MediaTypeObject, HeaderObject, ExampleObject, PathItemObject, PathsObject, ServerObject, SecuritySchemeObject, ReferenceObject, TagObject, ExternalDocumentationObject, ServerVariableObject, EncodingObject, SecurityRequirementObject, SchemaObject, ValidationResult, ValidationErrorDetail, ValidationWarning, } from './types';
|
|
7
|
+
export { OpenAPIToolError, LoadError, ParseError, ValidationError, GenerationError, SchemaError } from './errors';
|
|
8
|
+
export type { McpOpenAPITool, ParameterMapper, ToolMetadata, FrontMcpExtensionData, SerializationInfo, SecurityRequirement, SecurityParameterInfo, ServerInfo, LoadOptions, GenerateOptions, NamingStrategy, OperationWithContext, OpenAPIDocument, OpenAPIVersion, HTTPMethod, ParameterLocation, AuthType, OperationObject, ParameterObject, RequestBodyObject, ResponseObject, ResponsesObject, MediaTypeObject, HeaderObject, ExampleObject, PathItemObject, PathsObject, ServerObject, SecuritySchemeObject, ReferenceObject, TagObject, ExternalDocumentationObject, ServerVariableObject, EncodingObject, SecurityRequirementObject, SchemaObject, ValidationResult, ValidationErrorDetail, ValidationWarning, } from './types';
|
|
9
9
|
export type { SecurityContext, ResolvedSecurity, DigestAuthCredentials, ClientCertificate, AWSCredentials, SignatureData, } from './security-resolver';
|
|
10
|
-
export { isReferenceObject,
|
|
10
|
+
export { isReferenceObject, toJsonSchema } from './types';
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.toJsonSchema = exports.isReferenceObject = exports.SchemaError = exports.GenerationError = exports.ValidationError = exports.ParseError = exports.LoadError = exports.OpenAPIToolError = exports.createSecurityContext = exports.SecurityResolver = exports.Validator = exports.ResponseBuilder = exports.ParameterResolver = exports.SchemaBuilder = exports.OpenAPIToolGenerator = void 0;
|
|
4
4
|
// Main exports
|
|
5
5
|
var generator_1 = require("./generator");
|
|
6
6
|
Object.defineProperty(exports, "OpenAPIToolGenerator", { enumerable: true, get: function () { return generator_1.OpenAPIToolGenerator; } });
|
|
@@ -26,5 +26,5 @@ Object.defineProperty(exports, "SchemaError", { enumerable: true, get: function
|
|
|
26
26
|
// Utility exports
|
|
27
27
|
var types_1 = require("./types");
|
|
28
28
|
Object.defineProperty(exports, "isReferenceObject", { enumerable: true, get: function () { return types_1.isReferenceObject; } });
|
|
29
|
-
Object.defineProperty(exports, "
|
|
29
|
+
Object.defineProperty(exports, "toJsonSchema", { enumerable: true, get: function () { return types_1.toJsonSchema; } });
|
|
30
30
|
//# sourceMappingURL=index.js.map
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,eAAe;AACf,yCAAmD;AAA1C,iHAAA,oBAAoB,OAAA;AAC7B,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AACtB,2DAAyD;AAAhD,uHAAA,iBAAiB,OAAA;AAC1B,uDAAqD;AAA5C,mHAAA,eAAe,OAAA;AACxB,yCAAwC;AAA/B,sGAAA,SAAS,OAAA;AAClB,yDAA8E;AAArE,qHAAA,gBAAgB,OAAA;AAAE,0HAAA,qBAAqB,OAAA;AAEhD,gBAAgB;AAChB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,eAAe;AACf,yCAAmD;AAA1C,iHAAA,oBAAoB,OAAA;AAC7B,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AACtB,2DAAyD;AAAhD,uHAAA,iBAAiB,OAAA;AAC1B,uDAAqD;AAA5C,mHAAA,eAAe,OAAA;AACxB,yCAAwC;AAA/B,sGAAA,SAAS,OAAA;AAClB,yDAA8E;AAArE,qHAAA,gBAAgB,OAAA;AAAE,0HAAA,qBAAqB,OAAA;AAEhD,gBAAgB;AAChB,mCAAkH;AAAzG,0GAAA,gBAAgB,OAAA;AAAE,mGAAA,SAAS,OAAA;AAAE,oGAAA,UAAU,OAAA;AAAE,yGAAA,eAAe,OAAA;AAAE,yGAAA,eAAe,OAAA;AAAE,qGAAA,WAAW,OAAA;AAgE/F,kBAAkB;AAClB,iCAA0D;AAAjD,0GAAA,iBAAiB,OAAA;AAAE,qGAAA,YAAY,OAAA","sourcesContent":["// Main exports\nexport { OpenAPIToolGenerator } from './generator';\nexport { SchemaBuilder } from './schema-builder';\nexport { ParameterResolver } from './parameter-resolver';\nexport { ResponseBuilder } from './response-builder';\nexport { Validator } from './validator';\nexport { SecurityResolver, createSecurityContext } from './security-resolver';\n\n// Error exports\nexport { OpenAPIToolError, LoadError, ParseError, ValidationError, GenerationError, SchemaError } from './errors';\n\n// Type exports\nexport type {\n // Main MCP types\n McpOpenAPITool,\n ParameterMapper,\n ToolMetadata,\n FrontMcpExtensionData,\n SerializationInfo,\n SecurityRequirement,\n SecurityParameterInfo,\n ServerInfo,\n\n // Configuration types\n LoadOptions,\n GenerateOptions,\n NamingStrategy,\n OperationWithContext,\n\n // Basic types\n OpenAPIDocument,\n OpenAPIVersion,\n HTTPMethod,\n ParameterLocation,\n AuthType,\n\n // Re-exported OpenAPI types (from openapi-types package)\n OperationObject,\n ParameterObject,\n RequestBodyObject,\n ResponseObject,\n ResponsesObject,\n MediaTypeObject,\n HeaderObject,\n ExampleObject,\n PathItemObject,\n PathsObject,\n ServerObject,\n SecuritySchemeObject,\n ReferenceObject,\n TagObject,\n ExternalDocumentationObject,\n ServerVariableObject,\n EncodingObject,\n SecurityRequirementObject,\n SchemaObject,\n\n // Validation types\n ValidationResult,\n ValidationErrorDetail,\n ValidationWarning,\n} from './types';\n\n// Security resolver types\nexport type {\n SecurityContext,\n ResolvedSecurity,\n DigestAuthCredentials,\n ClientCertificate,\n AWSCredentials,\n SignatureData,\n} from './security-resolver';\n\n// Utility exports\nexport { isReferenceObject, toJsonSchema } from './types';\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JSONSchema } from 'zod/v4/core';
|
|
2
|
+
/** JSON Schema type from Zod v4 */
|
|
3
|
+
type JsonSchema = JSONSchema.JSONSchema;
|
|
2
4
|
import type { ParameterMapper, ParameterObject, NamingStrategy, SecurityRequirement } from './types';
|
|
3
5
|
/**
|
|
4
6
|
* Resolves parameters and handles naming conflicts
|
|
@@ -14,7 +16,7 @@ export declare class ParameterResolver {
|
|
|
14
16
|
* Resolve all parameters for an operation
|
|
15
17
|
*/
|
|
16
18
|
resolve(operation: any, pathParameters?: ParameterObject[], securityRequirements?: SecurityRequirement[], includeSecurityInInput?: boolean): {
|
|
17
|
-
inputSchema:
|
|
19
|
+
inputSchema: JsonSchema;
|
|
18
20
|
mapper: ParameterMapper[];
|
|
19
21
|
};
|
|
20
22
|
/**
|
|
@@ -34,3 +36,4 @@ export declare class ParameterResolver {
|
|
|
34
36
|
*/
|
|
35
37
|
private processSecurityRequirements;
|
|
36
38
|
}
|
|
39
|
+
export {};
|
|
@@ -6,6 +6,7 @@ const types_1 = require("./types");
|
|
|
6
6
|
* Resolves parameters and handles naming conflicts
|
|
7
7
|
*/
|
|
8
8
|
class ParameterResolver {
|
|
9
|
+
namingStrategy;
|
|
9
10
|
constructor(namingStrategy) {
|
|
10
11
|
this.namingStrategy = namingStrategy ?? {
|
|
11
12
|
conflictResolver: this.defaultConflictResolver,
|
|
@@ -28,10 +29,7 @@ class ParameterResolver {
|
|
|
28
29
|
* Resolve all parameters for an operation
|
|
29
30
|
*/
|
|
30
31
|
resolve(operation, pathParameters, securityRequirements, includeSecurityInInput) {
|
|
31
|
-
const allParameters = [
|
|
32
|
-
...(pathParameters ?? []),
|
|
33
|
-
...(operation.parameters ?? []),
|
|
34
|
-
];
|
|
32
|
+
const allParameters = [...(pathParameters ?? []), ...(operation.parameters ?? [])];
|
|
35
33
|
const requestBody = operation.requestBody;
|
|
36
34
|
// Collect all parameter names and detect conflicts
|
|
37
35
|
const parametersByName = new Map();
|
|
@@ -40,7 +38,7 @@ class ParameterResolver {
|
|
|
40
38
|
const info = {
|
|
41
39
|
name: param.name,
|
|
42
40
|
location: param.in,
|
|
43
|
-
required: param.required ??
|
|
41
|
+
required: param.required ?? param.in === 'path',
|
|
44
42
|
schema: param.schema ?? { type: 'string' },
|
|
45
43
|
description: param.description,
|
|
46
44
|
style: param.style,
|
|
@@ -122,8 +120,8 @@ class ParameterResolver {
|
|
|
122
120
|
extractBodyParameters(schema, parametersByName, required, contentType, prefix = '') {
|
|
123
121
|
if (!schema || typeof schema !== 'object')
|
|
124
122
|
return;
|
|
125
|
-
// Convert to
|
|
126
|
-
const jsonSchema = (0, types_1.
|
|
123
|
+
// Convert to JsonSchema for processing
|
|
124
|
+
const jsonSchema = (0, types_1.toJsonSchema)(schema);
|
|
127
125
|
// Handle object schemas
|
|
128
126
|
if (jsonSchema.type === 'object' && jsonSchema.properties) {
|
|
129
127
|
const requiredFields = new Set(jsonSchema.required ?? []);
|
|
@@ -170,7 +168,7 @@ class ParameterResolver {
|
|
|
170
168
|
* Build JSON Schema for a parameter
|
|
171
169
|
*/
|
|
172
170
|
buildParameterSchema(param) {
|
|
173
|
-
const schema = (0, types_1.
|
|
171
|
+
const schema = (0, types_1.toJsonSchema)(param.schema);
|
|
174
172
|
if (param.description) {
|
|
175
173
|
schema.description = param.description;
|
|
176
174
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parameter-resolver.js","sourceRoot":"","sources":["../../src/parameter-resolver.ts"],"names":[],"mappings":";;;AAaA,mCAA2D;AAE3D;;GAEG;AACH,MAAa,iBAAiB;IAG5B,YAAY,cAA+B;QACzC,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI;YACtC,gBAAgB,EAAE,IAAI,CAAC,uBAAuB;SAC/C,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,uBAAuB,CAC7B,SAAiB,EACjB,QAA2B,EAC3B,KAAa;QAEb,MAAM,cAAc,GAAG;YACrB,IAAI,EAAE,MAAM;YACZ,KAAK,EAAE,OAAO;YACd,MAAM,EAAE,QAAQ;YAChB,MAAM,EAAE,QAAQ;YAChB,IAAI,EAAE,MAAM;SACb,CAAC,QAAQ,CAAC,CAAC;QAEZ,OAAO,GAAG,cAAc,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG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CAAC,CAAC,aAAa,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;gBAC3G,MAAM,GAAG;oBACP,IAAI,EAAE,QAAQ;oBACd,WAAW;iBACZ,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,qBAAqB;gBACrB,SAAS;YACX,CAAC;YAED,yBAAyB;YACzB,MAAM,CAAC,IAAI,CAAC;gBACV,QAAQ;gBACR,IAAI,EAAE,aAAa;gBACnB,GAAG,EAAE,SAAS;gBACd,QAAQ,EAAE,IAAI;gBACd,QAAQ,EAAE,YAAY;aACvB,CAAC,CAAC;YAEH,sDAAsD;YACtD,IAAI,cAAc,EAAE,CAAC;gBACnB,UAAU,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;gBAC9B,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC1B,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA9WD,8CA8WC","sourcesContent":["import type { JSONSchema7 } from 'json-schema';\nimport type {\n ParameterMapper,\n ParameterObject,\n RequestBodyObject,\n NamingStrategy,\n ParameterLocation,\n SchemaObject,\n ReferenceObject,\n SecurityRequirement,\n SecurityParameterInfo,\n SecuritySchemeObject,\n} from './types';\nimport { toJSONSchema7, isReferenceObject } from './types';\n\n/**\n * Resolves parameters and handles naming conflicts\n */\nexport class ParameterResolver {\n private namingStrategy: NamingStrategy;\n\n constructor(namingStrategy?: NamingStrategy) {\n this.namingStrategy = namingStrategy ?? {\n conflictResolver: this.defaultConflictResolver,\n };\n }\n\n /**\n * Default conflict resolver: prefix with location\n */\n private defaultConflictResolver(\n paramName: string,\n location: ParameterLocation,\n index: number\n ): string {\n const locationPrefix = {\n path: 'path',\n query: 'query',\n header: 'header',\n cookie: 'cookie',\n body: 'body',\n }[location];\n\n return `${locationPrefix}${paramName.charAt(0).toUpperCase()}${paramName.slice(1)}`;\n }\n\n /**\n * Resolve all parameters for an operation\n */\n resolve(\n operation: any,\n pathParameters?: ParameterObject[],\n securityRequirements?: SecurityRequirement[],\n includeSecurityInInput?: boolean\n ): {\n inputSchema: JSONSchema7;\n mapper: ParameterMapper[];\n } {\n const allParameters: ParameterObject[] = [\n ...(pathParameters ?? []),\n ...(operation.parameters ?? []),\n ];\n\n const requestBody = operation.requestBody as RequestBodyObject | undefined;\n\n // Collect all parameter names and detect conflicts\n const parametersByName = new Map<string, ParameterInfo[]>();\n\n // Process standard parameters\n allParameters.forEach((param) => {\n const info: ParameterInfo = {\n name: param.name,\n location: param.in as ParameterLocation,\n required: param.required ?? (param.in === 'path'),\n schema: param.schema ?? { type: 'string' },\n description: param.description,\n style: param.style,\n explode: param.explode,\n allowReserved: param.allowReserved,\n deprecated: param.deprecated,\n };\n\n if (!parametersByName.has(param.name)) {\n parametersByName.set(param.name, []);\n }\n parametersByName.get(param.name)!.push(info);\n });\n\n // Process request body\n if (requestBody?.content) {\n const contentType = this.selectContentType(requestBody.content);\n const mediaType = requestBody.content[contentType];\n\n if (mediaType?.schema) {\n this.extractBodyParameters(\n mediaType.schema,\n parametersByName,\n requestBody.required ?? false,\n contentType\n );\n }\n }\n\n // Resolve conflicts and build schema + mapper\n const properties: Record<string, JSONSchema7> = {};\n const required: string[] = [];\n const mapper: ParameterMapper[] = [];\n\n for (const [originalName, params] of parametersByName.entries()) {\n if (params.length === 1) {\n // No conflict\n const param = params[0];\n const inputKey = originalName;\n\n properties[inputKey] = this.buildParameterSchema(param);\n if (param.required) {\n required.push(inputKey);\n }\n\n mapper.push({\n inputKey,\n type: param.location,\n key: originalName,\n required: param.required,\n style: param.style,\n explode: param.explode,\n serialization: param.serialization,\n });\n } else {\n // Conflict - need to resolve\n params.forEach((param, index) => {\n const inputKey = this.namingStrategy.conflictResolver(\n originalName,\n param.location,\n index\n );\n\n properties[inputKey] = this.buildParameterSchema(param);\n if (param.required) {\n required.push(inputKey);\n }\n\n mapper.push({\n inputKey,\n type: param.location,\n key: originalName,\n required: param.required,\n style: param.style,\n explode: param.explode,\n serialization: param.serialization,\n });\n });\n }\n }\n\n // Process security requirements\n if (securityRequirements && securityRequirements.length > 0) {\n this.processSecurityRequirements(\n securityRequirements,\n properties,\n required,\n mapper,\n includeSecurityInInput ?? false\n );\n }\n\n const inputSchema: JSONSchema7 = {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n additionalProperties: false,\n };\n\n return { inputSchema, mapper };\n }\n\n /**\n * Extract parameters from request body schema\n */\n private extractBodyParameters(\n schema: SchemaObject | ReferenceObject,\n parametersByName: Map<string, ParameterInfo[]>,\n required: boolean,\n contentType: string,\n prefix = ''\n ): void {\n if (!schema || typeof schema !== 'object') return;\n\n // Convert to JSONSchema7 for processing\n const jsonSchema = toJSONSchema7(schema);\n\n // Handle object schemas\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const requiredFields = new Set(jsonSchema.required ?? []);\n\n for (const [propName, propSchema] of Object.entries(jsonSchema.properties)) {\n const fullName = prefix ? `${prefix}.${propName}` : propName;\n const isRequired = required && requiredFields.has(propName);\n\n if (typeof propSchema === 'object') {\n const info: ParameterInfo = {\n name: fullName,\n location: 'body',\n required: isRequired,\n schema: propSchema as JSONSchema7,\n description: (propSchema as any).description,\n serialization: {\n contentType,\n },\n };\n\n if (!parametersByName.has(fullName)) {\n parametersByName.set(fullName, []);\n }\n parametersByName.get(fullName)!.push(info);\n }\n }\n } else {\n // For non-object bodies (arrays, primitives), treat as single parameter\n const bodyParamName = prefix || 'body';\n const info: ParameterInfo = {\n name: bodyParamName,\n location: 'body',\n required,\n schema,\n serialization: {\n contentType,\n },\n };\n\n if (!parametersByName.has(bodyParamName)) {\n parametersByName.set(bodyParamName, []);\n }\n parametersByName.get(bodyParamName)!.push(info);\n }\n }\n\n /**\n * Build JSON Schema for a parameter\n */\n private buildParameterSchema(param: ParameterInfo): JSONSchema7 {\n const schema: JSONSchema7 = toJSONSchema7(param.schema as any);\n\n if (param.description) {\n schema.description = param.description;\n }\n\n if (param.deprecated) {\n schema['deprecated'] = true;\n }\n\n // Add parameter metadata\n (schema as any)['x-parameter-location'] = param.location;\n if (param.style) {\n (schema as any)['x-parameter-style'] = param.style;\n }\n if (param.explode !== undefined) {\n (schema as any)['x-parameter-explode'] = param.explode;\n }\n\n return schema;\n }\n\n /**\n * Select the most appropriate content type\n */\n private selectContentType(content: Record<string, any>): string {\n // Preference order\n const preferences = [\n 'application/json',\n 'application/x-www-form-urlencoded',\n 'multipart/form-data',\n 'application/xml',\n 'text/plain',\n ];\n\n for (const pref of preferences) {\n if (content[pref]) return pref;\n }\n\n // Fallback to first available\n const firstKey = Object.keys(content)[0];\n if (!firstKey) {\n throw new Error('No content type available in request body');\n }\n return firstKey;\n }\n\n /**\n * Process security requirements and add to mapper/inputSchema\n */\n private processSecurityRequirements(\n securityRequirements: SecurityRequirement[],\n properties: Record<string, JSONSchema7>,\n required: string[],\n mapper: ParameterMapper[],\n includeInInput: boolean\n ): void {\n for (const secReq of securityRequirements) {\n const { scheme, type, name: apiKeyName, in: apiKeyIn, scopes } = secReq;\n\n // Build security parameter info\n const securityInfo: SecurityParameterInfo = {\n scheme,\n type,\n scopes,\n };\n\n // Determine parameter details based on security type\n let inputKey: string;\n let headerKey: string;\n let paramLocation: ParameterLocation;\n let description: string;\n let schema: JSONSchema7;\n\n if (type === 'http') {\n // HTTP auth (bearer, basic, etc.)\n inputKey = scheme;\n headerKey = 'Authorization';\n paramLocation = 'header';\n\n const httpScheme = 'httpScheme' in secReq && secReq.httpScheme ? secReq.httpScheme : 'bearer';\n const bearerFormat = 'bearerFormat' in secReq ? secReq.bearerFormat : undefined;\n\n securityInfo.httpScheme = httpScheme;\n if (bearerFormat) {\n securityInfo.bearerFormat = bearerFormat;\n }\n\n description = `${httpScheme.charAt(0).toUpperCase()}${httpScheme.slice(1)} authentication token`;\n if (bearerFormat) {\n description += ` (${bearerFormat})`;\n }\n\n schema = {\n type: 'string',\n description,\n };\n } else if (type === 'apiKey') {\n // API Key auth\n inputKey = scheme;\n headerKey = apiKeyName || 'X-API-Key';\n paramLocation = (apiKeyIn || 'header') as ParameterLocation;\n\n securityInfo.apiKeyName = apiKeyName;\n securityInfo.apiKeyIn = apiKeyIn;\n\n description = `API key for ${scheme}`;\n schema = {\n type: 'string',\n description,\n };\n } else if (type === 'oauth2' || type === 'openIdConnect') {\n // OAuth2 / OpenID Connect\n inputKey = scheme;\n headerKey = 'Authorization';\n paramLocation = 'header';\n\n description = `OAuth2 access token${scopes && scopes.length > 0 ? ` (scopes: ${scopes.join(', ')})` : ''}`;\n schema = {\n type: 'string',\n description,\n };\n } else {\n // Unknown type, skip\n continue;\n }\n\n // Add to mapper (always)\n mapper.push({\n inputKey,\n type: paramLocation,\n key: headerKey,\n required: true,\n security: securityInfo,\n });\n\n // Add to inputSchema (only if includeInInput is true)\n if (includeInInput) {\n properties[inputKey] = schema;\n required.push(inputKey);\n }\n }\n }\n}\n\n/**\n * Internal parameter info structure\n */\ninterface ParameterInfo {\n name: string;\n location: ParameterLocation;\n required: boolean;\n schema: SchemaObject | ReferenceObject | JSONSchema7;\n description?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n deprecated?: boolean;\n serialization?: {\n contentType?: string;\n encoding?: Record<string, any>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"parameter-resolver.js","sourceRoot":"","sources":["../../src/parameter-resolver.ts"],"names":[],"mappings":";;;AAgBA,mCAA0D;AAE1D;;GAEG;AACH,MAAa,iBAAiB;IACpB,cAAc,CAAiB;IAEvC,YAAY,cAA+B;QACzC,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI;YACtC,gBAAgB,EAAE,IAAI,CAAC,uBAAuB;SAC/C,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,uBAAuB,CAAC,SAAiB,EAAE,QAA2B,EAAE,KAAa;QAC3F,MAAM,cAAc,GAAG;YACrB,IAAI,EAAE,MAAM;YACZ,KAAK,EAAE,OAAO;YACd,MAAM,EAAE,QAAQ;YAChB,MAAM,EAA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AC;gBAClB,SAAS,GAAG,eAAe,CAAC;gBAC5B,aAAa,GAAG,QAAQ,CAAC;gBAEzB,WAAW,GAAG,sBAAsB,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;gBAC3G,MAAM,GAAG;oBACP,IAAI,EAAE,QAAQ;oBACd,WAAW;iBACZ,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,qBAAqB;gBACrB,SAAS;YACX,CAAC;YAED,yBAAyB;YACzB,MAAM,CAAC,IAAI,CAAC;gBACV,QAAQ;gBACR,IAAI,EAAE,aAAa;gBACnB,GAAG,EAAE,SAAS;gBACd,QAAQ,EAAE,IAAI;gBACd,QAAQ,EAAE,YAAY;aACvB,CAAC,CAAC;YAEH,sDAAsD;YACtD,IAAI,cAAc,EAAE,CAAC;gBACnB,UAAU,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;gBAC9B,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC1B,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA9VD,8CA8VC","sourcesContent":["import type { JSONSchema } from 'zod/v4/core';\n\n/** JSON Schema type from Zod v4 */\ntype JsonSchema = JSONSchema.JSONSchema;\nimport type {\n ParameterMapper,\n ParameterObject,\n RequestBodyObject,\n NamingStrategy,\n ParameterLocation,\n SchemaObject,\n ReferenceObject,\n SecurityRequirement,\n SecurityParameterInfo,\n SecuritySchemeObject,\n} from './types';\nimport { toJsonSchema, isReferenceObject } from './types';\n\n/**\n * Resolves parameters and handles naming conflicts\n */\nexport class ParameterResolver {\n private namingStrategy: NamingStrategy;\n\n constructor(namingStrategy?: NamingStrategy) {\n this.namingStrategy = namingStrategy ?? {\n conflictResolver: this.defaultConflictResolver,\n };\n }\n\n /**\n * Default conflict resolver: prefix with location\n */\n private defaultConflictResolver(paramName: string, location: ParameterLocation, index: number): string {\n const locationPrefix = {\n path: 'path',\n query: 'query',\n header: 'header',\n cookie: 'cookie',\n body: 'body',\n }[location];\n\n return `${locationPrefix}${paramName.charAt(0).toUpperCase()}${paramName.slice(1)}`;\n }\n\n /**\n * Resolve all parameters for an operation\n */\n resolve(\n operation: any,\n pathParameters?: ParameterObject[],\n securityRequirements?: SecurityRequirement[],\n includeSecurityInInput?: boolean,\n ): {\n inputSchema: JsonSchema;\n mapper: ParameterMapper[];\n } {\n const allParameters: ParameterObject[] = [...(pathParameters ?? []), ...(operation.parameters ?? [])];\n\n const requestBody = operation.requestBody as RequestBodyObject | undefined;\n\n // Collect all parameter names and detect conflicts\n const parametersByName = new Map<string, ParameterInfo[]>();\n\n // Process standard parameters\n allParameters.forEach((param) => {\n const info: ParameterInfo = {\n name: param.name,\n location: param.in as ParameterLocation,\n required: param.required ?? param.in === 'path',\n schema: param.schema ?? { type: 'string' },\n description: param.description,\n style: param.style,\n explode: param.explode,\n allowReserved: param.allowReserved,\n deprecated: param.deprecated,\n };\n\n if (!parametersByName.has(param.name)) {\n parametersByName.set(param.name, []);\n }\n parametersByName.get(param.name)!.push(info);\n });\n\n // Process request body\n if (requestBody?.content) {\n const contentType = this.selectContentType(requestBody.content);\n const mediaType = requestBody.content[contentType];\n\n if (mediaType?.schema) {\n this.extractBodyParameters(mediaType.schema, parametersByName, requestBody.required ?? false, contentType);\n }\n }\n\n // Resolve conflicts and build schema + mapper\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n const mapper: ParameterMapper[] = [];\n\n for (const [originalName, params] of parametersByName.entries()) {\n if (params.length === 1) {\n // No conflict\n const param = params[0];\n const inputKey = originalName;\n\n properties[inputKey] = this.buildParameterSchema(param);\n if (param.required) {\n required.push(inputKey);\n }\n\n mapper.push({\n inputKey,\n type: param.location,\n key: originalName,\n required: param.required,\n style: param.style,\n explode: param.explode,\n serialization: param.serialization,\n });\n } else {\n // Conflict - need to resolve\n params.forEach((param, index) => {\n const inputKey = this.namingStrategy.conflictResolver(originalName, param.location, index);\n\n properties[inputKey] = this.buildParameterSchema(param);\n if (param.required) {\n required.push(inputKey);\n }\n\n mapper.push({\n inputKey,\n type: param.location,\n key: originalName,\n required: param.required,\n style: param.style,\n explode: param.explode,\n serialization: param.serialization,\n });\n });\n }\n }\n\n // Process security requirements\n if (securityRequirements && securityRequirements.length > 0) {\n this.processSecurityRequirements(\n securityRequirements,\n properties,\n required,\n mapper,\n includeSecurityInInput ?? false,\n );\n }\n\n const inputSchema: JsonSchema = {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n additionalProperties: false,\n };\n\n return { inputSchema, mapper };\n }\n\n /**\n * Extract parameters from request body schema\n */\n private extractBodyParameters(\n schema: SchemaObject | ReferenceObject,\n parametersByName: Map<string, ParameterInfo[]>,\n required: boolean,\n contentType: string,\n prefix = '',\n ): void {\n if (!schema || typeof schema !== 'object') return;\n\n // Convert to JsonSchema for processing\n const jsonSchema = toJsonSchema(schema);\n\n // Handle object schemas\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const requiredFields = new Set(jsonSchema.required ?? []);\n\n for (const [propName, propSchema] of Object.entries(jsonSchema.properties)) {\n const fullName = prefix ? `${prefix}.${propName}` : propName;\n const isRequired = required && requiredFields.has(propName);\n\n if (typeof propSchema === 'object') {\n const info: ParameterInfo = {\n name: fullName,\n location: 'body',\n required: isRequired,\n schema: propSchema as JsonSchema,\n description: (propSchema as any).description,\n serialization: {\n contentType,\n },\n };\n\n if (!parametersByName.has(fullName)) {\n parametersByName.set(fullName, []);\n }\n parametersByName.get(fullName)!.push(info);\n }\n }\n } else {\n // For non-object bodies (arrays, primitives), treat as single parameter\n const bodyParamName = prefix || 'body';\n const info: ParameterInfo = {\n name: bodyParamName,\n location: 'body',\n required,\n schema,\n serialization: {\n contentType,\n },\n };\n\n if (!parametersByName.has(bodyParamName)) {\n parametersByName.set(bodyParamName, []);\n }\n parametersByName.get(bodyParamName)!.push(info);\n }\n }\n\n /**\n * Build JSON Schema for a parameter\n */\n private buildParameterSchema(param: ParameterInfo): JsonSchema {\n const schema: JsonSchema = toJsonSchema(param.schema as any);\n\n if (param.description) {\n schema.description = param.description;\n }\n\n if (param.deprecated) {\n schema['deprecated'] = true;\n }\n\n // Add parameter metadata\n (schema as any)['x-parameter-location'] = param.location;\n if (param.style) {\n (schema as any)['x-parameter-style'] = param.style;\n }\n if (param.explode !== undefined) {\n (schema as any)['x-parameter-explode'] = param.explode;\n }\n\n return schema;\n }\n\n /**\n * Select the most appropriate content type\n */\n private selectContentType(content: Record<string, any>): string {\n // Preference order\n const preferences = [\n 'application/json',\n 'application/x-www-form-urlencoded',\n 'multipart/form-data',\n 'application/xml',\n 'text/plain',\n ];\n\n for (const pref of preferences) {\n if (content[pref]) return pref;\n }\n\n // Fallback to first available\n const firstKey = Object.keys(content)[0];\n if (!firstKey) {\n throw new Error('No content type available in request body');\n }\n return firstKey;\n }\n\n /**\n * Process security requirements and add to mapper/inputSchema\n */\n private processSecurityRequirements(\n securityRequirements: SecurityRequirement[],\n properties: Record<string, JsonSchema>,\n required: string[],\n mapper: ParameterMapper[],\n includeInInput: boolean,\n ): void {\n for (const secReq of securityRequirements) {\n const { scheme, type, name: apiKeyName, in: apiKeyIn, scopes } = secReq;\n\n // Build security parameter info\n const securityInfo: SecurityParameterInfo = {\n scheme,\n type,\n scopes,\n };\n\n // Determine parameter details based on security type\n let inputKey: string;\n let headerKey: string;\n let paramLocation: ParameterLocation;\n let description: string;\n let schema: JsonSchema;\n\n if (type === 'http') {\n // HTTP auth (bearer, basic, etc.)\n inputKey = scheme;\n headerKey = 'Authorization';\n paramLocation = 'header';\n\n const httpScheme = 'httpScheme' in secReq && secReq.httpScheme ? secReq.httpScheme : 'bearer';\n const bearerFormat = 'bearerFormat' in secReq ? secReq.bearerFormat : undefined;\n\n securityInfo.httpScheme = httpScheme;\n if (bearerFormat) {\n securityInfo.bearerFormat = bearerFormat;\n }\n\n description = `${httpScheme.charAt(0).toUpperCase()}${httpScheme.slice(1)} authentication token`;\n if (bearerFormat) {\n description += ` (${bearerFormat})`;\n }\n\n schema = {\n type: 'string',\n description,\n };\n } else if (type === 'apiKey') {\n // API Key auth\n inputKey = scheme;\n headerKey = apiKeyName || 'X-API-Key';\n paramLocation = (apiKeyIn || 'header') as ParameterLocation;\n\n securityInfo.apiKeyName = apiKeyName;\n securityInfo.apiKeyIn = apiKeyIn;\n\n description = `API key for ${scheme}`;\n schema = {\n type: 'string',\n description,\n };\n } else if (type === 'oauth2' || type === 'openIdConnect') {\n // OAuth2 / OpenID Connect\n inputKey = scheme;\n headerKey = 'Authorization';\n paramLocation = 'header';\n\n description = `OAuth2 access token${scopes && scopes.length > 0 ? ` (scopes: ${scopes.join(', ')})` : ''}`;\n schema = {\n type: 'string',\n description,\n };\n } else {\n // Unknown type, skip\n continue;\n }\n\n // Add to mapper (always)\n mapper.push({\n inputKey,\n type: paramLocation,\n key: headerKey,\n required: true,\n security: securityInfo,\n });\n\n // Add to inputSchema (only if includeInInput is true)\n if (includeInInput) {\n properties[inputKey] = schema;\n required.push(inputKey);\n }\n }\n }\n}\n\n/**\n * Internal parameter info structure\n */\ninterface ParameterInfo {\n name: string;\n location: ParameterLocation;\n required: boolean;\n schema: SchemaObject | ReferenceObject | JsonSchema;\n description?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n deprecated?: boolean;\n serialization?: {\n contentType?: string;\n encoding?: Record<string, any>;\n };\n}\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JSONSchema } from 'zod/v4/core';
|
|
2
|
+
/** JSON Schema type from Zod v4 */
|
|
3
|
+
type JsonSchema = JSONSchema.JSONSchema;
|
|
2
4
|
import type { GenerateOptions, ResponsesObject } from './types';
|
|
3
5
|
/**
|
|
4
6
|
* Builds output schemas from OpenAPI response definitions
|
|
@@ -10,7 +12,7 @@ export declare class ResponseBuilder {
|
|
|
10
12
|
/**
|
|
11
13
|
* Build output schema from responses
|
|
12
14
|
*/
|
|
13
|
-
build(responses?: ResponsesObject):
|
|
15
|
+
build(responses?: ResponsesObject): JsonSchema | undefined;
|
|
14
16
|
/**
|
|
15
17
|
* Extract schemas from all responses
|
|
16
18
|
*/
|
|
@@ -28,3 +30,4 @@ export declare class ResponseBuilder {
|
|
|
28
30
|
*/
|
|
29
31
|
private selectPreferredSchema;
|
|
30
32
|
}
|
|
33
|
+
export {};
|
package/src/response-builder.js
CHANGED
|
@@ -6,6 +6,8 @@ const types_1 = require("./types");
|
|
|
6
6
|
* Builds output schemas from OpenAPI response definitions
|
|
7
7
|
*/
|
|
8
8
|
class ResponseBuilder {
|
|
9
|
+
preferredStatusCodes;
|
|
10
|
+
includeAllResponses;
|
|
9
11
|
constructor(options = {}) {
|
|
10
12
|
this.preferredStatusCodes = options.preferredStatusCodes ?? [200, 201, 204, 202, 203, 206];
|
|
11
13
|
this.includeAllResponses = options.includeAllResponses ?? true;
|
|
@@ -90,7 +92,7 @@ class ResponseBuilder {
|
|
|
90
92
|
return null;
|
|
91
93
|
}
|
|
92
94
|
const schema = {
|
|
93
|
-
...(0, types_1.
|
|
95
|
+
...(0, types_1.toJsonSchema)(mediaType.schema),
|
|
94
96
|
'x-status-code': statusCode,
|
|
95
97
|
};
|
|
96
98
|
// Add description if not already present
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-builder.js","sourceRoot":"","sources":["../../src/response-builder.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"response-builder.js","sourceRoot":"","sources":["../../src/response-builder.ts"],"names":[],"mappings":";;;AAKA,mCAA0D;AAE1D;;GAEG;AACH,MAAa,eAAe;IAClB,oBAAoB,CAAW;IAC/B,mBAAmB,CAAU;IAErC,YAAY,UAA2B,EAAE;QACvC,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EA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UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,UAAU,GAAG,GAAG,CAAC,CAAC;QAC/E,IAAI,OAAO;YAAE,OAAO,OAAO,CAAC;QAE5B,qCAAqC;QACrC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,UAAU,GAAG,GAAG,CAAC,CAAC;QAChF,IAAI,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAE9B,8BAA8B;QAC9B,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;CACF;AA9JD,0CA8JC","sourcesContent":["import type { JSONSchema } from 'zod/v4/core';\n\n/** JSON Schema type from Zod v4 */\ntype JsonSchema = JSONSchema.JSONSchema;\nimport type { ResponseObject, GenerateOptions, ResponsesObject } from './types';\nimport { isReferenceObject, toJsonSchema } from './types';\n\n/**\n * Builds output schemas from OpenAPI response definitions\n */\nexport class ResponseBuilder {\n private preferredStatusCodes: number[];\n private includeAllResponses: boolean;\n\n constructor(options: GenerateOptions = {}) {\n this.preferredStatusCodes = options.preferredStatusCodes ?? [200, 201, 204, 202, 203, 206];\n this.includeAllResponses = options.includeAllResponses ?? true;\n }\n\n /**\n * Build output schema from responses\n */\n build(responses?: ResponsesObject): JsonSchema | undefined {\n if (!responses || Object.keys(responses).length === 0) {\n return undefined;\n }\n\n const schemas = this.extractResponseSchemas(responses);\n\n if (schemas.length === 0) {\n return undefined;\n }\n\n if (schemas.length === 1) {\n return schemas[0].schema;\n }\n\n if (this.includeAllResponses) {\n // Return union of all response schemas\n return {\n oneOf: schemas.map((s) => s.schema),\n description: 'Response can be one of multiple status codes',\n };\n } else {\n // Return only the preferred status code\n const preferred = this.selectPreferredSchema(schemas);\n return preferred.schema;\n }\n }\n\n /**\n * Extract schemas from all responses\n */\n private extractResponseSchemas(responses: ResponsesObject): ResponseSchema[] {\n const schemas: ResponseSchema[] = [];\n\n for (const [statusCode, response] of Object.entries(responses)) {\n // Skip if it's a reference object\n if (isReferenceObject(response)) continue;\n\n // Skip 'default' for now, we'll handle it separately\n if (statusCode === 'default') continue;\n\n const code = parseInt(statusCode, 10);\n if (isNaN(code)) continue;\n\n const schema = this.extractResponseSchema(response, code);\n if (schema) {\n schemas.push(schema);\n }\n }\n\n // Handle default response if no other schemas found\n if (schemas.length === 0 && responses['default']) {\n const defaultResponse = responses['default'];\n if (!isReferenceObject(defaultResponse)) {\n const schema = this.extractResponseSchema(defaultResponse, 0);\n if (schema) {\n schemas.push(schema);\n }\n }\n }\n\n return schemas;\n }\n\n /**\n * Extract schema from a single response\n */\n private extractResponseSchema(response: ResponseObject, statusCode: number): ResponseSchema | null {\n if (!response.content) {\n // Response with no content (e.g., 204 No Content)\n return {\n statusCode,\n schema: {\n type: 'null',\n description: response.description,\n 'x-status-code': statusCode,\n } as JsonSchema,\n };\n }\n\n const contentType = this.selectContentType(response.content);\n const mediaType = response.content[contentType];\n\n if (!mediaType?.schema) {\n return null;\n }\n\n const schema: JsonSchema & { 'x-status-code'?: number } = {\n ...toJsonSchema(mediaType.schema),\n 'x-status-code': statusCode,\n };\n\n // Add description if not already present\n if (!schema.description && response.description) {\n schema.description = response.description;\n }\n\n // Add content type metadata\n (schema as any)['x-content-type'] = contentType;\n\n return { statusCode, schema };\n }\n\n /**\n * Select the most appropriate content type\n */\n private selectContentType(content: Record<string, any>): string {\n // Preference order for responses\n const preferences = [\n 'application/json',\n 'application/hal+json',\n 'application/problem+json',\n 'application/xml',\n 'text/plain',\n 'text/html',\n ];\n\n for (const pref of preferences) {\n if (content[pref]) return pref;\n }\n\n // Fallback to first available\n return Object.keys(content)[0];\n }\n\n /**\n * Select the preferred schema based on status code preferences\n */\n private selectPreferredSchema(schemas: ResponseSchema[]): ResponseSchema {\n // First, try to find exact match in preferred list\n for (const preferredCode of this.preferredStatusCodes) {\n const found = schemas.find((s) => s.statusCode === preferredCode);\n if (found) return found;\n }\n\n // Next, try to find any 2xx response\n const success = schemas.find((s) => s.statusCode >= 200 && s.statusCode < 300);\n if (success) return success;\n\n // Next, try to find any 3xx response\n const redirect = schemas.find((s) => s.statusCode >= 300 && s.statusCode < 400);\n if (redirect) return redirect;\n\n // Fallback to first available\n return schemas[0];\n }\n}\n\n/**\n * Internal response schema structure\n */\ninterface ResponseSchema {\n statusCode: number;\n schema: JsonSchema;\n}\n"]}
|
package/src/schema-builder.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JSONSchema } from 'zod/v4/core';
|
|
2
|
+
/** JSON Schema type from Zod v4 */
|
|
3
|
+
type JsonSchema = JSONSchema.JSONSchema;
|
|
2
4
|
/**
|
|
3
5
|
* Helper class for building and manipulating JSON schemas
|
|
4
6
|
*/
|
|
@@ -6,66 +8,66 @@ export declare class SchemaBuilder {
|
|
|
6
8
|
/**
|
|
7
9
|
* Merge multiple schemas into one
|
|
8
10
|
*/
|
|
9
|
-
static merge(schemas:
|
|
11
|
+
static merge(schemas: JsonSchema[]): JsonSchema;
|
|
10
12
|
/**
|
|
11
13
|
* Create a union schema (oneOf)
|
|
12
14
|
*/
|
|
13
|
-
static union(schemas:
|
|
15
|
+
static union(schemas: JsonSchema[]): JsonSchema;
|
|
14
16
|
/**
|
|
15
17
|
* Deep clone a schema
|
|
16
18
|
*/
|
|
17
|
-
static clone(schema:
|
|
19
|
+
static clone(schema: JsonSchema): JsonSchema;
|
|
18
20
|
/**
|
|
19
21
|
* Remove $ref from schema (assumes already dereferenced)
|
|
20
22
|
*/
|
|
21
|
-
static removeRefs(schema:
|
|
23
|
+
static removeRefs(schema: JsonSchema): JsonSchema;
|
|
22
24
|
private static removeRefsRecursive;
|
|
23
25
|
/**
|
|
24
26
|
* Add description to schema
|
|
25
27
|
*/
|
|
26
|
-
static withDescription(schema:
|
|
28
|
+
static withDescription(schema: JsonSchema, description: string): JsonSchema;
|
|
27
29
|
/**
|
|
28
30
|
* Add example to schema
|
|
29
31
|
*/
|
|
30
|
-
static withExample(schema:
|
|
32
|
+
static withExample(schema: JsonSchema, example: any): JsonSchema;
|
|
31
33
|
/**
|
|
32
34
|
* Add default value to schema
|
|
33
35
|
*/
|
|
34
|
-
static withDefault(schema:
|
|
36
|
+
static withDefault(schema: JsonSchema, defaultValue: any): JsonSchema;
|
|
35
37
|
/**
|
|
36
38
|
* Add format to schema
|
|
37
39
|
*/
|
|
38
|
-
static withFormat(schema:
|
|
40
|
+
static withFormat(schema: JsonSchema, format: string): JsonSchema;
|
|
39
41
|
/**
|
|
40
42
|
* Add pattern to schema
|
|
41
43
|
*/
|
|
42
|
-
static withPattern(schema:
|
|
44
|
+
static withPattern(schema: JsonSchema, pattern: string): JsonSchema;
|
|
43
45
|
/**
|
|
44
46
|
* Add enum to schema
|
|
45
47
|
*/
|
|
46
|
-
static withEnum(schema:
|
|
48
|
+
static withEnum(schema: JsonSchema, values: any[]): JsonSchema;
|
|
47
49
|
/**
|
|
48
50
|
* Add minimum/maximum constraints
|
|
49
51
|
*/
|
|
50
|
-
static withRange(schema:
|
|
52
|
+
static withRange(schema: JsonSchema, min?: number, max?: number, options?: {
|
|
51
53
|
exclusive?: boolean;
|
|
52
|
-
}):
|
|
54
|
+
}): JsonSchema;
|
|
53
55
|
/**
|
|
54
56
|
* Add minLength/maxLength constraints
|
|
55
57
|
*/
|
|
56
|
-
static withLength(schema:
|
|
58
|
+
static withLength(schema: JsonSchema, minLength?: number, maxLength?: number): JsonSchema;
|
|
57
59
|
/**
|
|
58
60
|
* Create object schema
|
|
59
61
|
*/
|
|
60
|
-
static object(properties: Record<string,
|
|
62
|
+
static object(properties: Record<string, JsonSchema>, required?: string[]): JsonSchema;
|
|
61
63
|
/**
|
|
62
64
|
* Create array schema
|
|
63
65
|
*/
|
|
64
|
-
static array(items:
|
|
66
|
+
static array(items: JsonSchema, constraints?: {
|
|
65
67
|
minItems?: number;
|
|
66
68
|
maxItems?: number;
|
|
67
69
|
uniqueItems?: boolean;
|
|
68
|
-
}):
|
|
70
|
+
}): JsonSchema;
|
|
69
71
|
/**
|
|
70
72
|
* Create string schema
|
|
71
73
|
*/
|
|
@@ -75,7 +77,7 @@ export declare class SchemaBuilder {
|
|
|
75
77
|
pattern?: string;
|
|
76
78
|
format?: string;
|
|
77
79
|
enum?: string[];
|
|
78
|
-
}):
|
|
80
|
+
}): JsonSchema;
|
|
79
81
|
/**
|
|
80
82
|
* Create number schema
|
|
81
83
|
*/
|
|
@@ -85,7 +87,7 @@ export declare class SchemaBuilder {
|
|
|
85
87
|
exclusiveMinimum?: number;
|
|
86
88
|
exclusiveMaximum?: number;
|
|
87
89
|
multipleOf?: number;
|
|
88
|
-
}):
|
|
90
|
+
}): JsonSchema;
|
|
89
91
|
/**
|
|
90
92
|
* Create integer schema
|
|
91
93
|
*/
|
|
@@ -95,21 +97,22 @@ export declare class SchemaBuilder {
|
|
|
95
97
|
exclusiveMinimum?: number;
|
|
96
98
|
exclusiveMaximum?: number;
|
|
97
99
|
multipleOf?: number;
|
|
98
|
-
}):
|
|
100
|
+
}): JsonSchema;
|
|
99
101
|
/**
|
|
100
102
|
* Create boolean schema
|
|
101
103
|
*/
|
|
102
|
-
static boolean():
|
|
104
|
+
static boolean(): JsonSchema;
|
|
103
105
|
/**
|
|
104
106
|
* Create null schema
|
|
105
107
|
*/
|
|
106
|
-
static null():
|
|
108
|
+
static null(): JsonSchema;
|
|
107
109
|
/**
|
|
108
110
|
* Flatten nested oneOf/anyOf/allOf schemas
|
|
109
111
|
*/
|
|
110
|
-
static flatten(schema:
|
|
112
|
+
static flatten(schema: JsonSchema, maxDepth?: number): JsonSchema;
|
|
111
113
|
/**
|
|
112
114
|
* Simplify schema by removing unnecessary fields
|
|
113
115
|
*/
|
|
114
|
-
static simplify(schema:
|
|
116
|
+
static simplify(schema: JsonSchema): JsonSchema;
|
|
115
117
|
}
|
|
118
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-builder.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ACtB,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AApWD,sCAoWC","sourcesContent":["import type { JSONSchema7 } from 'json-schema';\n\n/**\n * Helper class for building and manipulating JSON schemas\n */\nexport class SchemaBuilder {\n /**\n * Merge multiple schemas into one\n */\n static merge(schemas: JSONSchema7[]): JSONSchema7 {\n if (schemas.length === 0) {\n return { type: 'object' };\n }\n\n if (schemas.length === 1) {\n return schemas[0];\n }\n\n const merged: JSONSchema7 = {\n type: 'object',\n properties: {},\n required: [],\n };\n\n const allRequired = new Set<string>();\n\n for (const schema of schemas) {\n if (schema.properties) {\n merged.properties = {\n ...merged.properties,\n ...schema.properties,\n };\n }\n\n if (schema.required) {\n schema.required.forEach((field) => allRequired.add(field));\n }\n }\n\n if (allRequired.size > 0) {\n merged.required = Array.from(allRequired);\n }\n\n return merged;\n }\n\n /**\n * Create a union schema (oneOf)\n */\n static union(schemas: JSONSchema7[]): JSONSchema7 {\n if (schemas.length === 0) {\n return {};\n }\n\n if (schemas.length === 1) {\n return schemas[0];\n }\n\n return {\n oneOf: schemas,\n };\n }\n\n /**\n * Deep clone a schema\n */\n static clone(schema: JSONSchema7): JSONSchema7 {\n return JSON.parse(JSON.stringify(schema));\n }\n\n /**\n * Remove $ref from schema (assumes already dereferenced)\n */\n static removeRefs(schema: JSONSchema7): JSONSchema7 {\n const cloned = this.clone(schema);\n this.removeRefsRecursive(cloned);\n return cloned;\n }\n\n private static removeRefsRecursive(obj: any): void {\n if (!obj || typeof obj !== 'object') return;\n\n if (obj.$ref) {\n delete obj.$ref;\n }\n\n for (const key in obj) {\n if (key in obj) {\n const value = obj[key];\n if (value && typeof value === 'object') {\n this.removeRefsRecursive(value);\n }\n }\n }\n }\n\n /**\n * Add description to schema\n */\n static withDescription(schema: JSONSchema7, description: string): JSONSchema7 {\n return {\n ...schema,\n description,\n };\n }\n\n /**\n * Add example to schema\n */\n static withExample(schema: JSONSchema7, example: any): JSONSchema7 {\n const existingExamples = Array.isArray(schema.examples) ? schema.examples : [];\n return {\n ...schema,\n examples: [...existingExamples, example],\n };\n }\n\n /**\n * Add default value to schema\n */\n static withDefault(schema: JSONSchema7, defaultValue: any): JSONSchema7 {\n return {\n ...schema,\n default: defaultValue,\n };\n }\n\n /**\n * Add format to schema\n */\n static withFormat(schema: JSONSchema7, format: string): JSONSchema7 {\n return {\n ...schema,\n format,\n };\n }\n\n /**\n * Add pattern to schema\n */\n static withPattern(schema: JSONSchema7, pattern: string): JSONSchema7 {\n return {\n ...schema,\n pattern,\n };\n }\n\n /**\n * Add enum to schema\n */\n static withEnum(schema: JSONSchema7, values: any[]): JSONSchema7 {\n return {\n ...schema,\n enum: values,\n };\n }\n\n /**\n * Add minimum/maximum constraints\n */\n static withRange(\n schema: JSONSchema7,\n min?: number,\n max?: number,\n options: { exclusive?: boolean } = {}\n ): JSONSchema7 {\n const result = { ...schema };\n\n if (min !== undefined) {\n if (options.exclusive) {\n result.exclusiveMinimum = min;\n } else {\n result.minimum = min;\n }\n }\n\n if (max !== undefined) {\n if (options.exclusive) {\n result.exclusiveMaximum = max;\n } else {\n result.maximum = max;\n }\n }\n\n return result;\n }\n\n /**\n * Add minLength/maxLength constraints\n */\n static withLength(schema: JSONSchema7, minLength?: number, maxLength?: number): JSONSchema7 {\n const result = { ...schema };\n\n if (minLength !== undefined) {\n result.minLength = minLength;\n }\n\n if (maxLength !== undefined) {\n result.maxLength = maxLength;\n }\n\n return result;\n }\n\n /**\n * Create object schema\n */\n static object(\n properties: Record<string, JSONSchema7>,\n required?: string[]\n ): JSONSchema7 {\n return {\n type: 'object',\n properties,\n ...(required && required.length > 0 && { required }),\n additionalProperties: false,\n };\n }\n\n /**\n * Create array schema\n */\n static array(items: JSONSchema7, constraints?: {\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n }): JSONSchema7 {\n return {\n type: 'array',\n items,\n ...constraints,\n };\n }\n\n /**\n * Create string schema\n */\n static string(constraints?: {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n enum?: string[];\n }): JSONSchema7 {\n return {\n type: 'string',\n ...constraints,\n };\n }\n\n /**\n * Create number schema\n */\n static number(constraints?: {\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n }): JSONSchema7 {\n return {\n type: 'number',\n ...constraints,\n };\n }\n\n /**\n * Create integer schema\n */\n static integer(constraints?: {\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n }): JSONSchema7 {\n return {\n type: 'integer',\n ...constraints,\n };\n }\n\n /**\n * Create boolean schema\n */\n static boolean(): JSONSchema7 {\n return {\n type: 'boolean',\n };\n }\n\n /**\n * Create null schema\n */\n static null(): JSONSchema7 {\n return {\n type: 'null',\n };\n }\n\n /**\n * Flatten nested oneOf/anyOf/allOf schemas\n */\n static flatten(schema: JSONSchema7, maxDepth = 10): JSONSchema7 {\n if (maxDepth <= 0) return schema;\n\n const cloned = this.clone(schema);\n\n if (cloned.oneOf) {\n const flattened = cloned.oneOf.flatMap((s) => {\n const sub = this.flatten(s as JSONSchema7, maxDepth - 1);\n return sub.oneOf ? sub.oneOf : [sub];\n });\n cloned.oneOf = flattened as JSONSchema7[];\n }\n\n if (cloned.anyOf) {\n const flattened = cloned.anyOf.flatMap((s) => {\n const sub = this.flatten(s as JSONSchema7, maxDepth - 1);\n return sub.anyOf ? sub.anyOf : [sub];\n });\n cloned.anyOf = flattened as JSONSchema7[];\n }\n\n if (cloned.allOf) {\n const flattened = cloned.allOf.flatMap((s) => {\n const sub = this.flatten(s as JSONSchema7, maxDepth - 1);\n return sub.allOf ? sub.allOf : [sub];\n });\n cloned.allOf = flattened as JSONSchema7[];\n }\n\n return cloned;\n }\n\n /**\n * Simplify schema by removing unnecessary fields\n */\n static simplify(schema: JSONSchema7): JSONSchema7 {\n const cloned = this.clone(schema);\n\n // Remove empty arrays/objects\n if (Array.isArray(cloned.required) && cloned.required.length === 0) {\n delete cloned.required;\n }\n\n if (cloned.properties && Object.keys(cloned.properties).length === 0) {\n delete cloned.properties;\n }\n\n if (Array.isArray(cloned.examples) && cloned.examples.length === 0) {\n delete cloned.examples;\n }\n\n // Remove title if it matches description\n if (cloned.title && cloned.description && cloned.title === cloned.description) {\n delete cloned.title;\n }\n\n return cloned;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"schema-builder.js","sourceRoot":"","sources":["../../src/schema-builder.ts"],"names":[],"mappings":";;;AAKA;;GAEG;AACH,MAAa,aAAa;IACxB;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,OAAqB;QAChC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QAC5B,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QAED,MAAM,MAAM,GAAe;YACzB,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,EAAE;SACb,CAAC;QAEF,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAC;QAEtC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;gBACtB,MAAM,CAAC,UAAU,GAAG;oBAClB,GAAG,MAAM,CAAC,UAAU;oBACpB,GAAG,MAAM,CAAC,UAAU;iBACrB,CAAC;YACJ,CAAC;YAED,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;gBACpB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;YAC7D,CAAC;QACH,CAAC;QAED,IAAI,WAAW,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YACzB,MAAM,CA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AAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACnE,OAAO,MAAM,CAAC,QAAQ,CAAC;QACzB,CAAC;QAED,yCAAyC;QACzC,IAAI,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;YAC9E,OAAO,MAAM,CAAC,KAAK,CAAC;QACtB,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA/VD,sCA+VC","sourcesContent":["import type { JSONSchema } from 'zod/v4/core';\n\n/** JSON Schema type from Zod v4 */\ntype JsonSchema = JSONSchema.JSONSchema;\n\n/**\n * Helper class for building and manipulating JSON schemas\n */\nexport class SchemaBuilder {\n /**\n * Merge multiple schemas into one\n */\n static merge(schemas: JsonSchema[]): JsonSchema {\n if (schemas.length === 0) {\n return { type: 'object' };\n }\n\n if (schemas.length === 1) {\n return schemas[0];\n }\n\n const merged: JsonSchema = {\n type: 'object',\n properties: {},\n required: [],\n };\n\n const allRequired = new Set<string>();\n\n for (const schema of schemas) {\n if (schema.properties) {\n merged.properties = {\n ...merged.properties,\n ...schema.properties,\n };\n }\n\n if (schema.required) {\n schema.required.forEach((field) => allRequired.add(field));\n }\n }\n\n if (allRequired.size > 0) {\n merged.required = Array.from(allRequired);\n }\n\n return merged;\n }\n\n /**\n * Create a union schema (oneOf)\n */\n static union(schemas: JsonSchema[]): JsonSchema {\n if (schemas.length === 0) {\n return {};\n }\n\n if (schemas.length === 1) {\n return schemas[0];\n }\n\n return {\n oneOf: schemas,\n };\n }\n\n /**\n * Deep clone a schema\n */\n static clone(schema: JsonSchema): JsonSchema {\n return JSON.parse(JSON.stringify(schema));\n }\n\n /**\n * Remove $ref from schema (assumes already dereferenced)\n */\n static removeRefs(schema: JsonSchema): JsonSchema {\n const cloned = this.clone(schema);\n this.removeRefsRecursive(cloned);\n return cloned;\n }\n\n private static removeRefsRecursive(obj: any): void {\n if (!obj || typeof obj !== 'object') return;\n\n if (obj.$ref) {\n delete obj.$ref;\n }\n\n for (const key in obj) {\n if (key in obj) {\n const value = obj[key];\n if (value && typeof value === 'object') {\n this.removeRefsRecursive(value);\n }\n }\n }\n }\n\n /**\n * Add description to schema\n */\n static withDescription(schema: JsonSchema, description: string): JsonSchema {\n return {\n ...schema,\n description,\n };\n }\n\n /**\n * Add example to schema\n */\n static withExample(schema: JsonSchema, example: any): JsonSchema {\n const existingExamples = Array.isArray(schema.examples) ? schema.examples : [];\n return {\n ...schema,\n examples: [...existingExamples, example],\n };\n }\n\n /**\n * Add default value to schema\n */\n static withDefault(schema: JsonSchema, defaultValue: any): JsonSchema {\n return {\n ...schema,\n default: defaultValue,\n };\n }\n\n /**\n * Add format to schema\n */\n static withFormat(schema: JsonSchema, format: string): JsonSchema {\n return {\n ...schema,\n format,\n };\n }\n\n /**\n * Add pattern to schema\n */\n static withPattern(schema: JsonSchema, pattern: string): JsonSchema {\n return {\n ...schema,\n pattern,\n };\n }\n\n /**\n * Add enum to schema\n */\n static withEnum(schema: JsonSchema, values: any[]): JsonSchema {\n return {\n ...schema,\n enum: values,\n };\n }\n\n /**\n * Add minimum/maximum constraints\n */\n static withRange(schema: JsonSchema, min?: number, max?: number, options: { exclusive?: boolean } = {}): JsonSchema {\n const result = { ...schema };\n\n if (min !== undefined) {\n if (options.exclusive) {\n result.exclusiveMinimum = min;\n } else {\n result.minimum = min;\n }\n }\n\n if (max !== undefined) {\n if (options.exclusive) {\n result.exclusiveMaximum = max;\n } else {\n result.maximum = max;\n }\n }\n\n return result;\n }\n\n /**\n * Add minLength/maxLength constraints\n */\n static withLength(schema: JsonSchema, minLength?: number, maxLength?: number): JsonSchema {\n const result = { ...schema };\n\n if (minLength !== undefined) {\n result.minLength = minLength;\n }\n\n if (maxLength !== undefined) {\n result.maxLength = maxLength;\n }\n\n return result;\n }\n\n /**\n * Create object schema\n */\n static object(properties: Record<string, JsonSchema>, required?: string[]): JsonSchema {\n return {\n type: 'object',\n properties,\n ...(required && required.length > 0 && { required }),\n additionalProperties: false,\n };\n }\n\n /**\n * Create array schema\n */\n static array(\n items: JsonSchema,\n constraints?: {\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n },\n ): JsonSchema {\n return {\n type: 'array',\n items,\n ...constraints,\n };\n }\n\n /**\n * Create string schema\n */\n static string(constraints?: {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n enum?: string[];\n }): JsonSchema {\n return {\n type: 'string',\n ...constraints,\n };\n }\n\n /**\n * Create number schema\n */\n static number(constraints?: {\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n }): JsonSchema {\n return {\n type: 'number',\n ...constraints,\n };\n }\n\n /**\n * Create integer schema\n */\n static integer(constraints?: {\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n }): JsonSchema {\n return {\n type: 'integer',\n ...constraints,\n };\n }\n\n /**\n * Create boolean schema\n */\n static boolean(): JsonSchema {\n return {\n type: 'boolean',\n };\n }\n\n /**\n * Create null schema\n */\n static null(): JsonSchema {\n return {\n type: 'null',\n };\n }\n\n /**\n * Flatten nested oneOf/anyOf/allOf schemas\n */\n static flatten(schema: JsonSchema, maxDepth = 10): JsonSchema {\n if (maxDepth <= 0) return schema;\n\n const cloned = this.clone(schema);\n\n if (cloned.oneOf) {\n const flattened = cloned.oneOf.flatMap((s) => {\n const sub = this.flatten(s as JsonSchema, maxDepth - 1);\n return sub.oneOf ? sub.oneOf : [sub];\n });\n cloned.oneOf = flattened as JsonSchema[];\n }\n\n if (cloned.anyOf) {\n const flattened = cloned.anyOf.flatMap((s) => {\n const sub = this.flatten(s as JsonSchema, maxDepth - 1);\n return sub.anyOf ? sub.anyOf : [sub];\n });\n cloned.anyOf = flattened as JsonSchema[];\n }\n\n if (cloned.allOf) {\n const flattened = cloned.allOf.flatMap((s) => {\n const sub = this.flatten(s as JsonSchema, maxDepth - 1);\n return sub.allOf ? sub.allOf : [sub];\n });\n cloned.allOf = flattened as JsonSchema[];\n }\n\n return cloned;\n }\n\n /**\n * Simplify schema by removing unnecessary fields\n */\n static simplify(schema: JsonSchema): JsonSchema {\n const cloned = this.clone(schema);\n\n // Remove empty arrays/objects\n if (Array.isArray(cloned.required) && cloned.required.length === 0) {\n delete cloned.required;\n }\n\n if (cloned.properties && Object.keys(cloned.properties).length === 0) {\n delete cloned.properties;\n }\n\n if (Array.isArray(cloned.examples) && cloned.examples.length === 0) {\n delete cloned.examples;\n }\n\n // Remove title if it matches description\n if (cloned.title && cloned.description && cloned.title === cloned.description) {\n delete cloned.title;\n }\n\n return cloned;\n }\n}\n"]}
|
package/src/types.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JSONSchema } from 'zod/v4/core';
|
|
2
|
+
/** JSON Schema type from Zod v4 */
|
|
3
|
+
type JsonSchema = JSONSchema.JSONSchema;
|
|
2
4
|
import type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
|
|
3
5
|
/**
|
|
4
6
|
* OpenAPI specification version 3.0.x or 3.1.x
|
|
@@ -44,11 +46,11 @@ export type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;
|
|
|
44
46
|
*/
|
|
45
47
|
export declare function isReferenceObject(obj: any): obj is ReferenceObject;
|
|
46
48
|
/**
|
|
47
|
-
* Convert OpenAPI schema to
|
|
49
|
+
* Convert OpenAPI schema to JsonSchema
|
|
48
50
|
* Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4
|
|
49
51
|
* OpenAPI 3.1 uses JSON Schema Draft 2020-12
|
|
50
52
|
*/
|
|
51
|
-
export declare function
|
|
53
|
+
export declare function toJsonSchema(schema: SchemaObject | ReferenceObject): JsonSchema;
|
|
52
54
|
/**
|
|
53
55
|
* Main MCP Tool definition generated from OpenAPI
|
|
54
56
|
*/
|
|
@@ -65,12 +67,12 @@ export interface McpOpenAPITool {
|
|
|
65
67
|
* Combined input schema including all parameters
|
|
66
68
|
* (path, query, header, cookie, body)
|
|
67
69
|
*/
|
|
68
|
-
inputSchema:
|
|
70
|
+
inputSchema: JsonSchema;
|
|
69
71
|
/**
|
|
70
72
|
* Output schema based on response definitions
|
|
71
73
|
* Can be a union of multiple status codes
|
|
72
74
|
*/
|
|
73
|
-
outputSchema?:
|
|
75
|
+
outputSchema?: JsonSchema;
|
|
74
76
|
/**
|
|
75
77
|
* Mapping from input schema properties to actual request parameters
|
|
76
78
|
*/
|
|
@@ -185,6 +187,14 @@ export interface ToolMetadata {
|
|
|
185
187
|
* Operation ID from OpenAPI
|
|
186
188
|
*/
|
|
187
189
|
operationId?: string;
|
|
190
|
+
/**
|
|
191
|
+
* Operation summary from OpenAPI (short description)
|
|
192
|
+
*/
|
|
193
|
+
operationSummary?: string;
|
|
194
|
+
/**
|
|
195
|
+
* Operation description from OpenAPI (detailed description)
|
|
196
|
+
*/
|
|
197
|
+
operationDescription?: string;
|
|
188
198
|
/**
|
|
189
199
|
* Tags from OpenAPI
|
|
190
200
|
*/
|
|
@@ -209,6 +219,57 @@ export interface ToolMetadata {
|
|
|
209
219
|
* External documentation
|
|
210
220
|
*/
|
|
211
221
|
externalDocs?: ExternalDocumentationObject;
|
|
222
|
+
/**
|
|
223
|
+
* FrontMCP extension data from x-frontmcp in the OpenAPI operation.
|
|
224
|
+
* Contains annotations, cache config, codecall config, tags, etc.
|
|
225
|
+
*/
|
|
226
|
+
frontmcp?: FrontMcpExtensionData;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* FrontMCP extension data extracted from x-frontmcp in OpenAPI operations.
|
|
230
|
+
* This provides declarative configuration for tools directly in the OpenAPI spec.
|
|
231
|
+
*/
|
|
232
|
+
export interface FrontMcpExtensionData {
|
|
233
|
+
/**
|
|
234
|
+
* Tool annotations for AI behavior hints.
|
|
235
|
+
*/
|
|
236
|
+
annotations?: {
|
|
237
|
+
title?: string;
|
|
238
|
+
readOnlyHint?: boolean;
|
|
239
|
+
destructiveHint?: boolean;
|
|
240
|
+
idempotentHint?: boolean;
|
|
241
|
+
openWorldHint?: boolean;
|
|
242
|
+
};
|
|
243
|
+
/**
|
|
244
|
+
* Cache configuration for response caching.
|
|
245
|
+
*/
|
|
246
|
+
cache?: {
|
|
247
|
+
ttl?: number;
|
|
248
|
+
slideWindow?: boolean;
|
|
249
|
+
};
|
|
250
|
+
/**
|
|
251
|
+
* CodeCall-specific configuration.
|
|
252
|
+
*/
|
|
253
|
+
codecall?: {
|
|
254
|
+
enabledInCodeCall?: boolean;
|
|
255
|
+
visibleInListTools?: boolean;
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* Tags/labels for categorization.
|
|
259
|
+
*/
|
|
260
|
+
tags?: string[];
|
|
261
|
+
/**
|
|
262
|
+
* If true, hide tool from discovery.
|
|
263
|
+
*/
|
|
264
|
+
hideFromDiscovery?: boolean;
|
|
265
|
+
/**
|
|
266
|
+
* Usage examples.
|
|
267
|
+
*/
|
|
268
|
+
examples?: Array<{
|
|
269
|
+
description: string;
|
|
270
|
+
input: Record<string, unknown>;
|
|
271
|
+
output?: unknown;
|
|
272
|
+
}>;
|
|
212
273
|
}
|
|
213
274
|
/**
|
|
214
275
|
* Security requirement definition
|
|
@@ -432,3 +493,4 @@ export interface ValidationWarning {
|
|
|
432
493
|
*/
|
|
433
494
|
code?: string;
|
|
434
495
|
}
|
|
496
|
+
export {};
|
package/src/types.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.isReferenceObject = isReferenceObject;
|
|
4
|
-
exports.
|
|
4
|
+
exports.toJsonSchema = toJsonSchema;
|
|
5
5
|
/**
|
|
6
6
|
* Helper to check if an object is a ReferenceObject
|
|
7
7
|
*/
|
|
@@ -9,11 +9,11 @@ function isReferenceObject(obj) {
|
|
|
9
9
|
return obj && typeof obj === 'object' && '$ref' in obj;
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* Convert OpenAPI schema to
|
|
12
|
+
* Convert OpenAPI schema to JsonSchema
|
|
13
13
|
* Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4
|
|
14
14
|
* OpenAPI 3.1 uses JSON Schema Draft 2020-12
|
|
15
15
|
*/
|
|
16
|
-
function
|
|
16
|
+
function toJsonSchema(schema) {
|
|
17
17
|
if (isReferenceObject(schema)) {
|
|
18
18
|
return { $ref: schema.$ref };
|
|
19
19
|
}
|
|
@@ -67,32 +67,32 @@ function toJSONSchema7(schema) {
|
|
|
67
67
|
// No exclusiveMinimum, just minimum
|
|
68
68
|
result['minimum'] = minimum;
|
|
69
69
|
}
|
|
70
|
-
// Recursively convert nested schemas to ensure all nested schemas are valid
|
|
70
|
+
// Recursively convert nested schemas to ensure all nested schemas are valid JsonSchema
|
|
71
71
|
if (result['properties'] && typeof result['properties'] === 'object') {
|
|
72
72
|
const props = {};
|
|
73
73
|
for (const [key, value] of Object.entries(result['properties'])) {
|
|
74
|
-
props[key] =
|
|
74
|
+
props[key] = toJsonSchema(value);
|
|
75
75
|
}
|
|
76
76
|
result['properties'] = props;
|
|
77
77
|
}
|
|
78
78
|
if (result['items']) {
|
|
79
79
|
if (Array.isArray(result['items'])) {
|
|
80
|
-
result['items'] = result['items'].map(
|
|
80
|
+
result['items'] = result['items'].map(toJsonSchema);
|
|
81
81
|
}
|
|
82
82
|
else {
|
|
83
|
-
result['items'] =
|
|
83
|
+
result['items'] = toJsonSchema(result['items']);
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
86
|
if (result['additionalProperties'] && typeof result['additionalProperties'] === 'object') {
|
|
87
|
-
result['additionalProperties'] =
|
|
87
|
+
result['additionalProperties'] = toJsonSchema(result['additionalProperties']);
|
|
88
88
|
}
|
|
89
89
|
for (const key of ['allOf', 'anyOf', 'oneOf']) {
|
|
90
90
|
if (result[key] && Array.isArray(result[key])) {
|
|
91
|
-
result[key] = result[key].map(
|
|
91
|
+
result[key] = result[key].map(toJsonSchema);
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
if (result['not']) {
|
|
95
|
-
result['not'] =
|
|
95
|
+
result['not'] = toJsonSchema(result['not']);
|
|
96
96
|
}
|
|
97
97
|
return result;
|
|
98
98
|
}
|
package/src/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;AAsDA,8CAEC;AAOD,sCAqFC;AAjGD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,GAAQ;IACxC,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,CAAC;AACzD,CAAC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,MAAsC;IAClE,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAiB,CAAC;IAC9C,CAAC;IAED,+DAA+D;IAC/D,2DAA2D;IAC3D,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEjF,MAAM,MAAM,GAA4B,EAAE,GAAG,IAAI,EAAE,CAAC;IAEpD,qCAAqC;IACrC,IAAI,OAAO,gBAAgB,KAAK,SAAS,EAAE,CAAC;QAC1C,IAAI,gBAAgB,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC9C,gEAAgE;YAChE,MAAM,CAAC,kBAAkB,CAAC,GAAG,OAAO,CAAC;QACvC,CAAC;aAAM,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YACjC,qDAAqD;YACrD,MAAM,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC;QAC9B,CAAC;QACD,qEAAqE;IACvE,CAAC;SAAM,IAAI,gBAAgB,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AAC;AAC/B,CAAC","sourcesContent":["import type { JSONSchema7 } from 'json-schema';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\n/**\n * OpenAPI specification version 3.0.x or 3.1.x\n */\nexport type OpenAPIVersion = '3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0';\n\n/**\n * Unified OpenAPI Document type (supports both 3.0 and 3.1)\n */\nexport type OpenAPIDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\n/**\n * HTTP methods supported by OpenAPI\n */\nexport type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * Parameter location types\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'body';\n\n/**\n * Authentication types supported\n */\nexport type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect' | 'mutualTLS';\n\n// Re-export OpenAPI types for convenience\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type ResponsesObject = OpenAPIV3.ResponsesObject | OpenAPIV3_1.ResponsesObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type HeaderObject = OpenAPIV3.HeaderObject | OpenAPIV3_1.HeaderObject;\nexport type ExampleObject = OpenAPIV3.ExampleObject | OpenAPIV3_1.ExampleObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type PathsObject = OpenAPIV3.PathsObject | OpenAPIV3_1.PathsObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\nexport type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject | OpenAPIV3_1.SecuritySchemeObject;\nexport type ReferenceObject = OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;\nexport type TagObject = OpenAPIV3.TagObject | OpenAPIV3_1.TagObject;\nexport type ExternalDocumentationObject =\n | OpenAPIV3.ExternalDocumentationObject\n | OpenAPIV3_1.ExternalDocumentationObject;\nexport type ServerVariableObject = OpenAPIV3.ServerVariableObject | OpenAPIV3_1.ServerVariableObject;\nexport type EncodingObject = OpenAPIV3.EncodingObject | OpenAPIV3_1.EncodingObject;\nexport type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject | OpenAPIV3_1.SecurityRequirementObject;\nexport type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;\n\n/**\n * Helper to check if an object is a ReferenceObject\n */\nexport function isReferenceObject(obj: any): obj is ReferenceObject {\n return obj && typeof obj === 'object' && '$ref' in obj;\n}\n\n/**\n * Convert OpenAPI schema to JSONSchema7\n * Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4\n * OpenAPI 3.1 uses JSON Schema Draft 2020-12\n */\nexport function toJSONSchema7(schema: SchemaObject | ReferenceObject): JSONSchema7 {\n if (isReferenceObject(schema)) {\n return { $ref: schema.$ref } as JSONSchema7;\n }\n\n // Handle OpenAPI 3.0 boolean exclusiveMaximum/exclusiveMinimum\n // by converting them to JSON Schema Draft 7 numeric format\n const { exclusiveMaximum, exclusiveMinimum, maximum, minimum, ...rest } = schema;\n\n const result: Record<string, unknown> = { ...rest };\n\n // Handle exclusiveMaximum conversion\n if (typeof exclusiveMaximum === 'boolean') {\n if (exclusiveMaximum && maximum !== undefined) {\n // true + maximum present -> convert to numeric exclusiveMaximum\n result['exclusiveMaximum'] = maximum;\n } else if (maximum !== undefined) {\n // false or true without maximum -> keep maximum only\n result['maximum'] = maximum;\n }\n // Boolean exclusiveMaximum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMaximum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMaximum'] = exclusiveMaximum;\n if (maximum !== undefined) {\n result['maximum'] = maximum;\n }\n } else if (maximum !== undefined) {\n // No exclusiveMaximum, just maximum\n result['maximum'] = maximum;\n }\n\n // Handle exclusiveMinimum conversion\n if (typeof exclusiveMinimum === 'boolean') {\n if (exclusiveMinimum && minimum !== undefined) {\n // true + minimum present -> convert to numeric exclusiveMinimum\n result['exclusiveMinimum'] = minimum;\n } else if (minimum !== undefined) {\n // false or true without minimum -> keep minimum only\n result['minimum'] = minimum;\n }\n // Boolean exclusiveMinimum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMinimum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMinimum'] = exclusiveMinimum;\n if (minimum !== undefined) {\n result['minimum'] = minimum;\n }\n } else if (minimum !== undefined) {\n // No exclusiveMinimum, just minimum\n result['minimum'] = minimum;\n }\n\n // Recursively convert nested schemas to ensure all nested schemas are valid JSONSchema7\n if (result['properties'] && typeof result['properties'] === 'object') {\n const props: Record<string, JSONSchema7> = {};\n for (const [key, value] of Object.entries(result['properties'] as Record<string, SchemaObject | ReferenceObject>)) {\n props[key] = toJSONSchema7(value);\n }\n result['properties'] = props;\n }\n\n if (result['items']) {\n if (Array.isArray(result['items'])) {\n result['items'] = (result['items'] as (SchemaObject | ReferenceObject)[]).map(toJSONSchema7);\n } else {\n result['items'] = toJSONSchema7(result['items'] as SchemaObject | ReferenceObject);\n }\n }\n\n if (result['additionalProperties'] && typeof result['additionalProperties'] === 'object') {\n result['additionalProperties'] = toJSONSchema7(result['additionalProperties'] as SchemaObject | ReferenceObject);\n }\n\n for (const key of ['allOf', 'anyOf', 'oneOf'] as const) {\n if (result[key] && Array.isArray(result[key])) {\n result[key] = (result[key] as (SchemaObject | ReferenceObject)[]).map(toJSONSchema7);\n }\n }\n\n if (result['not']) {\n result['not'] = toJSONSchema7(result['not'] as SchemaObject | ReferenceObject);\n }\n\n return result as JSONSchema7;\n}\n\n/**\n * Main MCP Tool definition generated from OpenAPI\n */\nexport interface McpOpenAPITool {\n /**\n * Unique tool name (from operationId or generated)\n */\n name: string;\n\n /**\n * Tool description (from operation summary/description)\n */\n description: string;\n\n /**\n * Combined input schema including all parameters\n * (path, query, header, cookie, body)\n */\n inputSchema: JSONSchema7;\n\n /**\n * Output schema based on response definitions\n * Can be a union of multiple status codes\n */\n outputSchema?: JSONSchema7;\n\n /**\n * Mapping from input schema properties to actual request parameters\n */\n mapper: ParameterMapper[];\n\n /**\n * Additional metadata about the tool\n */\n metadata: ToolMetadata;\n}\n\n/**\n * Maps input schema properties to their actual request locations\n */\nexport interface ParameterMapper {\n /**\n * Property name in the input schema\n */\n inputKey: string;\n\n /**\n * Where this parameter should be placed in the request\n */\n type: ParameterLocation;\n\n /**\n * Original parameter name (before conflict resolution)\n */\n key: string;\n\n /**\n * Whether this parameter is required\n */\n required?: boolean;\n\n /**\n * Parameter style (for path/query parameters)\n */\n style?: string;\n\n /**\n * Whether to explode arrays/objects\n */\n explode?: boolean;\n\n /**\n * Custom serialization info\n */\n serialization?: SerializationInfo;\n\n /**\n * Security scheme information (if this is an auth parameter)\n * This allows frameworks to resolve auth from context, env vars, etc.\n */\n security?: SecurityParameterInfo;\n}\n\n/**\n * Serialization information for complex parameters\n */\nexport interface SerializationInfo {\n /**\n * Content type for body parameters\n */\n contentType?: string;\n\n /**\n * Encoding rules\n */\n encoding?: Record<string, EncodingObject>;\n}\n\n/**\n * Security parameter information for framework-agnostic auth resolution\n */\nexport interface SecurityParameterInfo {\n /**\n * Security scheme name from OpenAPI (e.g., \"BearerAuth\")\n */\n scheme: string;\n\n /**\n * Security type (apiKey, http, oauth2, openIdConnect)\n */\n type: AuthType;\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Required OAuth2 scopes\n */\n scopes?: string[];\n\n /**\n * API key parameter name (for type: \"apiKey\")\n */\n apiKeyName?: string;\n\n /**\n * API key location (for type: \"apiKey\")\n */\n apiKeyIn?: 'query' | 'header' | 'cookie';\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Additional metadata about the generated tool\n */\nexport interface ToolMetadata {\n /**\n * Original OpenAPI path\n */\n path: string;\n\n /**\n * HTTP method\n */\n method: HTTPMethod;\n\n /**\n * Operation ID from OpenAPI\n */\n operationId?: string;\n\n /**\n * Tags from OpenAPI\n */\n tags?: string[];\n\n /**\n * Whether operation is deprecated\n */\n deprecated?: boolean;\n\n /**\n * Security requirements\n */\n security?: SecurityRequirement[];\n\n /**\n * Server information\n */\n servers?: ServerInfo[];\n\n /**\n * Response status codes included in output schema\n */\n responseStatusCodes?: number[];\n\n /**\n * External documentation\n */\n externalDocs?: ExternalDocumentationObject;\n}\n\n/**\n * Security requirement definition\n */\nexport interface SecurityRequirement {\n /**\n * Security scheme name\n */\n scheme: string;\n\n /**\n * Security type\n */\n type: AuthType;\n\n /**\n * Scopes required (for OAuth2/OpenID Connect)\n */\n scopes?: string[];\n\n /**\n * Parameter name (for API key)\n */\n name?: string;\n\n /**\n * Parameter location (for API key)\n */\n in?: 'query' | 'header' | 'cookie';\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Server information\n */\nexport interface ServerInfo {\n /**\n * Server URL\n */\n url: string;\n\n /**\n * Server description\n */\n description?: string;\n\n /**\n * Server variables\n */\n variables?: Record<string, ServerVariableObject>;\n}\n\n/**\n * Options for loading OpenAPI specifications\n */\nexport interface LoadOptions {\n /**\n * Whether to dereference $refs in schemas\n * @default true\n */\n dereference?: boolean;\n\n /**\n * Base URL for API requests\n * Overrides servers in OpenAPI spec\n */\n baseUrl?: string;\n\n /**\n * Custom HTTP headers for loading from URL\n */\n headers?: Record<string, string>;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Whether to validate the OpenAPI document\n * @default true\n */\n validate?: boolean;\n\n /**\n * Whether to follow HTTP redirects\n * @default true\n */\n followRedirects?: boolean;\n}\n\n/**\n * Operation object with additional context for filtering\n */\nexport type OperationWithContext = OperationObject & {\n path: string;\n method: string;\n};\n\n/**\n * Options for generating tools\n */\nexport interface GenerateOptions {\n /**\n * Include only these operation IDs\n */\n includeOperations?: string[];\n\n /**\n * Exclude these operation IDs\n */\n excludeOperations?: string[];\n\n /**\n * Custom filter function\n */\n filterFn?: (operation: OperationWithContext) => boolean;\n\n /**\n * Naming strategy for resolving conflicts\n */\n namingStrategy?: NamingStrategy;\n\n /**\n * Preferred response status codes (in order of preference)\n * @default [200, 201, 204, 202, 203, 206]\n */\n preferredStatusCodes?: number[];\n\n /**\n * Whether to include deprecated operations\n * @default false\n */\n includeDeprecated?: boolean;\n\n /**\n * Whether to include all response codes in output schema\n * If false, only preferred status code is used\n * @default true\n */\n includeAllResponses?: boolean;\n\n /**\n * Maximum depth for dereferencing schemas\n * @default 10\n */\n maxSchemaDepth?: number;\n\n /**\n * Whether to include examples in schemas\n * @default false\n */\n includeExamples?: boolean;\n\n /**\n * Whether to include security requirements as input parameters\n * If false, security is only in mapper (frameworks resolve from context/env/etc.)\n * If true, security is added to inputSchema as explicit parameters\n * @default false\n */\n includeSecurityInInput?: boolean;\n}\n\n/**\n * Naming strategy for resolving parameter conflicts\n */\nexport interface NamingStrategy {\n /**\n * Resolver function for parameter name conflicts\n * @param paramName - Original parameter name\n * @param location - Parameter location\n * @param index - Index of conflicting parameter (0-based)\n * @returns New parameter name\n */\n conflictResolver: (paramName: string, location: ParameterLocation, index: number) => string;\n\n /**\n * Function to generate tool names\n * @param path - OpenAPI path\n * @param method - HTTP method\n * @param operationId - Operation ID if available\n * @returns Tool name\n */\n toolNameGenerator?: (path: string, method: HTTPMethod, operationId?: string) => string;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /**\n * Whether the document is valid\n */\n valid: boolean;\n\n /**\n * Validation errors\n */\n errors?: ValidationErrorDetail[];\n\n /**\n * Validation warnings\n */\n warnings?: ValidationWarning[];\n}\n\n/**\n * Validation error detail\n */\nexport interface ValidationErrorDetail {\n /**\n * Error message\n */\n message: string;\n\n /**\n * Error path (JSON pointer)\n */\n path?: string;\n\n /**\n * Error code\n */\n code?: string;\n}\n\n/**\n * Validation warning\n */\nexport interface ValidationWarning {\n /**\n * Warning message\n */\n message: string;\n\n /**\n * Warning path (JSON pointer)\n */\n path?: string;\n\n /**\n * Warning code\n */\n code?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;AAyDA,8CAEC;AAOD,oCAqFC;AAjGD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,GAAQ;IACxC,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,CAAC;AACzD,CAAC;AAED;;;;GAIG;AACH,SAAgB,YAAY,CAAC,MAAsC;IACjE,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAgB,CAAC;IAC7C,CAAC;IAED,+DAA+D;IAC/D,2DAA2D;IAC3D,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEjF,MAAM,MAAM,GAA4B,EAAE,GAAG,IAAI,EAAE,CAAC;IAEpD,qCAAqC;IACrC,IAAI,OAAO,gBAAgB,KAAK,SAAS,EAAE,CAAC;QAC1C,IAAI,gBAAgB,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC9C,gEAAgE;YAChE,MAAM,CAAC,kBAAkB,CAAC,GAAG,OAAO,CAAC;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;IACH,CAAC;IAED,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QAClB,MAAM,CAAC,KAAK,CAAC,GAAG,YAAY,CAAC,MAAM,CAAC,KAAK,CAAmC,CAAC,CAAC;IAChF,CAAC;IAED,OAAO,MAAoB,CAAC;AAC9B,CAAC","sourcesContent":["import type { JSONSchema } from 'zod/v4/core';\n\n/** JSON Schema type from Zod v4 */\ntype JsonSchema = JSONSchema.JSONSchema;\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\n/**\n * OpenAPI specification version 3.0.x or 3.1.x\n */\nexport type OpenAPIVersion = '3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0';\n\n/**\n * Unified OpenAPI Document type (supports both 3.0 and 3.1)\n */\nexport type OpenAPIDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\n/**\n * HTTP methods supported by OpenAPI\n */\nexport type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * Parameter location types\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'body';\n\n/**\n * Authentication types supported\n */\nexport type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect' | 'mutualTLS';\n\n// Re-export OpenAPI types for convenience\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type ResponsesObject = OpenAPIV3.ResponsesObject | OpenAPIV3_1.ResponsesObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type HeaderObject = OpenAPIV3.HeaderObject | OpenAPIV3_1.HeaderObject;\nexport type ExampleObject = OpenAPIV3.ExampleObject | OpenAPIV3_1.ExampleObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type PathsObject = OpenAPIV3.PathsObject | OpenAPIV3_1.PathsObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\nexport type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject | OpenAPIV3_1.SecuritySchemeObject;\nexport type ReferenceObject = OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;\nexport type TagObject = OpenAPIV3.TagObject | OpenAPIV3_1.TagObject;\nexport type ExternalDocumentationObject =\n | OpenAPIV3.ExternalDocumentationObject\n | OpenAPIV3_1.ExternalDocumentationObject;\nexport type ServerVariableObject = OpenAPIV3.ServerVariableObject | OpenAPIV3_1.ServerVariableObject;\nexport type EncodingObject = OpenAPIV3.EncodingObject | OpenAPIV3_1.EncodingObject;\nexport type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject | OpenAPIV3_1.SecurityRequirementObject;\nexport type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;\n\n/**\n * Helper to check if an object is a ReferenceObject\n */\nexport function isReferenceObject(obj: any): obj is ReferenceObject {\n return obj && typeof obj === 'object' && '$ref' in obj;\n}\n\n/**\n * Convert OpenAPI schema to JsonSchema\n * Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4\n * OpenAPI 3.1 uses JSON Schema Draft 2020-12\n */\nexport function toJsonSchema(schema: SchemaObject | ReferenceObject): JsonSchema {\n if (isReferenceObject(schema)) {\n return { $ref: schema.$ref } as JsonSchema;\n }\n\n // Handle OpenAPI 3.0 boolean exclusiveMaximum/exclusiveMinimum\n // by converting them to JSON Schema Draft 7 numeric format\n const { exclusiveMaximum, exclusiveMinimum, maximum, minimum, ...rest } = schema;\n\n const result: Record<string, unknown> = { ...rest };\n\n // Handle exclusiveMaximum conversion\n if (typeof exclusiveMaximum === 'boolean') {\n if (exclusiveMaximum && maximum !== undefined) {\n // true + maximum present -> convert to numeric exclusiveMaximum\n result['exclusiveMaximum'] = maximum;\n } else if (maximum !== undefined) {\n // false or true without maximum -> keep maximum only\n result['maximum'] = maximum;\n }\n // Boolean exclusiveMaximum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMaximum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMaximum'] = exclusiveMaximum;\n if (maximum !== undefined) {\n result['maximum'] = maximum;\n }\n } else if (maximum !== undefined) {\n // No exclusiveMaximum, just maximum\n result['maximum'] = maximum;\n }\n\n // Handle exclusiveMinimum conversion\n if (typeof exclusiveMinimum === 'boolean') {\n if (exclusiveMinimum && minimum !== undefined) {\n // true + minimum present -> convert to numeric exclusiveMinimum\n result['exclusiveMinimum'] = minimum;\n } else if (minimum !== undefined) {\n // false or true without minimum -> keep minimum only\n result['minimum'] = minimum;\n }\n // Boolean exclusiveMinimum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMinimum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMinimum'] = exclusiveMinimum;\n if (minimum !== undefined) {\n result['minimum'] = minimum;\n }\n } else if (minimum !== undefined) {\n // No exclusiveMinimum, just minimum\n result['minimum'] = minimum;\n }\n\n // Recursively convert nested schemas to ensure all nested schemas are valid JsonSchema\n if (result['properties'] && typeof result['properties'] === 'object') {\n const props: Record<string, JsonSchema> = {};\n for (const [key, value] of Object.entries(result['properties'] as Record<string, SchemaObject | ReferenceObject>)) {\n props[key] = toJsonSchema(value);\n }\n result['properties'] = props;\n }\n\n if (result['items']) {\n if (Array.isArray(result['items'])) {\n result['items'] = (result['items'] as (SchemaObject | ReferenceObject)[]).map(toJsonSchema);\n } else {\n result['items'] = toJsonSchema(result['items'] as SchemaObject | ReferenceObject);\n }\n }\n\n if (result['additionalProperties'] && typeof result['additionalProperties'] === 'object') {\n result['additionalProperties'] = toJsonSchema(result['additionalProperties'] as SchemaObject | ReferenceObject);\n }\n\n for (const key of ['allOf', 'anyOf', 'oneOf'] as const) {\n if (result[key] && Array.isArray(result[key])) {\n result[key] = (result[key] as (SchemaObject | ReferenceObject)[]).map(toJsonSchema);\n }\n }\n\n if (result['not']) {\n result['not'] = toJsonSchema(result['not'] as SchemaObject | ReferenceObject);\n }\n\n return result as JsonSchema;\n}\n\n/**\n * Main MCP Tool definition generated from OpenAPI\n */\nexport interface McpOpenAPITool {\n /**\n * Unique tool name (from operationId or generated)\n */\n name: string;\n\n /**\n * Tool description (from operation summary/description)\n */\n description: string;\n\n /**\n * Combined input schema including all parameters\n * (path, query, header, cookie, body)\n */\n inputSchema: JsonSchema;\n\n /**\n * Output schema based on response definitions\n * Can be a union of multiple status codes\n */\n outputSchema?: JsonSchema;\n\n /**\n * Mapping from input schema properties to actual request parameters\n */\n mapper: ParameterMapper[];\n\n /**\n * Additional metadata about the tool\n */\n metadata: ToolMetadata;\n}\n\n/**\n * Maps input schema properties to their actual request locations\n */\nexport interface ParameterMapper {\n /**\n * Property name in the input schema\n */\n inputKey: string;\n\n /**\n * Where this parameter should be placed in the request\n */\n type: ParameterLocation;\n\n /**\n * Original parameter name (before conflict resolution)\n */\n key: string;\n\n /**\n * Whether this parameter is required\n */\n required?: boolean;\n\n /**\n * Parameter style (for path/query parameters)\n */\n style?: string;\n\n /**\n * Whether to explode arrays/objects\n */\n explode?: boolean;\n\n /**\n * Custom serialization info\n */\n serialization?: SerializationInfo;\n\n /**\n * Security scheme information (if this is an auth parameter)\n * This allows frameworks to resolve auth from context, env vars, etc.\n */\n security?: SecurityParameterInfo;\n}\n\n/**\n * Serialization information for complex parameters\n */\nexport interface SerializationInfo {\n /**\n * Content type for body parameters\n */\n contentType?: string;\n\n /**\n * Encoding rules\n */\n encoding?: Record<string, EncodingObject>;\n}\n\n/**\n * Security parameter information for framework-agnostic auth resolution\n */\nexport interface SecurityParameterInfo {\n /**\n * Security scheme name from OpenAPI (e.g., \"BearerAuth\")\n */\n scheme: string;\n\n /**\n * Security type (apiKey, http, oauth2, openIdConnect)\n */\n type: AuthType;\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Required OAuth2 scopes\n */\n scopes?: string[];\n\n /**\n * API key parameter name (for type: \"apiKey\")\n */\n apiKeyName?: string;\n\n /**\n * API key location (for type: \"apiKey\")\n */\n apiKeyIn?: 'query' | 'header' | 'cookie';\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Additional metadata about the generated tool\n */\nexport interface ToolMetadata {\n /**\n * Original OpenAPI path\n */\n path: string;\n\n /**\n * HTTP method\n */\n method: HTTPMethod;\n\n /**\n * Operation ID from OpenAPI\n */\n operationId?: string;\n\n /**\n * Operation summary from OpenAPI (short description)\n */\n operationSummary?: string;\n\n /**\n * Operation description from OpenAPI (detailed description)\n */\n operationDescription?: string;\n\n /**\n * Tags from OpenAPI\n */\n tags?: string[];\n\n /**\n * Whether operation is deprecated\n */\n deprecated?: boolean;\n\n /**\n * Security requirements\n */\n security?: SecurityRequirement[];\n\n /**\n * Server information\n */\n servers?: ServerInfo[];\n\n /**\n * Response status codes included in output schema\n */\n responseStatusCodes?: number[];\n\n /**\n * External documentation\n */\n externalDocs?: ExternalDocumentationObject;\n\n /**\n * FrontMCP extension data from x-frontmcp in the OpenAPI operation.\n * Contains annotations, cache config, codecall config, tags, etc.\n */\n frontmcp?: FrontMcpExtensionData;\n}\n\n/**\n * FrontMCP extension data extracted from x-frontmcp in OpenAPI operations.\n * This provides declarative configuration for tools directly in the OpenAPI spec.\n */\nexport interface FrontMcpExtensionData {\n /**\n * Tool annotations for AI behavior hints.\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n };\n\n /**\n * Cache configuration for response caching.\n */\n cache?: {\n ttl?: number;\n slideWindow?: boolean;\n };\n\n /**\n * CodeCall-specific configuration.\n */\n codecall?: {\n enabledInCodeCall?: boolean;\n visibleInListTools?: boolean;\n };\n\n /**\n * Tags/labels for categorization.\n */\n tags?: string[];\n\n /**\n * If true, hide tool from discovery.\n */\n hideFromDiscovery?: boolean;\n\n /**\n * Usage examples.\n */\n examples?: Array<{\n description: string;\n input: Record<string, unknown>;\n output?: unknown;\n }>;\n}\n\n/**\n * Security requirement definition\n */\nexport interface SecurityRequirement {\n /**\n * Security scheme name\n */\n scheme: string;\n\n /**\n * Security type\n */\n type: AuthType;\n\n /**\n * Scopes required (for OAuth2/OpenID Connect)\n */\n scopes?: string[];\n\n /**\n * Parameter name (for API key)\n */\n name?: string;\n\n /**\n * Parameter location (for API key)\n */\n in?: 'query' | 'header' | 'cookie';\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Server information\n */\nexport interface ServerInfo {\n /**\n * Server URL\n */\n url: string;\n\n /**\n * Server description\n */\n description?: string;\n\n /**\n * Server variables\n */\n variables?: Record<string, ServerVariableObject>;\n}\n\n/**\n * Options for loading OpenAPI specifications\n */\nexport interface LoadOptions {\n /**\n * Whether to dereference $refs in schemas\n * @default true\n */\n dereference?: boolean;\n\n /**\n * Base URL for API requests\n * Overrides servers in OpenAPI spec\n */\n baseUrl?: string;\n\n /**\n * Custom HTTP headers for loading from URL\n */\n headers?: Record<string, string>;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Whether to validate the OpenAPI document\n * @default true\n */\n validate?: boolean;\n\n /**\n * Whether to follow HTTP redirects\n * @default true\n */\n followRedirects?: boolean;\n}\n\n/**\n * Operation object with additional context for filtering\n */\nexport type OperationWithContext = OperationObject & {\n path: string;\n method: string;\n};\n\n/**\n * Options for generating tools\n */\nexport interface GenerateOptions {\n /**\n * Include only these operation IDs\n */\n includeOperations?: string[];\n\n /**\n * Exclude these operation IDs\n */\n excludeOperations?: string[];\n\n /**\n * Custom filter function\n */\n filterFn?: (operation: OperationWithContext) => boolean;\n\n /**\n * Naming strategy for resolving conflicts\n */\n namingStrategy?: NamingStrategy;\n\n /**\n * Preferred response status codes (in order of preference)\n * @default [200, 201, 204, 202, 203, 206]\n */\n preferredStatusCodes?: number[];\n\n /**\n * Whether to include deprecated operations\n * @default false\n */\n includeDeprecated?: boolean;\n\n /**\n * Whether to include all response codes in output schema\n * If false, only preferred status code is used\n * @default true\n */\n includeAllResponses?: boolean;\n\n /**\n * Maximum depth for dereferencing schemas\n * @default 10\n */\n maxSchemaDepth?: number;\n\n /**\n * Whether to include examples in schemas\n * @default false\n */\n includeExamples?: boolean;\n\n /**\n * Whether to include security requirements as input parameters\n * If false, security is only in mapper (frameworks resolve from context/env/etc.)\n * If true, security is added to inputSchema as explicit parameters\n * @default false\n */\n includeSecurityInInput?: boolean;\n}\n\n/**\n * Naming strategy for resolving parameter conflicts\n */\nexport interface NamingStrategy {\n /**\n * Resolver function for parameter name conflicts\n * @param paramName - Original parameter name\n * @param location - Parameter location\n * @param index - Index of conflicting parameter (0-based)\n * @returns New parameter name\n */\n conflictResolver: (paramName: string, location: ParameterLocation, index: number) => string;\n\n /**\n * Function to generate tool names\n * @param path - OpenAPI path\n * @param method - HTTP method\n * @param operationId - Operation ID if available\n * @returns Tool name\n */\n toolNameGenerator?: (path: string, method: HTTPMethod, operationId?: string) => string;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /**\n * Whether the document is valid\n */\n valid: boolean;\n\n /**\n * Validation errors\n */\n errors?: ValidationErrorDetail[];\n\n /**\n * Validation warnings\n */\n warnings?: ValidationWarning[];\n}\n\n/**\n * Validation error detail\n */\nexport interface ValidationErrorDetail {\n /**\n * Error message\n */\n message: string;\n\n /**\n * Error path (JSON pointer)\n */\n path?: string;\n\n /**\n * Error code\n */\n code?: string;\n}\n\n/**\n * Validation warning\n */\nexport interface ValidationWarning {\n /**\n * Warning message\n */\n message: string;\n\n /**\n * Warning path (JSON pointer)\n */\n path?: string;\n\n /**\n * Warning code\n */\n code?: string;\n}\n"]}
|