mcp-swagger-parser
Version:
Enterprise-grade OpenAPI/Swagger specification parser for Model Context Protocol (MCP) projects
175 lines • 5.12 kB
JavaScript
;
/**
* Enhanced utility functions for OpenAPI parsing and transformation
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isReferenceObject = isReferenceObject;
exports.getOperationCount = getOperationCount;
exports.getPathCount = getPathCount;
exports.getSchemaCount = getSchemaCount;
exports.getAllTags = getAllTags;
exports.normalizeVersion = normalizeVersion;
exports.isSupportedVersion = isSupportedVersion;
exports.extractPathParameters = extractPathParameters;
exports.generateToolName = generateToolName;
exports.getActionFromMethod = getActionFromMethod;
exports.getResourceFromPath = getResourceFromPath;
exports.isValidUrl = isValidUrl;
exports.sanitizeIdentifier = sanitizeIdentifier;
exports.formatDuration = formatDuration;
exports.parseContentType = parseContentType;
/**
* Check if an object is a reference object
*/
function isReferenceObject(obj) {
return obj && typeof obj === 'object' && '$ref' in obj;
}
/**
* Extract operation count from OpenAPI spec
*/
function getOperationCount(spec) {
let count = 0;
if (spec.paths) {
for (const pathItem of Object.values(spec.paths)) {
const methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'];
count += methods.filter(method => pathItem[method]).length;
}
}
return count;
}
/**
* Extract path count from OpenAPI spec
*/
function getPathCount(spec) {
return spec.paths ? Object.keys(spec.paths).length : 0;
}
/**
* Extract schema count from OpenAPI spec
*/
function getSchemaCount(spec) {
return spec.components?.schemas ? Object.keys(spec.components.schemas).length : 0;
}
/**
* Get all tags from OpenAPI spec
*/
function getAllTags(spec) {
const tags = new Set();
// From global tags
if (spec.tags) {
spec.tags.forEach(tag => tags.add(tag.name));
}
// From operations
if (spec.paths) {
for (const pathItem of Object.values(spec.paths)) {
const methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'];
methods.forEach(method => {
const operation = pathItem[method];
if (operation && typeof operation === 'object' && 'tags' in operation && operation.tags) {
operation.tags.forEach((tag) => tags.add(tag));
}
});
}
}
return Array.from(tags).sort();
}
/**
* Normalize OpenAPI version string
*/
function normalizeVersion(version) {
const match = version.match(/(\d+\.\d+(?:\.\d+)?)/);
return match ? match[1] : version;
}
/**
* Check if OpenAPI version is supported
*/
function isSupportedVersion(version) {
const normalized = normalizeVersion(version);
return normalized.startsWith('3.');
}
/**
* Extract path parameters from OpenAPI path string
*/
function extractPathParameters(path) {
const matches = path.match(/\{([^}]+)\}/g);
return matches ? matches.map(match => match.slice(1, -1)) : [];
}
/**
* Generate tool name from operation
*/
function generateToolName(method, path, operationId) {
if (operationId) {
return operationId.replace(/[^a-zA-Z0-9_]/g, '_');
}
const pathSegments = path.split('/').filter(segment => segment && !segment.startsWith('{'));
const cleanPath = pathSegments.join('_').replace(/[^a-zA-Z0-9_]/g, '_');
return `${method}_${cleanPath}`.toLowerCase().replace(/^_+|_+$/g, '');
}
/**
* Get action verb from HTTP method
*/
function getActionFromMethod(method) {
const actions = {
get: 'Retrieve',
post: 'Create',
put: 'Update',
patch: 'Partially update',
delete: 'Delete',
head: 'Get headers for',
options: 'Get options for',
trace: 'Trace'
};
return actions[method.toLowerCase()] || 'Execute';
}
/**
* Get resource name from path
*/
function getResourceFromPath(path) {
const segments = path.split('/').filter(segment => segment && !segment.startsWith('{') && segment !== 'api');
return segments.length > 0 ? segments.join(' ') : 'resource';
}
/**
* Validate URL format
*/
function isValidUrl(url) {
try {
new URL(url);
return true;
}
catch {
return false;
}
}
/**
* Sanitize string for use as identifier
*/
function sanitizeIdentifier(str) {
return str.replace(/[^a-zA-Z0-9_]/g, '_').replace(/^_+|_+$/g, '');
}
/**
* Format duration in human readable format
*/
function formatDuration(milliseconds) {
if (milliseconds < 1000) {
return `${milliseconds}ms`;
}
const seconds = milliseconds / 1000;
if (seconds < 60) {
return `${seconds.toFixed(1)}s`;
}
const minutes = seconds / 60;
return `${minutes.toFixed(1)}m`;
}
/**
* Parse content type to determine format
*/
function parseContentType(contentType) {
const lower = contentType.toLowerCase();
if (lower.includes('json')) {
return 'json';
}
if (lower.includes('yaml') || lower.includes('yml')) {
return 'yaml';
}
return 'unknown';
}
//# sourceMappingURL=index.js.map