openapi-mcp-generator
Version:
Generates MCP server code from OpenAPI specifications
50 lines • 2.04 kB
JavaScript
/**
* Programmatic API for OpenAPI to MCP Generator
* Allows direct usage from other Node.js applications
*/
import SwaggerParser from '@apidevtools/swagger-parser';
import { extractToolsFromApi } from './parser/extract-tools.js';
import { determineBaseUrl } from './utils/url.js';
/**
* Get a list of tools from an OpenAPI specification
*
* @param specPathOrUrl Path or URL to the OpenAPI specification
* @param options Options for generating the tools
* @returns Promise that resolves to an array of tool definitions
*/
export async function getToolsFromOpenApi(specPathOrUrl, options = {}) {
try {
// Parse the OpenAPI spec
const api = options.dereference
? (await SwaggerParser.dereference(specPathOrUrl))
: (await SwaggerParser.parse(specPathOrUrl));
// Extract tools from the API
const allTools = extractToolsFromApi(api);
// Add base URL to each tool
const baseUrl = determineBaseUrl(api, options.baseUrl);
// Apply filters to exclude specified operationIds and custom filter function
let filteredTools = allTools;
// Filter by excluded operation IDs if provided
if (options.excludeOperationIds && options.excludeOperationIds.length > 0) {
const excludeSet = new Set(options.excludeOperationIds);
filteredTools = filteredTools.filter(tool => !excludeSet.has(tool.operationId));
}
// Apply custom filter function if provided
if (options.filterFn) {
filteredTools = filteredTools.filter(options.filterFn);
}
// Return the filtered tools with base URL added
return filteredTools.map(tool => ({
...tool,
baseUrl: baseUrl || '',
}));
}
catch (error) {
// Provide more context for the error
if (error instanceof Error) {
throw new Error(`Failed to extract tools from OpenAPI: ${error.message}`);
}
throw error;
}
}
//# sourceMappingURL=api.js.map