mcp-from-openapi 2.1.0 → 2.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-from-openapi",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
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",
@@ -30,18 +30,27 @@
30
30
  "engines": {
31
31
  "node": ">=18.0.0"
32
32
  },
33
- "main": "./src/index.js",
34
- "types": "./src/index.d.ts",
33
+ "type": "commonjs",
34
+ "main": "./index.js",
35
+ "module": "./esm/index.mjs",
36
+ "types": "./index.d.ts",
37
+ "sideEffects": false,
35
38
  "exports": {
36
39
  "./package.json": "./package.json",
37
40
  ".": {
38
- "types": "./src/index.d.ts",
39
- "import": "./src/index.js",
40
- "default": "./src/index.js"
41
- }
41
+ "require": {
42
+ "types": "./index.d.ts",
43
+ "default": "./index.js"
44
+ },
45
+ "import": {
46
+ "types": "./index.d.ts",
47
+ "default": "./esm/index.mjs"
48
+ }
49
+ },
50
+ "./esm": null
42
51
  },
43
52
  "dependencies": {
44
- "@apidevtools/json-schema-ref-parser": "^11.5.4",
53
+ "@apidevtools/json-schema-ref-parser": "^11.9.3",
45
54
  "openapi-types": "^12.1.3",
46
55
  "yaml": "^2.8.1"
47
56
  },
@@ -52,6 +61,5 @@
52
61
  "@types/node": "^24.0.0",
53
62
  "typescript": "^5.0.0",
54
63
  "zod": "^4.0.0"
55
- },
56
- "type": "commonjs"
64
+ }
57
65
  }
