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.
@@ -0,0 +1,324 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecurityResolver = void 0;
4
+ exports.createSecurityContext = createSecurityContext;
5
+ /**
6
+ * Security resolver that maps OpenAPI security requirements to actual auth values
7
+ *
8
+ * This helper handles security parameters from any OpenAPI spec, regardless of
9
+ * custom naming (BearerAuth, JWT, Authorization, etc.). It uses the mapper's
10
+ * security metadata to determine the auth type and format.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // In FrontMCP
15
+ * const resolver = new SecurityResolver();
16
+ * const resolved = resolver.resolve(tool.mapper, {
17
+ * jwt: context.authInfo.jwt,
18
+ * apiKey: process.env.API_KEY
19
+ * });
20
+ *
21
+ * // Use resolved.headers in HTTP request
22
+ * fetch(url, { headers: { ...resolved.headers, ...otherHeaders } });
23
+ * ```
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // Custom resolver for framework-specific auth
28
+ * const resolved = resolver.resolve(tool.mapper, {
29
+ * customResolver: (security) => {
30
+ * if (security.type === 'http' && security.httpScheme === 'bearer') {
31
+ * return myFramework.getAuthToken();
32
+ * }
33
+ * return undefined;
34
+ * }
35
+ * });
36
+ * ```
37
+ */
38
+ class SecurityResolver {
39
+ /**
40
+ * Resolve security parameters from mapper entries
41
+ *
42
+ * @param mappers - Parameter mappers from the tool definition
43
+ * @param context - Security context with auth values or custom resolver
44
+ * @returns Resolved headers, query params, and cookies with auth applied
45
+ */
46
+ async resolve(mappers, context) {
47
+ const resolved = {
48
+ headers: {},
49
+ query: {},
50
+ cookies: {},
51
+ };
52
+ // Add client certificate if available (for mTLS)
53
+ if (context.clientCertificate) {
54
+ resolved.clientCertificate = context.clientCertificate;
55
+ }
56
+ // Check if signature-based auth is needed
57
+ let requiresSignature = false;
58
+ let signatureScheme;
59
+ for (const mapper of mappers) {
60
+ // Skip non-security parameters
61
+ if (!mapper.security) {
62
+ continue;
63
+ }
64
+ // Check for signature-based auth
65
+ if (this.isSignatureBasedAuth(mapper.security)) {
66
+ requiresSignature = true;
67
+ signatureScheme = mapper.security.scheme;
68
+ // Signature will be added later by signRequest()
69
+ continue;
70
+ }
71
+ // Try to resolve the auth value
72
+ const authValue = await this.resolveAuthValue(mapper.security, context);
73
+ if (!authValue) {
74
+ // Auth value not available - skip this security requirement
75
+ // Framework may want to throw an error or log a warning
76
+ continue;
77
+ }
78
+ // Apply to the correct location
79
+ const headerName = mapper.key;
80
+ if (mapper.type === 'header') {
81
+ resolved.headers[headerName] = authValue;
82
+ }
83
+ else if (mapper.type === 'query') {
84
+ resolved.query[headerName] = authValue;
85
+ }
86
+ else if (mapper.type === 'cookie') {
87
+ resolved.cookies[headerName] = authValue;
88
+ }
89
+ }
90
+ // Add context cookies if available
91
+ if (context.cookies) {
92
+ resolved.cookies = { ...resolved.cookies, ...context.cookies };
93
+ }
94
+ // Add signature metadata if needed
95
+ if (requiresSignature) {
96
+ resolved.requiresSignature = true;
97
+ resolved.signatureInfo = {
98
+ scheme: signatureScheme || 'unknown',
99
+ };
100
+ }
101
+ return resolved;
102
+ }
103
+ /**
104
+ * Check if security scheme requires request signing
105
+ */
106
+ isSignatureBasedAuth(security) {
107
+ // Check for schemes that typically require signing
108
+ const signatureSchemes = ['aws4', 'hmac', 'signature', 'hawk', 'custom-signature'];
109
+ return signatureSchemes.some(scheme => security.scheme.toLowerCase().includes(scheme));
110
+ }
111
+ /**
112
+ * Resolve the actual auth value based on security type
113
+ */
114
+ async resolveAuthValue(security, context) {
115
+ // Try custom resolver first
116
+ if (context.customResolver) {
117
+ const customValue = await context.customResolver(security);
118
+ if (customValue !== undefined) {
119
+ return customValue;
120
+ }
121
+ }
122
+ // Handle standard security types
123
+ if (security.type === 'http') {
124
+ return this.resolveHttpAuth(security, context);
125
+ }
126
+ else if (security.type === 'apiKey') {
127
+ return this.resolveApiKey(security, context);
128
+ }
129
+ else if (security.type === 'oauth2' || security.type === 'openIdConnect') {
130
+ return this.resolveOAuth2(security, context);
131
+ }
132
+ return undefined;
133
+ }
134
+ /**
135
+ * Resolve HTTP authentication (bearer, basic, digest, etc.)
136
+ */
137
+ resolveHttpAuth(security, context) {
138
+ const scheme = security.httpScheme?.toLowerCase() || 'bearer';
139
+ switch (scheme) {
140
+ case 'bearer':
141
+ return this.resolveBearerAuth(context);
142
+ case 'basic':
143
+ return this.resolveBasicAuth(context);
144
+ case 'digest':
145
+ return this.resolveDigestAuth(context);
146
+ case 'hoba':
147
+ case 'mutual':
148
+ case 'negotiate':
149
+ case 'vapid':
150
+ case 'scram':
151
+ // These schemes typically require custom implementation
152
+ // Try custom headers or signature generator
153
+ return this.resolveCustomHttpScheme(scheme, security, context);
154
+ default:
155
+ // Unknown scheme - try custom resolver
156
+ return undefined;
157
+ }
158
+ }
159
+ /**
160
+ * Resolve Bearer token authentication
161
+ */
162
+ resolveBearerAuth(context) {
163
+ const token = context.jwt;
164
+ if (!token)
165
+ return undefined;
166
+ return `Bearer ${token}`;
167
+ }
168
+ /**
169
+ * Resolve Basic authentication
170
+ */
171
+ resolveBasicAuth(context) {
172
+ const credentials = context.basic;
173
+ if (!credentials)
174
+ return undefined;
175
+ return `Basic ${credentials}`;
176
+ }
177
+ /**
178
+ * Resolve Digest authentication
179
+ */
180
+ resolveDigestAuth(context) {
181
+ const digest = context.digest;
182
+ if (!digest)
183
+ return undefined;
184
+ // Build digest auth header
185
+ const parts = [
186
+ `username="${digest.username}"`,
187
+ digest.realm ? `realm="${digest.realm}"` : '',
188
+ digest.nonce ? `nonce="${digest.nonce}"` : '',
189
+ digest.uri ? `uri="${digest.uri}"` : '',
190
+ digest.response ? `response="${digest.response}"` : '',
191
+ digest.opaque ? `opaque="${digest.opaque}"` : '',
192
+ digest.qop ? `qop=${digest.qop}` : '',
193
+ digest.nc ? `nc=${digest.nc}` : '',
194
+ digest.cnonce ? `cnonce="${digest.cnonce}"` : '',
195
+ ].filter(Boolean);
196
+ return `Digest ${parts.join(', ')}`;
197
+ }
198
+ /**
199
+ * Resolve custom HTTP authentication schemes
200
+ */
201
+ resolveCustomHttpScheme(scheme, security, context) {
202
+ // Try custom headers first
203
+ const headerKey = security.apiKeyName || `X-${scheme.toUpperCase()}`;
204
+ if (context.customHeaders?.[headerKey]) {
205
+ return context.customHeaders[headerKey];
206
+ }
207
+ // Unknown scheme
208
+ return undefined;
209
+ }
210
+ /**
211
+ * Resolve API key authentication
212
+ */
213
+ resolveApiKey(security, context) {
214
+ // Try named API keys first (for multiple keys)
215
+ if (context.apiKeys && security.apiKeyName) {
216
+ const key = context.apiKeys[security.apiKeyName];
217
+ if (key)
218
+ return key;
219
+ }
220
+ // Try custom headers (for proprietary auth headers like X-Custom-Auth)
221
+ if (context.customHeaders && security.apiKeyName) {
222
+ const header = context.customHeaders[security.apiKeyName];
223
+ if (header)
224
+ return header;
225
+ }
226
+ // Fall back to single apiKey (backward compatibility)
227
+ return context.apiKey;
228
+ }
229
+ /**
230
+ * Resolve OAuth2/OpenID Connect authentication
231
+ */
232
+ resolveOAuth2(security, context) {
233
+ const token = context.oauth2Token;
234
+ if (!token)
235
+ return undefined;
236
+ // OAuth2 tokens are typically formatted as "Bearer {token}"
237
+ return `Bearer ${token}`;
238
+ }
239
+ /**
240
+ * Check if any security requirements are missing from context
241
+ *
242
+ * @param mappers - Parameter mappers from the tool definition
243
+ * @param context - Security context with auth values
244
+ * @returns Array of missing security scheme names
245
+ */
246
+ async checkMissingSecurity(mappers, context) {
247
+ const missing = [];
248
+ for (const mapper of mappers) {
249
+ if (!mapper.security)
250
+ continue;
251
+ const authValue = await this.resolveAuthValue(mapper.security, context);
252
+ if (!authValue) {
253
+ missing.push(mapper.security.scheme);
254
+ }
255
+ }
256
+ return missing;
257
+ }
258
+ /**
259
+ * Sign a request for signature-based authentication
260
+ *
261
+ * Use this when resolved.requiresSignature is true.
262
+ * This method will call the signatureGenerator from context to sign the request.
263
+ *
264
+ * @param mappers - Parameter mappers from the tool definition
265
+ * @param signatureData - Request data to sign
266
+ * @param context - Security context with signature generator
267
+ * @returns Headers with signature added
268
+ *
269
+ * @example
270
+ * ```typescript
271
+ * const resolved = resolver.resolve(tool.mapper, context);
272
+ * if (resolved.requiresSignature) {
273
+ * const signedHeaders = await resolver.signRequest(
274
+ * tool.mapper,
275
+ * { method: 'GET', url: 'https://api.example.com/data', headers: resolved.headers },
276
+ * context
277
+ * );
278
+ * // Use signedHeaders in request
279
+ * }
280
+ * ```
281
+ */
282
+ async signRequest(mappers, signatureData, context) {
283
+ const headers = { ...signatureData.headers };
284
+ if (!context.signatureGenerator) {
285
+ throw new Error('Signature-based auth required but no signatureGenerator provided');
286
+ }
287
+ for (const mapper of mappers) {
288
+ if (!mapper.security || !this.isSignatureBasedAuth(mapper.security)) {
289
+ continue;
290
+ }
291
+ // Call signature generator
292
+ const signature = await context.signatureGenerator(signatureData, mapper.security);
293
+ // Add signature to appropriate location
294
+ if (mapper.type === 'header') {
295
+ headers[mapper.key] = signature;
296
+ }
297
+ // Note: Query/cookie signatures would be handled differently
298
+ }
299
+ return headers;
300
+ }
301
+ }
302
+ exports.SecurityResolver = SecurityResolver;
303
+ /**
304
+ * Create a basic security context from common auth sources
305
+ *
306
+ * @example
307
+ * ```typescript
308
+ * const context = createSecurityContext({
309
+ * jwt: process.env.JWT_TOKEN,
310
+ * apiKey: process.env.API_KEY
311
+ * });
312
+ * ```
313
+ */
314
+ function createSecurityContext(auth) {
315
+ return {
316
+ ...auth,
317
+ jwt: auth.jwt,
318
+ basic: auth.basic,
319
+ apiKey: auth.apiKey,
320
+ oauth2Token: auth.oauth2Token,
321
+ customResolver: auth.customResolver,
322
+ };
323
+ }
324
+ //# sourceMappingURL=security-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"security-resolver.js","sourceRoot":"","sources":["../../src/security-resolver.ts"],"names":[],"mappings":";;;AA+iBA,sDAWC;A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AAC;gBAC7B,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;YAClC,CAAC;YACD,6DAA6D;QAC/D,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AA/TD,4CA+TC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,qBAAqB,CACnC,IAA8B;IAE9B,OAAO;QACL,GAAG,IAAI;QACP,GAAG,EAAE,IAAI,CAAC,GAAG;QACb,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,cAAc,EAAE,IAAI,CAAC,cAAc;KACpC,CAAC;AACJ,CAAC","sourcesContent":["import type { ParameterMapper, SecurityParameterInfo } from './types';\n\n/**\n * Context for resolving security parameters\n * Frameworks should implement this interface based on their auth system\n */\nexport interface SecurityContext {\n /**\n * JWT/Bearer token\n */\n jwt?: string;\n\n /**\n * Basic auth credentials (base64 encoded \"username:password\")\n */\n basic?: string;\n\n /**\n * Digest auth credentials\n * Object with username, password, realm, nonce, etc.\n */\n digest?: DigestAuthCredentials;\n\n /**\n * API key (single key for backward compatibility)\n */\n apiKey?: string;\n\n /**\n * Multiple API keys by name\n * Use this when API requires different keys for different purposes\n * @example { 'X-API-Key': 'key1', 'X-Client-Id': 'client123' }\n */\n apiKeys?: Record<string, string>;\n\n /**\n * OAuth2 access token\n */\n oauth2Token?: string;\n\n /**\n * Client certificate for mutual TLS (mTLS)\n */\n clientCertificate?: ClientCertificate;\n\n /**\n * Private key for signature-based auth (HMAC, AWS Signature V4, etc.)\n */\n privateKey?: string;\n\n /**\n * Public key (if needed for verification)\n */\n publicKey?: string;\n\n /**\n * HMAC secret for HMAC-based authentication\n */\n hmacSecret?: string;\n\n /**\n * AWS credentials for AWS Signature V4\n */\n awsCredentials?: AWSCredentials;\n\n /**\n * Custom headers for proprietary authentication\n * @example { 'X-Custom-Auth': 'custom-value' }\n */\n customHeaders?: Record<string, string>;\n\n /**\n * Session cookies\n */\n cookies?: Record<string, string>;\n\n /**\n * Custom resolver for framework-specific auth\n * @param security - Security parameter info from mapper\n * @returns The auth value to use, or undefined if not available\n */\n customResolver?: (security: SecurityParameterInfo) => string | Promise<string | undefined>;\n\n /**\n * Signature generator for signature-based auth\n * @param data - Data to sign (typically the request)\n * @param security - Security parameter info\n * @returns The signature or signed value\n */\n signatureGenerator?: (data: SignatureData, security: SecurityParameterInfo) => string | Promise<string>;\n}\n\n/**\n * Digest authentication credentials\n */\nexport interface DigestAuthCredentials {\n username: string;\n password: string;\n realm?: string;\n nonce?: string;\n uri?: string;\n qop?: string;\n nc?: string;\n cnonce?: string;\n response?: string;\n opaque?: string;\n}\n\n/**\n * Client certificate for mTLS\n */\nexport interface ClientCertificate {\n /**\n * Certificate in PEM format\n */\n cert: string;\n\n /**\n * Private key in PEM format\n */\n key: string;\n\n /**\n * Passphrase for encrypted key\n */\n passphrase?: string;\n\n /**\n * CA certificates\n */\n ca?: string | string[];\n}\n\n/**\n * AWS credentials for Signature V4\n */\nexport interface AWSCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n region?: string;\n service?: string;\n}\n\n/**\n * Data to be signed for signature-based auth\n */\nexport interface SignatureData {\n method: string;\n url: string;\n headers: Record<string, string>;\n body?: string;\n timestamp?: number;\n}\n\n/**\n * Resolved security parameters ready to be added to HTTP request\n */\nexport interface ResolvedSecurity {\n /**\n * Headers to add to the request\n */\n headers: Record<string, string>;\n\n /**\n * Query parameters to add to the request\n */\n query: Record<string, string>;\n\n /**\n * Cookie values to add to the request\n */\n cookies: Record<string, string>;\n\n /**\n * Client certificate for mTLS (if applicable)\n */\n clientCertificate?: ClientCertificate;\n\n /**\n * Whether signature-based auth is required\n * If true, you need to call signRequest() before sending\n */\n requiresSignature?: boolean;\n\n /**\n * Signature metadata (if signature-based auth is used)\n */\n signatureInfo?: {\n scheme: string;\n algorithm?: string;\n };\n}\n\n/**\n * Security resolver that maps OpenAPI security requirements to actual auth values\n *\n * This helper handles security parameters from any OpenAPI spec, regardless of\n * custom naming (BearerAuth, JWT, Authorization, etc.). It uses the mapper's\n * security metadata to determine the auth type and format.\n *\n * @example\n * ```typescript\n * // In FrontMCP\n * const resolver = new SecurityResolver();\n * const resolved = resolver.resolve(tool.mapper, {\n * jwt: context.authInfo.jwt,\n * apiKey: process.env.API_KEY\n * });\n *\n * // Use resolved.headers in HTTP request\n * fetch(url, { headers: { ...resolved.headers, ...otherHeaders } });\n * ```\n *\n * @example\n * ```typescript\n * // Custom resolver for framework-specific auth\n * const resolved = resolver.resolve(tool.mapper, {\n * customResolver: (security) => {\n * if (security.type === 'http' && security.httpScheme === 'bearer') {\n * return myFramework.getAuthToken();\n * }\n * return undefined;\n * }\n * });\n * ```\n */\nexport class SecurityResolver {\n /**\n * Resolve security parameters from mapper entries\n *\n * @param mappers - Parameter mappers from the tool definition\n * @param context - Security context with auth values or custom resolver\n * @returns Resolved headers, query params, and cookies with auth applied\n */\n async resolve(mappers: ParameterMapper[], context: SecurityContext): Promise<ResolvedSecurity> {\n const resolved: ResolvedSecurity = {\n headers: {},\n query: {},\n cookies: {},\n };\n\n // Add client certificate if available (for mTLS)\n if (context.clientCertificate) {\n resolved.clientCertificate = context.clientCertificate;\n }\n\n // Check if signature-based auth is needed\n let requiresSignature = false;\n let signatureScheme: string | undefined;\n\n for (const mapper of mappers) {\n // Skip non-security parameters\n if (!mapper.security) {\n continue;\n }\n\n // Check for signature-based auth\n if (this.isSignatureBasedAuth(mapper.security)) {\n requiresSignature = true;\n signatureScheme = mapper.security.scheme;\n // Signature will be added later by signRequest()\n continue;\n }\n\n // Try to resolve the auth value\n const authValue = await this.resolveAuthValue(mapper.security, context);\n if (!authValue) {\n // Auth value not available - skip this security requirement\n // Framework may want to throw an error or log a warning\n continue;\n }\n\n // Apply to the correct location\n const headerName = mapper.key;\n\n if (mapper.type === 'header') {\n resolved.headers[headerName] = authValue;\n } else if (mapper.type === 'query') {\n resolved.query[headerName] = authValue;\n } else if (mapper.type === 'cookie') {\n resolved.cookies[headerName] = authValue;\n }\n }\n\n // Add context cookies if available\n if (context.cookies) {\n resolved.cookies = { ...resolved.cookies, ...context.cookies };\n }\n\n // Add signature metadata if needed\n if (requiresSignature) {\n resolved.requiresSignature = true;\n resolved.signatureInfo = {\n scheme: signatureScheme || 'unknown',\n };\n }\n\n return resolved;\n }\n\n /**\n * Check if security scheme requires request signing\n */\n private isSignatureBasedAuth(security: SecurityParameterInfo): boolean {\n // Check for schemes that typically require signing\n const signatureSchemes = ['aws4', 'hmac', 'signature', 'hawk', 'custom-signature'];\n return signatureSchemes.some(scheme =>\n security.scheme.toLowerCase().includes(scheme)\n );\n }\n\n /**\n * Resolve the actual auth value based on security type\n */\n private async resolveAuthValue(\n security: SecurityParameterInfo,\n context: SecurityContext\n ): Promise<string | undefined> {\n // Try custom resolver first\n if (context.customResolver) {\n const customValue = await context.customResolver(security);\n if (customValue !== undefined) {\n return customValue;\n }\n }\n\n // Handle standard security types\n if (security.type === 'http') {\n return this.resolveHttpAuth(security, context);\n } else if (security.type === 'apiKey') {\n return this.resolveApiKey(security, context);\n } else if (security.type === 'oauth2' || security.type === 'openIdConnect') {\n return this.resolveOAuth2(security, context);\n }\n\n return undefined;\n }\n\n /**\n * Resolve HTTP authentication (bearer, basic, digest, etc.)\n */\n private resolveHttpAuth(\n security: SecurityParameterInfo,\n context: SecurityContext\n ): string | undefined {\n const scheme = security.httpScheme?.toLowerCase() || 'bearer';\n\n switch (scheme) {\n case 'bearer':\n return this.resolveBearerAuth(context);\n\n case 'basic':\n return this.resolveBasicAuth(context);\n\n case 'digest':\n return this.resolveDigestAuth(context);\n\n case 'hoba':\n case 'mutual':\n case 'negotiate':\n case 'vapid':\n case 'scram':\n // These schemes typically require custom implementation\n // Try custom headers or signature generator\n return this.resolveCustomHttpScheme(scheme, security, context);\n\n default:\n // Unknown scheme - try custom resolver\n return undefined;\n }\n }\n\n /**\n * Resolve Bearer token authentication\n */\n private resolveBearerAuth(context: SecurityContext): string | undefined {\n const token = context.jwt;\n if (!token) return undefined;\n return `Bearer ${token}`;\n }\n\n /**\n * Resolve Basic authentication\n */\n private resolveBasicAuth(context: SecurityContext): string | undefined {\n const credentials = context.basic;\n if (!credentials) return undefined;\n return `Basic ${credentials}`;\n }\n\n /**\n * Resolve Digest authentication\n */\n private resolveDigestAuth(context: SecurityContext): string | undefined {\n const digest = context.digest;\n if (!digest) return undefined;\n\n // Build digest auth header\n const parts: string[] = [\n `username=\"${digest.username}\"`,\n digest.realm ? `realm=\"${digest.realm}\"` : '',\n digest.nonce ? `nonce=\"${digest.nonce}\"` : '',\n digest.uri ? `uri=\"${digest.uri}\"` : '',\n digest.response ? `response=\"${digest.response}\"` : '',\n digest.opaque ? `opaque=\"${digest.opaque}\"` : '',\n digest.qop ? `qop=${digest.qop}` : '',\n digest.nc ? `nc=${digest.nc}` : '',\n digest.cnonce ? `cnonce=\"${digest.cnonce}\"` : '',\n ].filter(Boolean);\n\n return `Digest ${parts.join(', ')}`;\n }\n\n /**\n * Resolve custom HTTP authentication schemes\n */\n private resolveCustomHttpScheme(\n scheme: string,\n security: SecurityParameterInfo,\n context: SecurityContext\n ): string | undefined {\n // Try custom headers first\n const headerKey = security.apiKeyName || `X-${scheme.toUpperCase()}`;\n if (context.customHeaders?.[headerKey]) {\n return context.customHeaders[headerKey];\n }\n\n // Unknown scheme\n return undefined;\n }\n\n /**\n * Resolve API key authentication\n */\n private resolveApiKey(\n security: SecurityParameterInfo,\n context: SecurityContext\n ): string | undefined {\n // Try named API keys first (for multiple keys)\n if (context.apiKeys && security.apiKeyName) {\n const key = context.apiKeys[security.apiKeyName];\n if (key) return key;\n }\n\n // Try custom headers (for proprietary auth headers like X-Custom-Auth)\n if (context.customHeaders && security.apiKeyName) {\n const header = context.customHeaders[security.apiKeyName];\n if (header) return header;\n }\n\n // Fall back to single apiKey (backward compatibility)\n return context.apiKey;\n }\n\n /**\n * Resolve OAuth2/OpenID Connect authentication\n */\n private resolveOAuth2(\n security: SecurityParameterInfo,\n context: SecurityContext\n ): string | undefined {\n const token = context.oauth2Token;\n if (!token) return undefined;\n\n // OAuth2 tokens are typically formatted as \"Bearer {token}\"\n return `Bearer ${token}`;\n }\n\n /**\n * Check if any security requirements are missing from context\n *\n * @param mappers - Parameter mappers from the tool definition\n * @param context - Security context with auth values\n * @returns Array of missing security scheme names\n */\n async checkMissingSecurity(\n mappers: ParameterMapper[],\n context: SecurityContext\n ): Promise<string[]> {\n const missing: string[] = [];\n\n for (const mapper of mappers) {\n if (!mapper.security) continue;\n\n const authValue = await this.resolveAuthValue(mapper.security, context);\n if (!authValue) {\n missing.push(mapper.security.scheme);\n }\n }\n\n return missing;\n }\n\n /**\n * Sign a request for signature-based authentication\n *\n * Use this when resolved.requiresSignature is true.\n * This method will call the signatureGenerator from context to sign the request.\n *\n * @param mappers - Parameter mappers from the tool definition\n * @param signatureData - Request data to sign\n * @param context - Security context with signature generator\n * @returns Headers with signature added\n *\n * @example\n * ```typescript\n * const resolved = resolver.resolve(tool.mapper, context);\n * if (resolved.requiresSignature) {\n * const signedHeaders = await resolver.signRequest(\n * tool.mapper,\n * { method: 'GET', url: 'https://api.example.com/data', headers: resolved.headers },\n * context\n * );\n * // Use signedHeaders in request\n * }\n * ```\n */\n async signRequest(\n mappers: ParameterMapper[],\n signatureData: SignatureData,\n context: SecurityContext\n ): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...signatureData.headers };\n\n if (!context.signatureGenerator) {\n throw new Error('Signature-based auth required but no signatureGenerator provided');\n }\n\n for (const mapper of mappers) {\n if (!mapper.security || !this.isSignatureBasedAuth(mapper.security)) {\n continue;\n }\n\n // Call signature generator\n const signature = await context.signatureGenerator(signatureData, mapper.security);\n\n // Add signature to appropriate location\n if (mapper.type === 'header') {\n headers[mapper.key] = signature;\n }\n // Note: Query/cookie signatures would be handled differently\n }\n\n return headers;\n }\n}\n\n/**\n * Create a basic security context from common auth sources\n *\n * @example\n * ```typescript\n * const context = createSecurityContext({\n * jwt: process.env.JWT_TOKEN,\n * apiKey: process.env.API_KEY\n * });\n * ```\n */\nexport function createSecurityContext(\n auth: Partial<SecurityContext>\n): SecurityContext {\n return {\n ...auth,\n jwt: auth.jwt,\n basic: auth.basic,\n apiKey: auth.apiKey,\n oauth2Token: auth.oauth2Token,\n customResolver: auth.customResolver,\n };\n}\n"]}
package/src/types.d.ts CHANGED
@@ -19,7 +19,7 @@ export type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'body';
19
19
  /**
20
20
  * Authentication types supported
21
21
  */
