mcp-from-openapi 0.0.1 → 1.0.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 ADDED
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ ## [1.0.0] - 2025-11-21
4
+
5
+ ### Features
6
+
7
+ - Production-ready library for converting OpenAPI specifications into MCP tool definitions
8
+ - OpenAPI 3.0+ and Swagger 2.0 support
9
+ - Comprehensive operation parsing:
10
+ - RESTful endpoint detection (GET, POST, PUT, PATCH, DELETE, etc.)
11
+ - Path parameter extraction and validation
12
+ - Query parameter handling
13
+ - Request body schema conversion
14
+ - Response schema parsing
15
+ - Advanced OpenAPI features:
16
+ - Reference resolution ($ref) across the entire specification
17
+ - Security scheme detection and configuration
18
+ - Parameter conflict resolution
19
+ - Operation naming controls and customization
20
+ - Request mapper generation:
21
+ - Automatic parameter mapping from MCP tool inputs to HTTP requests
22
+ - Type-safe parameter handling
23
+ - Support for different parameter locations (path, query, header, cookie)
24
+ - Request body transformation
25
+ - Tool metadata generation:
26
+ - Descriptive tool names from operation IDs
27
+ - Documentation from OpenAPI descriptions
28
+ - Schema validation rules
29
+ - Multiple input formats:
30
+ - JSON OpenAPI specifications
31
+ - YAML OpenAPI specifications
32
+ - Inline specification objects
33
+ - URL references to remote specifications
34
+ - Type-safe TypeScript implementation
35
+ - Node.js 18+ compatibility
36
+
37
+ ### Documentation
38
+
39
+ - Complete API reference
40
+ - OpenAPI conversion examples
41
+ - Integration guides for MCP servers
42
+ - Best practices for tool generation
43
+
44
+ This is the first official release of `mcp-from-openapi`, extracted from the FrontMCP framework to be published as a
45
+ standalone, reusable library for the community.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-from-openapi",
3
- "version": "0.0.1",
3
+ "version": "1.0.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",
@@ -26,6 +26,9 @@
26
26
  "url": "https://github.com/agentfront/frontmcp/issues"
27
27
  },
28
28
  "homepage": "https://github.com/agentfront/frontmcp/blob/main/libs/mcp-from-openapi/README.md",
29
+ "engines": {
30
+ "node": ">=18.0.0"
31
+ },
29
32
  "main": "./src/index.js",
30
33
  "types": "./src/index.d.ts",
31
34
  "exports": {
@@ -38,7 +41,7 @@
38
41
  },
39
42
  "dependencies": {
40
43
  "@apidevtools/json-schema-ref-parser": "^11.5.4",
41
- "json-schema": "^0.4.0",
44
+ "@types/json-schema": "^7.0.15",
42
45
  "openapi-types": "^12.1.3",
43
46
  "yaml": "^2.8.1"
44
47
  },
package/src/errors.js CHANGED
@@ -9,7 +9,10 @@ class OpenAPIToolError extends Error {
9
9
  super(message);
10
10
  this.name = this.constructor.name;
11
11
  this.context = context;
12
- Error.captureStackTrace(this, this.constructor);
12
+ // captureStackTrace is Node.js-specific, guard against non-Node environments
13
+ if (Error.captureStackTrace) {
14
+ Error.captureStackTrace(this, this.constructor);
15
+ }
13
16
  }
14
17
  }
15
18
  exports.OpenAPIToolError = OpenAPIToolError;
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;IAGzC,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;QACvB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;CACF;AATD,4CASC;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;IAGnD,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 Error.captureStackTrace(this, this.constructor);\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"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,gBAAiB,SAAQ,KAAK;IAGzC,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;IAGnD,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
@@ -43,10 +43,7 @@ class OpenAPIToolGenerator {
43
43
  });
44
44
  clearTimeout(timeout);
45
45
  if (!response.ok) {
46
- throw new errors_1.LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, {
47
- url,
48
- status: response.status,
49
- });
46
+ throw new errors_1.LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, { url, status: response.status });
50
47
  }
51
48
  const contentType = response.headers.get('content-type') || '';
52
49
  const text = await response.text();
