-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathapi.ts
More file actions
81 lines (68 loc) · 2.58 KB
/
api.ts
File metadata and controls
81 lines (68 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Programmatic API for OpenAPI to MCP Generator
* Allows direct usage from other Node.js applications
*/
import SwaggerParser from '@apidevtools/swagger-parser';
import { OpenAPIV3 } from 'openapi-types';
import { extractToolsFromApi } from './parser/extract-tools.js';
import type { McpToolDefinition } from './types/index.js';
import { determineBaseUrl } from './utils/url.js';
/**
* Options for generating the MCP tools
*/
export interface GetToolsOptions {
/** Optional base URL to override the one in the OpenAPI spec */
baseUrl?: string;
/** Whether to dereference the OpenAPI spec */
dereference?: boolean;
/** Array of operation IDs to exclude from the tools list */
excludeOperationIds?: string[];
/** Optional filter function to exclude tools based on custom criteria */
filterFn?: (tool: McpToolDefinition) => boolean;
}
/**
* 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: string,
options: GetToolsOptions = {}
): Promise<McpToolDefinition[]> {
try {
// Parse the OpenAPI spec
const api = options.dereference
? (await SwaggerParser.dereference(specPathOrUrl)) as OpenAPIV3.Document
: (await SwaggerParser.parse(specPathOrUrl)) as OpenAPIV3.Document;
// 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;
}
}
// Export types for convenience
export { McpToolDefinition };