package/src/errors.js DELETED
@@ -1,67 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SchemaError = exports.GenerationError = exports.ValidationError = exports.ParseError = exports.LoadError = exports.OpenAPIToolError = void 0;
4
- /**
5
- * Base error class for all library errors
6
- */
7
- class OpenAPIToolError extends Error {
8
- context;
9
- constructor(message, context) {
10
- super(message);
11
- this.name = this.constructor.name;
12
- this.context = context;
13
- // captureStackTrace is Node.js-specific, guard against non-Node environments
14
- if (Error.captureStackTrace) {
15
- Error.captureStackTrace(this, this.constructor);
16
- }
17
- }
18
- }
19
- exports.OpenAPIToolError = OpenAPIToolError;
20
- /**
21
- * Error thrown when loading an OpenAPI specification fails
22
- */
23
- class LoadError extends OpenAPIToolError {
24
- constructor(message, context) {
25
- super(message, context);
26
- }
27
- }
28
- exports.LoadError = LoadError;
29
- /**
30
- * Error thrown when parsing an OpenAPI specification fails
31
- */
32
- class ParseError extends OpenAPIToolError {
33
- constructor(message, context) {
34
- super(message, context);
35
- }
36
- }
37
- exports.ParseError = ParseError;
38
- /**
39
- * Error thrown when validating an OpenAPI specification fails
40
- */
41
- class ValidationError extends OpenAPIToolError {
42
- errors;
43
- constructor(message, context) {
44
- super(message, context);
45
- this.errors = context?.['errors'];
46
- }
47
- }
48
- exports.ValidationError = ValidationError;
49
- /**
50
- * Error thrown when generating a tool fails
51
- */
52
- class GenerationError extends OpenAPIToolError {
53
- constructor(message, context) {
54
- super(message, context);
55
- }
56
- }
57
- exports.GenerationError = GenerationError;
58
- /**
59
- * Error thrown when a schema is invalid
60
- */
61
- class SchemaError extends OpenAPIToolError {
62
- constructor(message, context) {
63
- super(message, context);
64
- }
65
- }
66
- exports.SchemaError = SchemaError;
67
- //# sourceMappingURL=errors.js.map
package/src/errors.js.map DELETED
@@ -1 +0,0 @@
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 DELETED
@@ -1,381 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpenAPIToolGenerator = void 0;
4
- const tslib_1 = require("tslib");
5
- const yaml = tslib_1.__importStar(require("yaml"));
6
- const fs = tslib_1.__importStar(require("fs/promises"));
7
- const path = tslib_1.__importStar(require("path"));
8
- const json_schema_ref_parser_1 = tslib_1.__importDefault(require("@apidevtools/json-schema-ref-parser"));
9
- const types_1 = require("./types");
10
- const parameter_resolver_1 = require("./parameter-resolver");
11
- const response_builder_1 = require("./response-builder");
12
- const validator_1 = require("./validator");
13
- const errors_1 = require("./errors");
14
- /**
15
- * Main class for generating MCP tools from OpenAPI specifications
16
- */
17
- class OpenAPIToolGenerator {
18
- document;
19
- dereferencedDocument;
20
- options;
21
- /**
22
- * Private constructor - use static factory methods to create instances
23
- */
24
- constructor(document, options = {}) {
25
- this.document = document;
26
- this.options = {
27
- dereference: options.dereference ?? true,
28
- baseUrl: options.baseUrl ?? '',
29
- headers: options.headers ?? {},
30
- timeout: options.timeout ?? 30000,
31
- validate: options.validate ?? true,
32
- followRedirects: options.followRedirects ?? true,
33
- };
34
- }
35
- /**
36
- * Create generator from a URL
37
- */
38
- static async fromURL(url, options = {}) {
39
- try {
40
- const controller = new AbortController();
41
- const timeout = setTimeout(() => controller.abort(), options.timeout ?? 30000);
42
- const response = await fetch(url, {
43
- headers: options.headers,
44
- signal: controller.signal,
45
- redirect: options.followRedirects ?? true ? 'follow' : 'manual',
46
- });
47
- clearTimeout(timeout);
48
- if (!response.ok) {
49
- throw new errors_1.LoadError(`Failed to fetch OpenAPI spec from URL: ${response.status} ${response.statusText}`, {
50
- url,
51
- status: response.status,
52
- });
53
- }
54
- const contentType = response.headers.get('content-type') || '';
55
- const text = await response.text();
56
- let document;
57
- if (contentType.includes('yaml') || contentType.includes('yml') || url.match(/\.ya?ml$/i)) {
58
- document = yaml.parse(text);
59
- }
60
- else {
61
- document = JSON.parse(text);
62
- }
63
- return new OpenAPIToolGenerator(document, options);
64
- }
65
- catch (error) {
66
- if (error instanceof errors_1.LoadError) {
67
- throw error;
68
- }
69
- const errorMessage = error instanceof Error ? error.message : String(error);
70
- throw new errors_1.LoadError(`Failed to load OpenAPI spec from URL: ${errorMessage}`, {
71
- url,
72
- originalError: error,
73
- });
74
- }
75
- }
76
- /**
77
- * Create generator from a file path
78
- */
79
- static async fromFile(filePath, options = {}) {
80
- try {
81
- const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
82
- const content = await fs.readFile(absolutePath, 'utf-8');
83
- const ext = path.extname(filePath).toLowerCase();
84
- let document;
85
- if (ext === '.yaml' || ext === '.yml') {
86
- document = yaml.parse(content);
87
- }
88
- else if (ext === '.json') {
89
- document = JSON.parse(content);
90
- }
91
- else {
92
- // Try to parse as JSON first, then YAML
93
- try {
94
- document = JSON.parse(content);
95
- }
96
- catch {
97
- document = yaml.parse(content);
98
- }
99
- }
100
- return new OpenAPIToolGenerator(document, options);
101
- }
102
- catch (error) {
103
- const errorMessage = error instanceof Error ? error.message : String(error);
104
- throw new errors_1.LoadError(`Failed to load OpenAPI spec from file: ${errorMessage}`, {
105
- filePath,
106
- originalError: error,
107
- });
108
- }
109
- }
110
- /**
111
- * Create generator from a YAML string
112
- */
113
- static async fromYAML(yamlString, options = {}) {
114
- try {
115
- const document = yaml.parse(yamlString);
116
- return new OpenAPIToolGenerator(document, options);
117
- }
118
- catch (error) {
119
- const errorMessage = error instanceof Error ? error.message : String(error);
120
- throw new errors_1.ParseError(`Failed to parse YAML: ${errorMessage}`, {
121
- originalError: error,
122
- });
123
- }
124
- }
125
- /**
126
- * Create generator from a JSON object
127
- */
128
- static async fromJSON(json, options = {}) {
129
- // Clone to avoid mutations
130
- const document = JSON.parse(JSON.stringify(json));
131
- return new OpenAPIToolGenerator(document, options);
132
- }
133
- /**
134
- * Get the OpenAPI document
135
- */
136
- getDocument() {
137
- return this.dereferencedDocument ?? this.document;
138
- }
139
- /**
140
- * Validate the OpenAPI document
141
- */
142
- async validate() {
143
- const validator = new validator_1.Validator();
144
- return validator.validate(this.document);
145
- }
146
- /**
147
- * Initialize the generator (dereference if needed)
148
- */
149
- async initialize() {
150
- if (this.options.validate) {
151
- const result = await this.validate();
152
- if (!result.valid) {
153
- throw new errors_1.ParseError('Invalid OpenAPI document', { errors: result.errors });
154
- }
155
- }
156
- if (this.options.dereference && !this.dereferencedDocument) {
157
- try {
158
- this.dereferencedDocument = (await json_schema_ref_parser_1.default.dereference(JSON.parse(JSON.stringify(this.document))));
159
- }
160
- catch (error) {
161
- const errorMessage = error instanceof Error ? error.message : String(error);
162
- throw new errors_1.ParseError(`Failed to dereference OpenAPI document: ${errorMessage}`, {
163
- originalError: error,
164
- });
165
- }
166
- }
167
- }
168
- /**
169
- * Generate all tools from the OpenAPI specification
170
- */
171
- async generateTools(options = {}) {
172
- await this.initialize();
173
- const document = this.getDocument();
174
- const tools = [];
175
- if (!document.paths) {
176
- return tools;
177
- }
178
- for (const [pathStr, pathItem] of Object.entries(document.paths)) {
179
- if (!pathItem || '$ref' in pathItem)
180
- continue;
181
- const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];
182
- for (const method of methods) {
183
- const operation = pathItem[method];
184
- if (!operation)
185
- continue;
186
- // Apply filters
187
- if (!this.shouldIncludeOperation(operation, pathStr, method, options)) {
188
- continue;
189
- }
190
- try {
191
- const tool = await this.generateTool(pathStr, method, options);
192
- tools.push(tool);
193
- }
194
- catch (error) {
195
- const errorMessage = error instanceof Error ? error.message : String(error);
196
- console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, errorMessage);
197
- }
198
- }
199
- }
200
- return tools;
201
- }
202
- /**
203
- * Generate a specific tool for a path and method
204
- */
205
- async generateTool(pathStr, method, options = {}) {
206
- await this.initialize();
207
- const document = this.getDocument();
208
- if (!document.paths) {
209
- throw new Error('No paths defined in OpenAPI document');
210
- }
211
- const pathItem = document.paths[pathStr];
212
- const operation = pathItem?.[method.toLowerCase()];
213
- if (!operation) {
214
- throw new Error(`Operation not found: ${method.toUpperCase()} ${pathStr}`);
215
- }
216
- // Resolve parameters
217
- const parameterResolver = new parameter_resolver_1.ParameterResolver(options.namingStrategy);
218
- // Filter out ReferenceObjects from parameters
219
- let pathParameters = undefined;
220
- if (pathItem.parameters) {
221
- pathParameters = pathItem.parameters.filter((p) => !(0, types_1.isReferenceObject)(p));
222
- }
223
- // Extract security requirements
224
- let securityRequirements = undefined;
225
- const securitySpec = operation.security ?? document.security;
226
- if (securitySpec) {
227
- securityRequirements = this.extractSecurityRequirements(securitySpec, document);
228
- }
229
- const { inputSchema, mapper } = parameterResolver.resolve(operation, pathParameters, securityRequirements, options.includeSecurityInInput);
230
- // Build response schema
231
- const responseBuilder = new response_builder_1.ResponseBuilder(options);
232
- const outputSchema = responseBuilder.build(operation.responses);
233
- // Generate tool name
234
- const name = this.generateToolName(pathStr, method, operation.operationId, options);
235
- // Generate description
236
- const description = operation.summary || operation.description || `${method.toUpperCase()} ${pathStr}`;
237
- // Extract metadata
238
- const metadata = this.extractMetadata(pathStr, method, operation, document, outputSchema);
239
- return {
240
- name,
241
- description,
242
- inputSchema,
243
- outputSchema,
244
- mapper,
245
- metadata,
246
- };
247
- }
248
- /**
249
- * Check if an operation should be included
250
- */
251
- shouldIncludeOperation(operation, path, method, options) {
252
- // Check deprecated
253
- if (operation.deprecated && !options.includeDeprecated) {
254
- return false;
255
- }
256
- // Check operation ID filters
257
- if (options.includeOperations && operation.operationId) {
258
- if (!options.includeOperations.includes(operation.operationId)) {
259
- return false;
260
- }
261
- }
262
- if (options.excludeOperations && operation.operationId) {
263
- if (options.excludeOperations.includes(operation.operationId)) {
264
- return false;
265
- }
266
- }
267
- // Custom filter
268
- if (options.filterFn) {
269
- return options.filterFn({
270
- ...operation,
271
- path,
272
- method,
273
- });
274
- }
275
- return true;
276
- }
277
- /**
278
- * Generate a tool name
279
- */
280
- generateToolName(path, method, operationId, options = {}) {
281
- if (options.namingStrategy?.toolNameGenerator) {
282
- return options.namingStrategy.toolNameGenerator(path, method, operationId);
283
- }
284
- if (operationId) {
285
- return operationId;
286
- }
287
- // Generate from path and method
288
- const sanitized = path
289
- .replace(/\{([^}]+)\}/g, 'By_$1')
290
- .replace(/[^a-zA-Z0-9_]/g, '_')
291
- .replace(/_+/g, '_')
292
- .replace(/^_|_$/g, '');
293
- return `${method}_${sanitized}`;
294
- }
295
- /**
296
- * Extract metadata from operation
297
- */
298
- extractMetadata(path, method, operation, document, outputSchema) {
299
- const metadata = {
300
- path,
301
- method,
302
- operationId: operation.operationId,
303
- operationSummary: operation.summary,
304
- operationDescription: operation.description,
305
- tags: operation.tags,
306
- deprecated: operation.deprecated,
307
- };
308
- // Extract security requirements
309
- if (operation.security || document.security) {
310
- metadata.security = this.extractSecurityRequirements((operation.security ?? document.security), document);
311
- }
312
- // Extract servers
313
- const servers = operation.servers ?? document.servers;
314
- if (servers) {
315
- metadata.servers = servers.map((server) => ({
316
- url: this.options.baseUrl || server.url,
317
- description: server.description,
318
- variables: server.variables,
319
- }));
320
- }
321
- else if (this.options.baseUrl) {
322
- metadata.servers = [{ url: this.options.baseUrl }];
323
- }
324
- // Extract response status codes (preserve 0 for default responses)
325
- const schemaObj = outputSchema;
326
- if (schemaObj && Array.isArray(schemaObj['oneOf'])) {
327
- const codes = schemaObj['oneOf']
328
- .map((schema) => schema['x-status-code'])
329
- .filter((code) => code !== undefined && code !== null);
330
- if (codes.length > 0) {
331
- metadata.responseStatusCodes = codes;
332
- }
333
- }
334
- else if (schemaObj && schemaObj['x-status-code'] !== undefined && schemaObj['x-status-code'] !== null) {
335
- metadata.responseStatusCodes = [schemaObj['x-status-code']];
336
- }
337
- // External docs
338
- if (operation.externalDocs) {
339
- metadata.externalDocs = operation.externalDocs;
340
- }
341
- // FrontMCP extension (x-frontmcp)
342
- const operationWithExt = operation;
343
- if (operationWithExt['x-frontmcp']) {
344
- metadata.frontmcp = operationWithExt['x-frontmcp'];
345
- }
346
- return metadata;
347
- }
348
- /**
349
- * Extract security requirements
350
- */
351
- extractSecurityRequirements(security, document) {
352
- if (!security || !document.components?.securitySchemes) {
353
- return [];
354
- }
355
- return security.flatMap((req) => Object.entries(req).map(([scheme, scopes]) => {
356
- const securityScheme = document.components.securitySchemes[scheme];
357
- // Skip if it's a reference object
358
- if ((0, types_1.isReferenceObject)(securityScheme)) {
359
- return { scheme, type: 'http', scopes };
360
- }
361
- const apiKeyIn = 'in' in securityScheme ? securityScheme.in : undefined;
362
- const result = {
363
- scheme,
364
- type: securityScheme.type,
365
- scopes,
366
- name: 'name' in securityScheme ? securityScheme.name : undefined,
367
- in: apiKeyIn && (apiKeyIn === 'query' || apiKeyIn === 'header' || apiKeyIn === 'cookie') ? apiKeyIn : undefined,
368
- };
369
- // Add HTTP-specific metadata
370
- if (securityScheme.type === 'http') {
371
- result.httpScheme = 'scheme' in securityScheme ? securityScheme.scheme : undefined;
372
- result.bearerFormat = 'bearerFormat' in securityScheme ? securityScheme.bearerFormat : undefined;
373
- }
374
- // Add description if available
375
- result.description = 'description' in securityScheme ? securityScheme.description : undefined;
376
- return result;
377
- }));
378
- }
379
- }
380
- exports.OpenAPIToolGenerator = OpenAPIToolGenerator;
381
- //# sourceMappingURL=generator.js.map
@@ -1 +0,0 @@
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,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;YAE/E,MAAM,QAAQ,GA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AAG,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.js DELETED
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
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
- // Main exports
5
- var generator_1 = require("./generator");
6
- Object.defineProperty(exports, "OpenAPIToolGenerator", { enumerable: true, get: function () { return generator_1.OpenAPIToolGenerator; } });
7
- var schema_builder_1 = require("./schema-builder");
8
- Object.defineProperty(exports, "SchemaBuilder", { enumerable: true, get: function () { return schema_builder_1.SchemaBuilder; } });
9
- var parameter_resolver_1 = require("./parameter-resolver");
10
- Object.defineProperty(exports, "ParameterResolver", { enumerable: true, get: function () { return parameter_resolver_1.ParameterResolver; } });
11
- var response_builder_1 = require("./response-builder");
12
- Object.defineProperty(exports, "ResponseBuilder", { enumerable: true, get: function () { return response_builder_1.ResponseBuilder; } });
13
- var validator_1 = require("./validator");
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; } });
18
- // Error exports
19
- var errors_1 = require("./errors");
20
- Object.defineProperty(exports, "OpenAPIToolError", { enumerable: true, get: function () { return errors_1.OpenAPIToolError; } });
21
- Object.defineProperty(exports, "LoadError", { enumerable: true, get: function () { return errors_1.LoadError; } });
22
- Object.defineProperty(exports, "ParseError", { enumerable: true, get: function () { return errors_1.ParseError; } });
23
- Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_1.ValidationError; } });
24
- Object.defineProperty(exports, "GenerationError", { enumerable: true, get: function () { return errors_1.GenerationError; } });
25
- Object.defineProperty(exports, "SchemaError", { enumerable: true, get: function () { return errors_1.SchemaError; } });
26
- // Utility exports
27
- var types_1 = require("./types");
28
- Object.defineProperty(exports, "isReferenceObject", { enumerable: true, get: function () { return types_1.isReferenceObject; } });
29
- Object.defineProperty(exports, "toJsonSchema", { enumerable: true, get: function () { return types_1.toJsonSchema; } });
30
- //# sourceMappingURL=index.js.map
package/src/index.js.map DELETED
@@ -1 +0,0 @@
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"]}