@@ -216,7 +213,13 @@ class OpenAPIToolGenerator {
216
213
  if (pathItem.parameters) {
217
214
  pathParameters = pathItem.parameters.filter((p) => !(0, types_1.isReferenceObject)(p));
218
215
  }
219
- const { inputSchema, mapper } = parameterResolver.resolve(operation, pathParameters);
216
+ // Extract security requirements
217
+ let securityRequirements = undefined;
218
+ const securitySpec = operation.security ?? document.security;
219
+ if (securitySpec) {
220
+ securityRequirements = this.extractSecurityRequirements(securitySpec, document);
221
+ }
222
+ const { inputSchema, mapper } = parameterResolver.resolve(operation, pathParameters, securityRequirements, options.includeSecurityInInput);
220
223
  // Build response schema
221
224
  const responseBuilder = new response_builder_1.ResponseBuilder(options);
222
225
  const outputSchema = responseBuilder.build(operation.responses);
@@ -259,7 +262,7 @@ class OpenAPIToolGenerator {
259
262
  return options.filterFn({
260
263
  ...operation,
261
264
  path,
262
- method,
265
+ method
263
266
  });
264
267
  }
265
268
  return true;
@@ -308,11 +311,18 @@ class OpenAPIToolGenerator {
308
311
  else if (this.options.baseUrl) {
309
312
  metadata.servers = [{ url: this.options.baseUrl }];
310
313
  }
311
- // Extract response status codes
312
- if (outputSchema && outputSchema.oneOf) {
313
- metadata.responseStatusCodes = outputSchema.oneOf.map((schema) => schema['x-status-code']).filter(Boolean);
314
+ // Extract response status codes (preserve 0 for default responses)
315
+ if (outputSchema && Array.isArray(outputSchema.oneOf)) {
316
+ const codes = outputSchema.oneOf
317
+ .map((schema) => schema['x-status-code'])
318
+ .filter((code) => code !== undefined && code !== null);
319
+ if (codes.length > 0) {
320
+ metadata.responseStatusCodes = codes;
321
+ }
314
322
  }
315
- else if (outputSchema?.['x-status-code']) {
323
+ else if (outputSchema &&
324
+ outputSchema['x-status-code'] !== undefined &&
325
+ outputSchema['x-status-code'] !== null) {
316
326
  metadata.responseStatusCodes = [outputSchema['x-status-code']];
317
327
  }
318
328
  // External docs
@@ -332,15 +342,26 @@ class OpenAPIToolGenerator {
332
342
  const securityScheme = document.components.securitySchemes[scheme];
333
343
  // Skip if it's a reference object
334
344
  if ((0, types_1.isReferenceObject)(securityScheme)) {
335
- return { scheme, type: 'unknown', scopes };
345
+ return { scheme, type: 'http', scopes };
336
346
  }
337
- return {
347
+ const apiKeyIn = 'in' in securityScheme ? securityScheme.in : undefined;
348
+ const result = {
338
349
  scheme,
339
350
  type: securityScheme.type,
340
351
  scopes,
341
352
  name: 'name' in securityScheme ? securityScheme.name : undefined,
342
- in: 'in' in securityScheme ? securityScheme.in : undefined,
353
+ in: apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie')
354
+ ? apiKeyIn
355
+ : undefined,
343
356
  };
357
+ // Add HTTP-specific metadata
358
+ if (securityScheme.type === 'http') {
359
+ result.httpScheme = 'scheme' in securityScheme ? securityScheme.scheme : undefined;
360
+ result.bearerFormat = 'bearerFormat' in securityScheme ? securityScheme.bearerFormat : undefined;
361
+ }
362
+ // Add description if available
363
+ result.description = 'description' in securityScheme ? securityScheme.description : undefined;
364
+ return result;
344
365
  }));
345
366
  }
346
367
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../src/generator.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,wDAAkC;AAClC,mDAA6B;AAC7B,yGAA6D;AAU7D,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,G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'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} 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: 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(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 const { inputSchema, mapper } = parameterResolver.resolve(operation, pathParameters);\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(operation: any, path: string, method: string, options: GenerateOptions): 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(operation.security ?? document.security, document);\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\n if (outputSchema && outputSchema.oneOf) {\n metadata.responseStatusCodes = outputSchema.oneOf.map((schema: any) => schema['x-status-code']).filter(Boolean);\n } else if (outputSchema?.['x-status-code']) {\n metadata.responseStatusCodes = [outputSchema['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(security: Record<string, string[]>[], document: OpenAPIDocument): any[] {\n if (!security || !document.components?.securitySchemes) {\n return [];\n }\n\n return security.flatMap((req) =>\n Object.entries(req).map(([scheme, scopes]) => {\n const securityScheme = document.components!.securitySchemes![scheme];\n\n // Skip if it's a reference object\n if (isReferenceObject(securityScheme)) {\n return { scheme, type: 'unknown' as any, scopes };\n }\n\n return {\n scheme,\n type: securityScheme.type,\n scopes,\n name: 'name' in securityScheme ? securityScheme.name : undefined,\n in: 'in' in securityScheme ? securityScheme.in : undefined,\n };\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;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,GAA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tools/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"]}
package/src/index.d.ts CHANGED
@@ -3,6 +3,8 @@ export { SchemaBuilder } from './schema-builder';
3
3
  export { ParameterResolver } from './parameter-resolver';
4
4
  export { ResponseBuilder } from './response-builder';
5
5
  export { Validator } from './validator';
6
+ export { SecurityResolver, createSecurityContext } from './security-resolver';
6
7
  export { OpenAPIToolError, LoadError, ParseError, ValidationError, GenerationError, SchemaError, } from './errors';
7
- export type { McpOpenAPITool, ParameterMapper, ToolMetadata, SerializationInfo, SecurityRequirement, 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';
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';
9
+ export type { SecurityContext, ResolvedSecurity, DigestAuthCredentials, ClientCertificate, AWSCredentials, SignatureData, } from './security-resolver';
8
10
  export { isReferenceObject, toJSONSchema7 } 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.toJSONSchema7 = exports.isReferenceObject = exports.SchemaError = exports.GenerationError = exports.ValidationError = exports.ParseError = exports.LoadError = exports.OpenAPIToolError = exports.Validator = exports.ResponseBuilder = exports.ParameterResolver = exports.SchemaBuilder = exports.OpenAPIToolGenerator = void 0;
3
+ exports.toJSONSchema7 = 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; } });
@@ -12,6 +12,9 @@ var response_builder_1 = require("./response-builder");
12
12
  Object.defineProperty(exports, "ResponseBuilder", { enumerable: true, get: function () { return response_builder_1.ResponseBuilder; } });
13
13
  var validator_1 = require("./validator");
14
14
  Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return validator_1.Validator; } });
15
+ var security_resolver_1 = require("./security-resolver");
16
+ Object.defineProperty(exports, "SecurityResolver", { enumerable: true, get: function () { return security_resolver_1.SecurityResolver; } });
17
+ Object.defineProperty(exports, "createSecurityContext", { enumerable: true, get: function () { return security_resolver_1.createSecurityContext; } });
15
18
  // Error exports
16
19
  var errors_1 = require("./errors");
17
20
  Object.defineProperty(exports, "OpenAPIToolError", { enumerable: true, get: function () { return errors_1.OpenAPIToolError; } });
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;AAElB,gBAAgB;AAChB,mCAOkB;AANhB,0GAAA,gBAAgB,OAAA;AAChB,mGAAA,SAAS,OAAA;AACT,oGAAA,UAAU,OAAA;AACV,yGAAA,eAAe,OAAA;AACf,yGAAA,eAAe,OAAA;AACf,qGAAA,WAAW,OAAA;AAqDb,kBAAkB;AAClB,iCAA2D;AAAlD,0GAAA,iBAAiB,OAAA;AAAE,sGAAA,aAAa,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';\n\n// Error exports\nexport {\n OpenAPIToolError,\n LoadError,\n ParseError,\n ValidationError,\n GenerationError,\n SchemaError,\n} from './errors';\n\n// Type exports\nexport type {\n // Main MCP types\n McpOpenAPITool,\n ParameterMapper,\n ToolMetadata,\n SerializationInfo,\n SecurityRequirement,\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// Utility exports\nexport { isReferenceObject, toJSONSchema7 } from './types';\n"]}
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,mCAOkB;AANhB,0GAAA,gBAAgB,OAAA;AAChB,mGAAA,SAAS,OAAA;AACT,oGAAA,UAAU,OAAA;AACV,yGAAA,eAAe,OAAA;AACf,yGAAA,eAAe,OAAA;AACf,qGAAA,WAAW,OAAA;AAgEb,kBAAkB;AAClB,iCAA2D;AAAlD,0GAAA,iBAAiB,OAAA;AAAE,sGAAA,aAAa,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 {\n OpenAPIToolError,\n LoadError,\n ParseError,\n ValidationError,\n GenerationError,\n SchemaError,\n} from './errors';\n\n// Type exports\nexport type {\n // Main MCP types\n McpOpenAPITool,\n ParameterMapper,\n ToolMetadata,\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, toJSONSchema7 } from './types';\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { JSONSchema7 } from 'json-schema';
2
- import type { ParameterMapper, ParameterObject, NamingStrategy } from './types';
2
+ import type { ParameterMapper, ParameterObject, NamingStrategy, SecurityRequirement } from './types';
3
3
  /**
4
4
  * Resolves parameters and handles naming conflicts
5
5
  */
@@ -13,7 +13,7 @@ export declare class ParameterResolver {
13
13
  /**
14
14
  * Resolve all parameters for an operation
15
15
  */
16
- resolve(operation: any, pathParameters?: ParameterObject[]): {
16
+ resolve(operation: any, pathParameters?: ParameterObject[], securityRequirements?: SecurityRequirement[], includeSecurityInInput?: boolean): {
17
17
  inputSchema: JSONSchema7;
18
18
  mapper: ParameterMapper[];
19
19
  };
@@ -29,4 +29,8 @@ export declare class ParameterResolver {
29
29
  * Select the most appropriate content type
30
30
  */
31
31
  private selectContentType;
32
+ /**
33
+ * Process security requirements and add to mapper/inputSchema
34
+ */
35
+ private processSecurityRequirements;
32
36
  }
@@ -27,7 +27,7 @@ class ParameterResolver {
27
27
  /**
28
28
  * Resolve all parameters for an operation
29
29
  */
30
- resolve(operation, pathParameters) {
30
+ resolve(operation, pathParameters, securityRequirements, includeSecurityInInput) {
31
31
  const allParameters = [
32
32
  ...(pathParameters ?? []),
33
33
  ...(operation.parameters ?? []),
@@ -104,6 +104,10 @@ class ParameterResolver {
104
104
  });
105
105
  }
106
106
  }
107
+ // Process security requirements
108
+ if (securityRequirements && securityRequirements.length > 0) {
109
+ this.processSecurityRequirements(securityRequirements, properties, required, mapper, includeSecurityInInput ?? false);
110
+ }
107
111
  const inputSchema = {
108
112
  type: 'object',
109
113
  properties,
@@ -126,7 +130,7 @@ class ParameterResolver {
126
130
  for (const [propName, propSchema] of Object.entries(jsonSchema.properties)) {
127
131
  const fullName = prefix ? `${prefix}.${propName}` : propName;
128
132
  const isRequired = required && requiredFields.has(propName);
129
- if (typeof propSchema === 'object' && !('$ref' in propSchema)) {
133
+ if (typeof propSchema === 'object') {
130
134
  const info = {
131
135
  name: fullName,
132
136
  location: 'body',
@@ -206,6 +210,87 @@ class ParameterResolver {
206
210
  }
207
211
  return firstKey;
208
212
  }
213
+ /**
214
+ * Process security requirements and add to mapper/inputSchema
215
+ */
216
+ processSecurityRequirements(securityRequirements, properties, required, mapper, includeInInput) {
217
+ for (const secReq of securityRequirements) {
218
+ const { scheme, type, name: apiKeyName, in: apiKeyIn, scopes } = secReq;
219
+ // Build security parameter info
220
+ const securityInfo = {
221
+ scheme,
222
+ type,
223
+ scopes,
224
+ };
225
+ // Determine parameter details based on security type
226
+ let inputKey;
227
+ let headerKey;
228
+ let paramLocation;
229
+ let description;
230
+ let schema;
231
+ if (type === 'http') {
232
+ // HTTP auth (bearer, basic, etc.)
233
+ inputKey = scheme;
234
+ headerKey = 'Authorization';
235
+ paramLocation = 'header';
236
+ const httpScheme = 'httpScheme' in secReq && secReq.httpScheme ? secReq.httpScheme : 'bearer';
237
+ const bearerFormat = 'bearerFormat' in secReq ? secReq.bearerFormat : undefined;
238
+ securityInfo.httpScheme = httpScheme;
239
+ if (bearerFormat) {
240
+ securityInfo.bearerFormat = bearerFormat;
241
+ }
242
+ description = `${httpScheme.charAt(0).toUpperCase()}${httpScheme.slice(1)} authentication token`;
243
+ if (bearerFormat) {
244
+ description += ` (${bearerFormat})`;
245
+ }
246
+ schema = {
247
+ type: 'string',
248
+ description,
249
+ };
250
+ }
251
+ else if (type === 'apiKey') {
252
+ // API Key auth
253
+ inputKey = scheme;
254
+ headerKey = apiKeyName || 'X-API-Key';
255
+ paramLocation = (apiKeyIn || 'header');
256
+ securityInfo.apiKeyName = apiKeyName;
257
+ securityInfo.apiKeyIn = apiKeyIn;
258
+ description = `API key for ${scheme}`;
259
+ schema = {
260
+ type: 'string',
261
+ description,
262
+ };
263
+ }
264
+ else if (type === 'oauth2' || type === 'openIdConnect') {
265
+ // OAuth2 / OpenID Connect
266
+ inputKey = scheme;
267
+ headerKey = 'Authorization';
268
+ paramLocation = 'header';
269
+ description = `OAuth2 access token${scopes && scopes.length > 0 ? ` (scopes: ${scopes.join(', ')})` : ''}`;
270
+ schema = {
271
+ type: 'string',
272
+ description,
273
+ };
274
+ }
275
+ else {
276
+ // Unknown type, skip
277
+ continue;
278
+ }
279
+ // Add to mapper (always)
280
+ mapper.push({
281
+ inputKey,
282
+ type: paramLocation,
283
+ key: headerKey,
284
+ required: true,
285
+ security: securityInfo,
286
+ });
287
+ // Add to inputSchema (only if includeInInput is true)
288
+ if (includeInInput) {
289
+ properties[inputKey] = schema;
290
+ required.push(inputKey);
291
+ }
292
+ }
293
+ }
209
294
  }
210
295
  exports.ParameterResolver = ParameterResolver;
211
296
  //# sourceMappingURL=parameter-resolver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"parameter-resolver.js","sourceRoot":"","sources":["../../src/parameter-resolver.ts"],"names":[],"mappings":";;;AAUA,mCAAwC;AAExC;;GAEG;AACH,MAAa,iBAAiB;IAG5B,YAAY,cAA+B;QACzC,IAAI,CAAC,cAAc,GAAG,c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AAK,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YAC/B,MAAc,CAAC,qBAAqB,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC;QACzD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;OAEG;IACK,iBAAiB,CAAC,OAA4B;QACpD,mBAAmB;QACnB,MAAM,WAAW,GAAG;YAClB,kBAAkB;YAClB,mCAAmC;YACnC,qBAAqB;YACrB,iBAAiB;YACjB,YAAY;SACb,CAAC;QAEF,KAAK,MAAM,IAAI,IAAI,WAAW,EAAE,CAAC;YAC/B,IAAI,OAAO,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;QACjC,CAAC;QAED,8BAA8B;QAC9B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AAhQD,8CAgQC","sourcesContent":["import type { JSONSchema7 } from 'json-schema';\nimport type {\n ParameterMapper,\n ParameterObject,\n RequestBodyObject,\n NamingStrategy,\n ParameterLocation,\n SchemaObject,\n ReferenceObject,\n} from './types';\nimport { toJSONSchema7 } 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 ): {\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 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' && !('$ref' in propSchema)) {\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/**\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":";;;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,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACH,OAAO,CACL,SAAc,EACd,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C3G,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"]}
@@ -24,14 +24,6 @@ export declare class SchemaBuilder {
24
24
  * Add description to schema
25
25
  */
26
26
  static withDescription(schema: JSONSchema7, description: string): JSONSchema7;
27
- /**
28
- * Mark schema as required
29
- */
30
- static required(schema: JSONSchema7): JSONSchema7;
31
- /**
32
- * Mark schema as optional
33
- */
34
- static optional(schema: JSONSchema7): JSONSchema7;
35
27
  /**
36
28
  * Add example to schema
37
29
  */