22
- export type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';
22
+ export type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect' | 'mutualTLS';
23
23
  export type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;
24
24
  export type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;
25
25
  export type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;
@@ -112,6 +112,11 @@ export interface ParameterMapper {
112
112
  * Custom serialization info
113
113
  */
114
114
  serialization?: SerializationInfo;
115
+ /**
116
+ * Security scheme information (if this is an auth parameter)
117
+ * This allows frameworks to resolve auth from context, env vars, etc.
118
+ */
119
+ security?: SecurityParameterInfo;
115
120
  }
116
121
  /**
117
122
  * Serialization information for complex parameters
@@ -126,6 +131,44 @@ export interface SerializationInfo {
126
131
  */
127
132
  encoding?: Record<string, EncodingObject>;
128
133
  }
134
+ /**
135
+ * Security parameter information for framework-agnostic auth resolution
136
+ */
137
+ export interface SecurityParameterInfo {
138
+ /**
139
+ * Security scheme name from OpenAPI (e.g., "BearerAuth")
140
+ */
141
+ scheme: string;
142
+ /**
143
+ * Security type (apiKey, http, oauth2, openIdConnect)
144
+ */
145
+ type: AuthType;
146
+ /**
147
+ * HTTP authentication scheme (for type: "http")
148
+ * e.g., "bearer", "basic"
149
+ */
150
+ httpScheme?: string;
151
+ /**
152
+ * Bearer token format (e.g., "JWT")
153
+ */
154
+ bearerFormat?: string;
155
+ /**
156
+ * Required OAuth2 scopes
157
+ */
158
+ scopes?: string[];
159
+ /**
160
+ * API key parameter name (for type: "apiKey")
161
+ */
162
+ apiKeyName?: string;
163
+ /**
164
+ * API key location (for type: "apiKey")
165
+ */
166
+ apiKeyIn?: 'query' | 'header' | 'cookie';
167
+ /**
168
+ * Description of the security scheme
169
+ */
170
+ description?: string;
171
+ }
129
172
  /**
130
173
  * Additional metadata about the generated tool
131
174
  */
@@ -191,6 +234,19 @@ export interface SecurityRequirement {
191
234
  * Parameter location (for API key)
192
235
  */
193
236
  in?: 'query' | 'header' | 'cookie';
237
+ /**
238
+ * HTTP authentication scheme (for type: "http")
239
+ * e.g., "bearer", "basic"
240
+ */
241
+ httpScheme?: string;
242
+ /**
243
+ * Bearer token format (e.g., "JWT")
244
+ */
245
+ bearerFormat?: string;
246
+ /**
247
+ * Description of the security scheme
248
+ */
249
+ description?: string;
194
250
  }
195
251
  /**
196
252
  * Server information
@@ -296,6 +352,13 @@ export interface GenerateOptions {
296
352
  * @default false
297
353
  */
298
354
  includeExamples?: boolean;
355
+ /**
356
+ * Whether to include security requirements as input parameters
357
+ * If false, security is only in mapper (frameworks resolve from context/env/etc.)
358
+ * If true, security is added to inputSchema as explicit parameters
359
+ * @default false
360
+ */
361
+ includeSecurityInInput?: boolean;
299
362
  }
300
363
  /**
301
364
  * Naming strategy for resolving parameter conflicts
package/src/types.js CHANGED
@@ -18,20 +18,81 @@ function toJSONSchema7(schema) {
18
18
  return { $ref: schema.$ref };
19
19
  }
20
20
  // Handle OpenAPI 3.0 boolean exclusiveMaximum/exclusiveMinimum
21
- const result = { ...schema };
22
- // Convert boolean exclusiveMaximum to number format (JSON Schema Draft 7)
23
- if ('exclusiveMaximum' in schema && typeof schema.exclusiveMaximum === 'boolean') {
24
- if (schema.exclusiveMaximum && 'maximum' in schema) {
25
- result.exclusiveMaximum = schema.maximum;
26
- delete result.maximum;
21
+ // by converting them to JSON Schema Draft 7 numeric format
22
+ const { exclusiveMaximum, exclusiveMinimum, maximum, minimum, ...rest } = schema;
23
+ const result = { ...rest };
24
+ // Handle exclusiveMaximum conversion
25
+ if (typeof exclusiveMaximum === 'boolean') {
26
+ if (exclusiveMaximum && maximum !== undefined) {
27
+ // true + maximum present -> convert to numeric exclusiveMaximum
28
+ result['exclusiveMaximum'] = maximum;
29
+ }
30
+ else if (maximum !== undefined) {
31
+ // false or true without maximum -> keep maximum only
32
+ result['maximum'] = maximum;
33
+ }
34
+ // Boolean exclusiveMaximum is never added (invalid in JSON Schema 7)
35
+ }
36
+ else if (exclusiveMaximum !== undefined) {
37
+ // Already numeric (OpenAPI 3.1) - keep as is
38
+ result['exclusiveMaximum'] = exclusiveMaximum;
39
+ if (maximum !== undefined) {
40
+ result['maximum'] = maximum;
27
41
  }
28
42
  }
29
- // Convert boolean exclusiveMinimum to number format (JSON Schema Draft 7)
30
- if ('exclusiveMinimum' in schema && typeof schema.exclusiveMinimum === 'boolean') {
31
- if (schema.exclusiveMinimum && 'minimum' in schema) {
32
- result.exclusiveMinimum = schema.minimum;
33
- delete result.minimum;
43
+ else if (maximum !== undefined) {
44
+ // No exclusiveMaximum, just maximum
45
+ result['maximum'] = maximum;
46
+ }
47
+ // Handle exclusiveMinimum conversion
48
+ if (typeof exclusiveMinimum === 'boolean') {
49
+ if (exclusiveMinimum && minimum !== undefined) {
50
+ // true + minimum present -> convert to numeric exclusiveMinimum
51
+ result['exclusiveMinimum'] = minimum;
52
+ }
53
+ else if (minimum !== undefined) {
54
+ // false or true without minimum -> keep minimum only
55
+ result['minimum'] = minimum;
34
56
  }
57
+ // Boolean exclusiveMinimum is never added (invalid in JSON Schema 7)
58
+ }
59
+ else if (exclusiveMinimum !== undefined) {
60
+ // Already numeric (OpenAPI 3.1) - keep as is
61
+ result['exclusiveMinimum'] = exclusiveMinimum;
62
+ if (minimum !== undefined) {
63
+ result['minimum'] = minimum;
64
+ }
65
+ }
66
+ else if (minimum !== undefined) {
67
+ // No exclusiveMinimum, just minimum
68
+ result['minimum'] = minimum;
69
+ }
70
+ // Recursively convert nested schemas to ensure all nested schemas are valid JSONSchema7
71
+ if (result['properties'] && typeof result['properties'] === 'object') {
72
+ const props = {};
73
+ for (const [key, value] of Object.entries(result['properties'])) {
74
+ props[key] = toJSONSchema7(value);
75
+ }
76
+ result['properties'] = props;
77
+ }
78
+ if (result['items']) {
79
+ if (Array.isArray(result['items'])) {
80
+ result['items'] = result['items'].map(toJSONSchema7);
81
+ }
82
+ else {
83
+ result['items'] = toJSONSchema7(result['items']);
84
+ }
85
+ }
86
+ if (result['additionalProperties'] && typeof result['additionalProperties'] === 'object') {
87
+ result['additionalProperties'] = toJSONSchema7(result['additionalProperties']);
88
+ }
89
+ for (const key of ['allOf', 'anyOf', 'oneOf']) {
90
+ if (result[key] && Array.isArray(result[key])) {
91
+ result[key] = result[key].map(toJSONSchema7);
92
+ }
93
+ }
94
+ if (result['not']) {
95
+ result['not'] = toJSONSchema7(result['not']);
35
96
  }
36
97
  return result;
37
98
  }
package/src/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;AAoDA,8CAEC;AAOD,sCAyBC;AArCD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,GAAQ;IACxC,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,CAAC;AACzD,CAAC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,MAAsC;IAClE,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAiB,CAAC;IAC9C,CAAC;IAED,+DAA+D;IAC/D,MAAM,MAAM,GAAgB,EAAE,GAAG,MAAM,EAAS,CAAC;IAEjD,0EAA0E;IAC1E,IAAI,kBAAkB,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,gBAAgB,KAAK,SAAS,EAAE,CAAC;QACjF,IAAI,MAAM,CAAC,gBAAgB,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;YACnD,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,OAAiB,CAAC;YACnD,OAAO,MAAM,CAAC,OAAO,CAAC;QACxB,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,IAAI,kBAAkB,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,gBAAgB,KAAK,SAAS,EAAE,CAAC;QACjF,IAAI,MAAM,CAAC,gBAAgB,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;YACnD,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,OAAiB,CAAC;YACnD,OAAO,MAAM,CAAC,OAAO,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { JSONSchema7 } from 'json-schema';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\n/**\n * OpenAPI specification version 3.0.x or 3.1.x\n */\nexport type OpenAPIVersion = '3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0';\n\n/**\n * Unified OpenAPI Document type (supports both 3.0 and 3.1)\n */\nexport type OpenAPIDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\n/**\n * HTTP methods supported by OpenAPI\n */\nexport type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * Parameter location types\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'body';\n\n/**\n * Authentication types supported\n */\nexport type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';\n\n// Re-export OpenAPI types for convenience\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type ResponsesObject = OpenAPIV3.ResponsesObject | OpenAPIV3_1.ResponsesObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type HeaderObject = OpenAPIV3.HeaderObject | OpenAPIV3_1.HeaderObject;\nexport type ExampleObject = OpenAPIV3.ExampleObject | OpenAPIV3_1.ExampleObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type PathsObject = OpenAPIV3.PathsObject | OpenAPIV3_1.PathsObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\nexport type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject | OpenAPIV3_1.SecuritySchemeObject;\nexport type ReferenceObject = OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;\nexport type TagObject = OpenAPIV3.TagObject | OpenAPIV3_1.TagObject;\nexport type ExternalDocumentationObject = OpenAPIV3.ExternalDocumentationObject | OpenAPIV3_1.ExternalDocumentationObject;\nexport type ServerVariableObject = OpenAPIV3.ServerVariableObject | OpenAPIV3_1.ServerVariableObject;\nexport type EncodingObject = OpenAPIV3.EncodingObject | OpenAPIV3_1.EncodingObject;\nexport type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject | OpenAPIV3_1.SecurityRequirementObject;\nexport type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;\n\n/**\n * Helper to check if an object is a ReferenceObject\n */\nexport function isReferenceObject(obj: any): obj is ReferenceObject {\n return obj && typeof obj === 'object' && '$ref' in obj;\n}\n\n/**\n * Convert OpenAPI schema to JSONSchema7\n * Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4\n * OpenAPI 3.1 uses JSON Schema Draft 2020-12\n */\nexport function toJSONSchema7(schema: SchemaObject | ReferenceObject): JSONSchema7 {\n if (isReferenceObject(schema)) {\n return { $ref: schema.$ref } as JSONSchema7;\n }\n\n // Handle OpenAPI 3.0 boolean exclusiveMaximum/exclusiveMinimum\n const result: JSONSchema7 = { ...schema } as any;\n\n // Convert boolean exclusiveMaximum to number format (JSON Schema Draft 7)\n if ('exclusiveMaximum' in schema && typeof schema.exclusiveMaximum === 'boolean') {\n if (schema.exclusiveMaximum && 'maximum' in schema) {\n result.exclusiveMaximum = schema.maximum as number;\n delete result.maximum;\n }\n }\n\n // Convert boolean exclusiveMinimum to number format (JSON Schema Draft 7)\n if ('exclusiveMinimum' in schema && typeof schema.exclusiveMinimum === 'boolean') {\n if (schema.exclusiveMinimum && 'minimum' in schema) {\n result.exclusiveMinimum = schema.minimum as number;\n delete result.minimum;\n }\n }\n\n return result;\n}\n\n/**\n * Main MCP Tool definition generated from OpenAPI\n */\nexport interface McpOpenAPITool {\n /**\n * Unique tool name (from operationId or generated)\n */\n name: string;\n\n /**\n * Tool description (from operation summary/description)\n */\n description: string;\n\n /**\n * Combined input schema including all parameters\n * (path, query, header, cookie, body)\n */\n inputSchema: JSONSchema7;\n\n /**\n * Output schema based on response definitions\n * Can be a union of multiple status codes\n */\n outputSchema?: JSONSchema7;\n\n /**\n * Mapping from input schema properties to actual request parameters\n */\n mapper: ParameterMapper[];\n\n /**\n * Additional metadata about the tool\n */\n metadata: ToolMetadata;\n}\n\n/**\n * Maps input schema properties to their actual request locations\n */\nexport interface ParameterMapper {\n /**\n * Property name in the input schema\n */\n inputKey: string;\n\n /**\n * Where this parameter should be placed in the request\n */\n type: ParameterLocation;\n\n /**\n * Original parameter name (before conflict resolution)\n */\n key: string;\n\n /**\n * Whether this parameter is required\n */\n required?: boolean;\n\n /**\n * Parameter style (for path/query parameters)\n */\n style?: string;\n\n /**\n * Whether to explode arrays/objects\n */\n explode?: boolean;\n\n /**\n * Custom serialization info\n */\n serialization?: SerializationInfo;\n}\n\n/**\n * Serialization information for complex parameters\n */\nexport interface SerializationInfo {\n /**\n * Content type for body parameters\n */\n contentType?: string;\n\n /**\n * Encoding rules\n */\n encoding?: Record<string, EncodingObject>;\n}\n\n/**\n * Additional metadata about the generated tool\n */\nexport interface ToolMetadata {\n /**\n * Original OpenAPI path\n */\n path: string;\n\n /**\n * HTTP method\n */\n method: HTTPMethod;\n\n /**\n * Operation ID from OpenAPI\n */\n operationId?: string;\n\n /**\n * Tags from OpenAPI\n */\n tags?: string[];\n\n /**\n * Whether operation is deprecated\n */\n deprecated?: boolean;\n\n /**\n * Security requirements\n */\n security?: SecurityRequirement[];\n\n /**\n * Server information\n */\n servers?: ServerInfo[];\n\n /**\n * Response status codes included in output schema\n */\n responseStatusCodes?: number[];\n\n /**\n * External documentation\n */\n externalDocs?: ExternalDocumentationObject;\n}\n\n/**\n * Security requirement definition\n */\nexport interface SecurityRequirement {\n /**\n * Security scheme name\n */\n scheme: string;\n\n /**\n * Security type\n */\n type: AuthType;\n\n /**\n * Scopes required (for OAuth2/OpenID Connect)\n */\n scopes?: string[];\n\n /**\n * Parameter name (for API key)\n */\n name?: string;\n\n /**\n * Parameter location (for API key)\n */\n in?: 'query' | 'header' | 'cookie';\n}\n\n/**\n * Server information\n */\nexport interface ServerInfo {\n /**\n * Server URL\n */\n url: string;\n\n /**\n * Server description\n */\n description?: string;\n\n /**\n * Server variables\n */\n variables?: Record<string, ServerVariableObject>;\n}\n\n/**\n * Options for loading OpenAPI specifications\n */\nexport interface LoadOptions {\n /**\n * Whether to dereference $refs in schemas\n * @default true\n */\n dereference?: boolean;\n\n /**\n * Base URL for API requests\n * Overrides servers in OpenAPI spec\n */\n baseUrl?: string;\n\n /**\n * Custom HTTP headers for loading from URL\n */\n headers?: Record<string, string>;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Whether to validate the OpenAPI document\n * @default true\n */\n validate?: boolean;\n\n /**\n * Whether to follow HTTP redirects\n * @default true\n */\n followRedirects?: boolean;\n}\n\n/**\n * Operation object with additional context for filtering\n */\nexport type OperationWithContext = OperationObject & {\n path: string;\n method: string;\n};\n\n/**\n * Options for generating tools\n */\nexport interface GenerateOptions {\n /**\n * Include only these operation IDs\n */\n includeOperations?: string[];\n\n /**\n * Exclude these operation IDs\n */\n excludeOperations?: string[];\n\n /**\n * Custom filter function\n */\n filterFn?: (operation: OperationWithContext) => boolean;\n\n /**\n * Naming strategy for resolving conflicts\n */\n namingStrategy?: NamingStrategy;\n\n /**\n * Preferred response status codes (in order of preference)\n * @default [200, 201, 204, 202, 203, 206]\n */\n preferredStatusCodes?: number[];\n\n /**\n * Whether to include deprecated operations\n * @default false\n */\n includeDeprecated?: boolean;\n\n /**\n * Whether to include all response codes in output schema\n * If false, only preferred status code is used\n * @default true\n */\n includeAllResponses?: boolean;\n\n /**\n * Maximum depth for dereferencing schemas\n * @default 10\n */\n maxSchemaDepth?: number;\n\n /**\n * Whether to include examples in schemas\n * @default false\n */\n includeExamples?: boolean;\n}\n\n/**\n * Naming strategy for resolving parameter conflicts\n */\nexport interface NamingStrategy {\n /**\n * Resolver function for parameter name conflicts\n * @param paramName - Original parameter name\n * @param location - Parameter location\n * @param index - Index of conflicting parameter (0-based)\n * @returns New parameter name\n */\n conflictResolver: (\n paramName: string,\n location: ParameterLocation,\n index: number\n ) => string;\n\n /**\n * Function to generate tool names\n * @param path - OpenAPI path\n * @param method - HTTP method\n * @param operationId - Operation ID if available\n * @returns Tool name\n */\n toolNameGenerator?: (\n path: string,\n method: HTTPMethod,\n operationId?: string\n ) => string;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /**\n * Whether the document is valid\n */\n valid: boolean;\n\n /**\n * Validation errors\n */\n errors?: ValidationErrorDetail[];\n\n /**\n * Validation warnings\n */\n warnings?: ValidationWarning[];\n}\n\n/**\n * Validation error detail\n */\nexport interface ValidationErrorDetail {\n /**\n * Error message\n */\n message: string;\n\n /**\n * Error path (JSON pointer)\n */\n path?: string;\n\n /**\n * Error code\n */\n code?: string;\n}\n\n/**\n * Validation warning\n */\nexport interface ValidationWarning {\n /**\n * Warning message\n */\n message: string;\n\n /**\n * Warning path (JSON pointer)\n */\n path?: string;\n\n /**\n * Warning code\n */\n code?: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;AAsDA,8CAEC;AAOD,sCAqFC;AAjGD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,GAAQ;IACxC,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,CAAC;AACzD,CAAC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,MAAsC;IAClE,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAiB,CAAC;IAC9C,CAAC;IAED,+DAA+D;IAC/D,2DAA2D;IAC3D,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEjF,MAAM,MAAM,GAA4B,EAAE,GAAG,IAAI,EAAE,CAAC;IAEpD,qCAAqC;IACrC,IAAI,OAAO,gBAAgB,KAAK,SAAS,EAAE,CAAC;QAC1C,IAAI,gBAAgB,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC9C,gEAAgE;YAChE,MAAM,CAAC,kBAAkB,CAAC,GAAG,OAAO,CAAC;QACvC,CAAC;aAAM,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YACjC,qDAAqD;YACrD,MAAM,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC;QAC9B,CAAC;QACD,qEAAqE;IACvE,CAAC;SAAM,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;QAC1C,6CAA6C;QAC7C,MAAM,CAAC,kBAAkB,CAAC,GAAG,gBAAgB,CAAC;QAC9C,IAAI,OAA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PI specification version 3.0.x or 3.1.x\n */\nexport type OpenAPIVersion = '3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0';\n\n/**\n * Unified OpenAPI Document type (supports both 3.0 and 3.1)\n */\nexport type OpenAPIDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\n/**\n * HTTP methods supported by OpenAPI\n */\nexport type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * Parameter location types\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'body';\n\n/**\n * Authentication types supported\n */\nexport type AuthType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect' | 'mutualTLS';\n\n// Re-export OpenAPI types for convenience\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type ResponsesObject = OpenAPIV3.ResponsesObject | OpenAPIV3_1.ResponsesObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type HeaderObject = OpenAPIV3.HeaderObject | OpenAPIV3_1.HeaderObject;\nexport type ExampleObject = OpenAPIV3.ExampleObject | OpenAPIV3_1.ExampleObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type PathsObject = OpenAPIV3.PathsObject | OpenAPIV3_1.PathsObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\nexport type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject | OpenAPIV3_1.SecuritySchemeObject;\nexport type ReferenceObject = OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;\nexport type TagObject = OpenAPIV3.TagObject | OpenAPIV3_1.TagObject;\nexport type ExternalDocumentationObject =\n | OpenAPIV3.ExternalDocumentationObject\n | OpenAPIV3_1.ExternalDocumentationObject;\nexport type ServerVariableObject = OpenAPIV3.ServerVariableObject | OpenAPIV3_1.ServerVariableObject;\nexport type EncodingObject = OpenAPIV3.EncodingObject | OpenAPIV3_1.EncodingObject;\nexport type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject | OpenAPIV3_1.SecurityRequirementObject;\nexport type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;\n\n/**\n * Helper to check if an object is a ReferenceObject\n */\nexport function isReferenceObject(obj: any): obj is ReferenceObject {\n return obj && typeof obj === 'object' && '$ref' in obj;\n}\n\n/**\n * Convert OpenAPI schema to JSONSchema7\n * Note: OpenAPI 3.0 uses a subset of JSON Schema Draft 4\n * OpenAPI 3.1 uses JSON Schema Draft 2020-12\n */\nexport function toJSONSchema7(schema: SchemaObject | ReferenceObject): JSONSchema7 {\n if (isReferenceObject(schema)) {\n return { $ref: schema.$ref } as JSONSchema7;\n }\n\n // Handle OpenAPI 3.0 boolean exclusiveMaximum/exclusiveMinimum\n // by converting them to JSON Schema Draft 7 numeric format\n const { exclusiveMaximum, exclusiveMinimum, maximum, minimum, ...rest } = schema;\n\n const result: Record<string, unknown> = { ...rest };\n\n // Handle exclusiveMaximum conversion\n if (typeof exclusiveMaximum === 'boolean') {\n if (exclusiveMaximum && maximum !== undefined) {\n // true + maximum present -> convert to numeric exclusiveMaximum\n result['exclusiveMaximum'] = maximum;\n } else if (maximum !== undefined) {\n // false or true without maximum -> keep maximum only\n result['maximum'] = maximum;\n }\n // Boolean exclusiveMaximum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMaximum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMaximum'] = exclusiveMaximum;\n if (maximum !== undefined) {\n result['maximum'] = maximum;\n }\n } else if (maximum !== undefined) {\n // No exclusiveMaximum, just maximum\n result['maximum'] = maximum;\n }\n\n // Handle exclusiveMinimum conversion\n if (typeof exclusiveMinimum === 'boolean') {\n if (exclusiveMinimum && minimum !== undefined) {\n // true + minimum present -> convert to numeric exclusiveMinimum\n result['exclusiveMinimum'] = minimum;\n } else if (minimum !== undefined) {\n // false or true without minimum -> keep minimum only\n result['minimum'] = minimum;\n }\n // Boolean exclusiveMinimum is never added (invalid in JSON Schema 7)\n } else if (exclusiveMinimum !== undefined) {\n // Already numeric (OpenAPI 3.1) - keep as is\n result['exclusiveMinimum'] = exclusiveMinimum;\n if (minimum !== undefined) {\n result['minimum'] = minimum;\n }\n } else if (minimum !== undefined) {\n // No exclusiveMinimum, just minimum\n result['minimum'] = minimum;\n }\n\n // Recursively convert nested schemas to ensure all nested schemas are valid JSONSchema7\n if (result['properties'] && typeof result['properties'] === 'object') {\n const props: Record<string, JSONSchema7> = {};\n for (const [key, value] of Object.entries(result['properties'] as Record<string, SchemaObject | ReferenceObject>)) {\n props[key] = toJSONSchema7(value);\n }\n result['properties'] = props;\n }\n\n if (result['items']) {\n if (Array.isArray(result['items'])) {\n result['items'] = (result['items'] as (SchemaObject | ReferenceObject)[]).map(toJSONSchema7);\n } else {\n result['items'] = toJSONSchema7(result['items'] as SchemaObject | ReferenceObject);\n }\n }\n\n if (result['additionalProperties'] && typeof result['additionalProperties'] === 'object') {\n result['additionalProperties'] = toJSONSchema7(result['additionalProperties'] as SchemaObject | ReferenceObject);\n }\n\n for (const key of ['allOf', 'anyOf', 'oneOf'] as const) {\n if (result[key] && Array.isArray(result[key])) {\n result[key] = (result[key] as (SchemaObject | ReferenceObject)[]).map(toJSONSchema7);\n }\n }\n\n if (result['not']) {\n result['not'] = toJSONSchema7(result['not'] as SchemaObject | ReferenceObject);\n }\n\n return result as JSONSchema7;\n}\n\n/**\n * Main MCP Tool definition generated from OpenAPI\n */\nexport interface McpOpenAPITool {\n /**\n * Unique tool name (from operationId or generated)\n */\n name: string;\n\n /**\n * Tool description (from operation summary/description)\n */\n description: string;\n\n /**\n * Combined input schema including all parameters\n * (path, query, header, cookie, body)\n */\n inputSchema: JSONSchema7;\n\n /**\n * Output schema based on response definitions\n * Can be a union of multiple status codes\n */\n outputSchema?: JSONSchema7;\n\n /**\n * Mapping from input schema properties to actual request parameters\n */\n mapper: ParameterMapper[];\n\n /**\n * Additional metadata about the tool\n */\n metadata: ToolMetadata;\n}\n\n/**\n * Maps input schema properties to their actual request locations\n */\nexport interface ParameterMapper {\n /**\n * Property name in the input schema\n */\n inputKey: string;\n\n /**\n * Where this parameter should be placed in the request\n */\n type: ParameterLocation;\n\n /**\n * Original parameter name (before conflict resolution)\n */\n key: string;\n\n /**\n * Whether this parameter is required\n */\n required?: boolean;\n\n /**\n * Parameter style (for path/query parameters)\n */\n style?: string;\n\n /**\n * Whether to explode arrays/objects\n */\n explode?: boolean;\n\n /**\n * Custom serialization info\n */\n serialization?: SerializationInfo;\n\n /**\n * Security scheme information (if this is an auth parameter)\n * This allows frameworks to resolve auth from context, env vars, etc.\n */\n security?: SecurityParameterInfo;\n}\n\n/**\n * Serialization information for complex parameters\n */\nexport interface SerializationInfo {\n /**\n * Content type for body parameters\n */\n contentType?: string;\n\n /**\n * Encoding rules\n */\n encoding?: Record<string, EncodingObject>;\n}\n\n/**\n * Security parameter information for framework-agnostic auth resolution\n */\nexport interface SecurityParameterInfo {\n /**\n * Security scheme name from OpenAPI (e.g., \"BearerAuth\")\n */\n scheme: string;\n\n /**\n * Security type (apiKey, http, oauth2, openIdConnect)\n */\n type: AuthType;\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Required OAuth2 scopes\n */\n scopes?: string[];\n\n /**\n * API key parameter name (for type: \"apiKey\")\n */\n apiKeyName?: string;\n\n /**\n * API key location (for type: \"apiKey\")\n */\n apiKeyIn?: 'query' | 'header' | 'cookie';\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Additional metadata about the generated tool\n */\nexport interface ToolMetadata {\n /**\n * Original OpenAPI path\n */\n path: string;\n\n /**\n * HTTP method\n */\n method: HTTPMethod;\n\n /**\n * Operation ID from OpenAPI\n */\n operationId?: string;\n\n /**\n * Tags from OpenAPI\n */\n tags?: string[];\n\n /**\n * Whether operation is deprecated\n */\n deprecated?: boolean;\n\n /**\n * Security requirements\n */\n security?: SecurityRequirement[];\n\n /**\n * Server information\n */\n servers?: ServerInfo[];\n\n /**\n * Response status codes included in output schema\n */\n responseStatusCodes?: number[];\n\n /**\n * External documentation\n */\n externalDocs?: ExternalDocumentationObject;\n}\n\n/**\n * Security requirement definition\n */\nexport interface SecurityRequirement {\n /**\n * Security scheme name\n */\n scheme: string;\n\n /**\n * Security type\n */\n type: AuthType;\n\n /**\n * Scopes required (for OAuth2/OpenID Connect)\n */\n scopes?: string[];\n\n /**\n * Parameter name (for API key)\n */\n name?: string;\n\n /**\n * Parameter location (for API key)\n */\n in?: 'query' | 'header' | 'cookie';\n\n /**\n * HTTP authentication scheme (for type: \"http\")\n * e.g., \"bearer\", \"basic\"\n */\n httpScheme?: string;\n\n /**\n * Bearer token format (e.g., \"JWT\")\n */\n bearerFormat?: string;\n\n /**\n * Description of the security scheme\n */\n description?: string;\n}\n\n/**\n * Server information\n */\nexport interface ServerInfo {\n /**\n * Server URL\n */\n url: string;\n\n /**\n * Server description\n */\n description?: string;\n\n /**\n * Server variables\n */\n variables?: Record<string, ServerVariableObject>;\n}\n\n/**\n * Options for loading OpenAPI specifications\n */\nexport interface LoadOptions {\n /**\n * Whether to dereference $refs in schemas\n * @default true\n */\n dereference?: boolean;\n\n /**\n * Base URL for API requests\n * Overrides servers in OpenAPI spec\n */\n baseUrl?: string;\n\n /**\n * Custom HTTP headers for loading from URL\n */\n headers?: Record<string, string>;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Whether to validate the OpenAPI document\n * @default true\n */\n validate?: boolean;\n\n /**\n * Whether to follow HTTP redirects\n * @default true\n */\n followRedirects?: boolean;\n}\n\n/**\n * Operation object with additional context for filtering\n */\nexport type OperationWithContext = OperationObject & {\n path: string;\n method: string;\n};\n\n/**\n * Options for generating tools\n */\nexport interface GenerateOptions {\n /**\n * Include only these operation IDs\n */\n includeOperations?: string[];\n\n /**\n * Exclude these operation IDs\n */\n excludeOperations?: string[];\n\n /**\n * Custom filter function\n */\n filterFn?: (operation: OperationWithContext) => boolean;\n\n /**\n * Naming strategy for resolving conflicts\n */\n namingStrategy?: NamingStrategy;\n\n /**\n * Preferred response status codes (in order of preference)\n * @default [200, 201, 204, 202, 203, 206]\n */\n preferredStatusCodes?: number[];\n\n /**\n * Whether to include deprecated operations\n * @default false\n */\n includeDeprecated?: boolean;\n\n /**\n * Whether to include all response codes in output schema\n * If false, only preferred status code is used\n * @default true\n */\n includeAllResponses?: boolean;\n\n /**\n * Maximum depth for dereferencing schemas\n * @default 10\n */\n maxSchemaDepth?: number;\n\n /**\n * Whether to include examples in schemas\n * @default false\n */\n includeExamples?: boolean;\n\n /**\n * Whether to include security requirements as input parameters\n * If false, security is only in mapper (frameworks resolve from context/env/etc.)\n * If true, security is added to inputSchema as explicit parameters\n * @default false\n */\n includeSecurityInInput?: boolean;\n}\n\n/**\n * Naming strategy for resolving parameter conflicts\n */\nexport interface NamingStrategy {\n /**\n * Resolver function for parameter name conflicts\n * @param paramName - Original parameter name\n * @param location - Parameter location\n * @param index - Index of conflicting parameter (0-based)\n * @returns New parameter name\n */\n conflictResolver: (paramName: string, location: ParameterLocation, index: number) => string;\n\n /**\n * Function to generate tool names\n * @param path - OpenAPI path\n * @param method - HTTP method\n * @param operationId - Operation ID if available\n * @returns Tool name\n */\n toolNameGenerator?: (path: string, method: HTTPMethod, operationId?: string) => string;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /**\n * Whether the document is valid\n */\n valid: boolean;\n\n /**\n * Validation errors\n */\n errors?: ValidationErrorDetail[];\n\n /**\n * Validation warnings\n */\n warnings?: ValidationWarning[];\n}\n\n/**\n * Validation error detail\n */\nexport interface ValidationErrorDetail {\n /**\n * Error message\n */\n message: string;\n\n /**\n * Error path (JSON pointer)\n */\n path?: string;\n\n /**\n * Error code\n */\n code?: string;\n}\n\n/**\n * Validation warning\n */\nexport interface ValidationWarning {\n /**\n * Warning message\n */\n message: string;\n\n /**\n * Warning path (JSON pointer)\n */\n path?: string;\n\n /**\n * Warning code\n */\n code?: string;\n}\n"]}
package/src/validator.js CHANGED
@@ -150,7 +150,9 @@ class Validator {
150
150
  }
151
151
  // Check for path parameters in path string
152
152
  const pathParams = path.match(/\{([^}]+)\}/g)?.map((p) => p.slice(1, -1)) ?? [];
153
- const definedPathParams = new Set(operation.parameters?.filter((p) => p.in === 'path').map((p) => p.name) ?? []);
153
+ const definedPathParams = new Set(operation.parameters
154
+ ?.filter((p) => p.in === 'path')
155
+ .map((p) => p.name) ?? []);
154
156
  for (const param of pathParams) {
155
157
  if (!definedPathParams.has(param)) {
156
158
  errors.push({