-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathparser.ts
More file actions
571 lines (501 loc) · 20.2 KB
/
Copy pathparser.ts
File metadata and controls
571 lines (501 loc) · 20.2 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'
import type { JSONSchema7 as IJsonSchema } from 'json-schema'
import type { ChatCompletionTool } from 'openai/resources/chat/completions'
import type { Tool } from '@anthropic-ai/sdk/resources/messages/messages'
type NewToolMethod = {
name: string
description: string
inputSchema: IJsonSchema & { type: 'object' }
returnSchema?: IJsonSchema
}
type FunctionParameters = {
type: 'object'
properties?: Record<string, unknown>
required?: string[]
[key: string]: unknown
}
export class OpenAPIToMCPConverter {
private schemaCache: Record<string, IJsonSchema> = {}
private nameCounter: number = 0
constructor(private openApiSpec: OpenAPIV3.Document | OpenAPIV3_1.Document) {}
/**
* Resolve a $ref reference to its schema in the openApiSpec.
* Returns the raw OpenAPI SchemaObject or null if not found.
*/
private internalResolveRef(ref: string, resolvedRefs: Set<string>): OpenAPIV3.SchemaObject | null {
if (!ref.startsWith('#/')) {
return null
}
if (resolvedRefs.has(ref)) {
return null
}
const parts = ref.replace(/^#\//, '').split('/')
let current: any = this.openApiSpec
for (const part of parts) {
current = current[part]
if (!current) return null
}
resolvedRefs.add(ref)
return current as OpenAPIV3.SchemaObject
}
/**
* Convert an OpenAPI schema (or reference) into a JSON Schema object.
* Uses caching and handles cycles by returning $ref nodes.
*/
convertOpenApiSchemaToJsonSchema(
schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject,
resolvedRefs: Set<string>,
resolveRefs: boolean = false,
): IJsonSchema {
if ('$ref' in schema) {
const ref = schema.$ref
if (!resolveRefs) {
if (ref.startsWith('#/components/schemas/')) {
return {
$ref: ref.replace(/^#\/components\/schemas\//, '#/$defs/'),
...('description' in schema ? { description: schema.description as string } : {}),
}
}
console.error(`Attempting to resolve ref ${ref} not found in components collection.`)
// deliberate fall through
}
// Create base schema with $ref and description if present
const refSchema: IJsonSchema = { $ref: ref }
if ('description' in schema && schema.description) {
refSchema.description = schema.description as string
}
// If already cached, return immediately with description
if (this.schemaCache[ref]) {
return this.schemaCache[ref]
}
const resolved = this.internalResolveRef(ref, resolvedRefs)
if (!resolved) {
// TODO: need extensive tests for this and we definitely need to handle the case of self references
console.error(`Failed to resolve ref ${ref}`)
return {
$ref: ref.replace(/^#\/components\/schemas\//, '#/$defs/'),
description: 'description' in schema ? ((schema.description as string) ?? '') : '',
}
} else {
const converted = this.convertOpenApiSchemaToJsonSchema(resolved, resolvedRefs, resolveRefs)
this.schemaCache[ref] = converted
return converted
}
}
// Handle inline schema
const result: IJsonSchema = {}
if (schema.type) {
result.type = schema.type as IJsonSchema['type']
}
// Convert binary format to uri-reference and enhance description
if (schema.format === 'binary') {
result.format = 'uri-reference'
const binaryDesc = 'absolute paths to local files'
result.description = schema.description ? `${schema.description} (${binaryDesc})` : binaryDesc
} else {
if (schema.format) {
result.format = schema.format
}
if (schema.description) {
result.description = schema.description
}
}
if (schema.enum) {
result.enum = schema.enum
}
// Handle const values (important for oneOf discriminators)
if ('const' in schema && schema.const !== undefined) {
result.const = schema.const as IJsonSchema['const']
}
if (schema.default !== undefined) {
result.default = schema.default
}
// Handle object properties
if (schema.type === 'object') {
result.type = 'object'
if (schema.properties) {
result.properties = {}
for (const [name, propSchema] of Object.entries(schema.properties)) {
result.properties[name] = this.convertOpenApiSchemaToJsonSchema(propSchema, resolvedRefs, resolveRefs)
}
}
if (schema.required) {
result.required = schema.required
}
if (schema.additionalProperties === true || schema.additionalProperties === undefined) {
result.additionalProperties = true
} else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
result.additionalProperties = this.convertOpenApiSchemaToJsonSchema(schema.additionalProperties, resolvedRefs, resolveRefs)
} else {
result.additionalProperties = false
}
}
// Handle arrays - ensure binary format conversion happens for array items too
if (schema.type === 'array' && schema.items) {
result.type = 'array'
result.items = this.convertOpenApiSchemaToJsonSchema(schema.items, resolvedRefs, resolveRefs)
}
// oneOf, anyOf, allOf
if (schema.oneOf) {
result.oneOf = schema.oneOf.map((s) => this.convertOpenApiSchemaToJsonSchema(s, resolvedRefs, resolveRefs))
}
if (schema.anyOf) {
result.anyOf = schema.anyOf.map((s) => this.convertOpenApiSchemaToJsonSchema(s, resolvedRefs, resolveRefs))
}
if (schema.allOf) {
result.allOf = schema.allOf.map((s) => this.convertOpenApiSchemaToJsonSchema(s, resolvedRefs, resolveRefs))
}
return result
}
convertToMCPTools(): {
tools: Record<string, { methods: NewToolMethod[] }>
openApiLookup: Record<string, OpenAPIV3.OperationObject & { method: string; path: string }>
zip: Record<string, { openApi: OpenAPIV3.OperationObject & { method: string; path: string }; mcp: NewToolMethod }>
} {
const apiName = 'API'
const openApiLookup: Record<string, OpenAPIV3.OperationObject & { method: string; path: string }> = {}
const tools: Record<string, { methods: NewToolMethod[] }> = {
[apiName]: { methods: [] },
}
const zip: Record<string, { openApi: OpenAPIV3.OperationObject & { method: string; path: string }; mcp: NewToolMethod }> = {}
for (const [path, pathItem] of Object.entries(this.openApiSpec.paths || {})) {
if (!pathItem) continue
for (const [method, operation] of Object.entries(pathItem)) {
if (!this.isOperation(method, operation)) continue
const mcpMethod = this.convertOperationToMCPMethod(operation, method, path)
if (mcpMethod) {
const uniqueName = this.ensureUniqueName(mcpMethod.name)
mcpMethod.name = uniqueName
// Apply description prefix to the already-built description (which includes error responses)
mcpMethod.description = this.getDescription(mcpMethod.description)
tools[apiName]!.methods.push(mcpMethod)
openApiLookup[apiName + '-' + uniqueName] = { ...operation, method, path }
zip[apiName + '-' + uniqueName] = { openApi: { ...operation, method, path }, mcp: mcpMethod }
}
}
}
return { tools, openApiLookup, zip }
}
/**
* Convert the OpenAPI spec to OpenAI's ChatCompletionTool format
*/
convertToOpenAITools(): ChatCompletionTool[] {
const tools: ChatCompletionTool[] = []
for (const [path, pathItem] of Object.entries(this.openApiSpec.paths || {})) {
if (!pathItem) continue
for (const [method, operation] of Object.entries(pathItem)) {
if (!this.isOperation(method, operation)) continue
const parameters = this.convertOperationToJsonSchema(operation, method, path)
const tool: ChatCompletionTool = {
type: 'function',
function: {
name: operation.operationId!,
description: this.getDescription(operation.summary || operation.description || ''),
parameters: parameters as FunctionParameters,
},
}
tools.push(tool)
}
}
return tools
}
/**
* Convert the OpenAPI spec to Anthropic's Tool format
*/
convertToAnthropicTools(): Tool[] {
const tools: Tool[] = []
for (const [path, pathItem] of Object.entries(this.openApiSpec.paths || {})) {
if (!pathItem) continue
for (const [method, operation] of Object.entries(pathItem)) {
if (!this.isOperation(method, operation)) continue
const parameters = this.convertOperationToJsonSchema(operation, method, path)
const tool: Tool = {
name: operation.operationId!,
description: this.getDescription(operation.summary || operation.description || ''),
input_schema: parameters as Tool['input_schema'],
}
tools.push(tool)
}
}
return tools
}
private convertComponentsToJsonSchema(): Record<string, IJsonSchema> {
const components = this.openApiSpec.components || {}
const schema: Record<string, IJsonSchema> = {}
for (const [key, value] of Object.entries(components.schemas || {})) {
schema[key] = this.convertOpenApiSchemaToJsonSchema(value, new Set())
}
return schema
}
/**
* Helper method to convert an operation to a JSON Schema for parameters
*/
private convertOperationToJsonSchema(
operation: OpenAPIV3.OperationObject,
method: string,
path: string,
): IJsonSchema & { type: 'object' } {
const schema: IJsonSchema & { type: 'object' } = {
type: 'object',
properties: {},
required: [],
$defs: this.convertComponentsToJsonSchema(),
}
// Handle parameters (path, query, cookie — skip header params, they're sent automatically)
if (operation.parameters) {
for (const param of operation.parameters) {
const paramObj = this.resolveParameter(param)
if (paramObj && paramObj.in === 'header') continue
if (paramObj && paramObj.schema) {
const paramSchema = this.convertOpenApiSchemaToJsonSchema(paramObj.schema, new Set())
// Merge parameter-level description if available
if (paramObj.description) {
paramSchema.description = paramObj.description
}
schema.properties![paramObj.name] = paramSchema
if (paramObj.required) {
schema.required!.push(paramObj.name)
}
}
}
}
// Handle requestBody
if (operation.requestBody) {
const bodyObj = this.resolveRequestBody(operation.requestBody)
if (bodyObj?.content) {
if (bodyObj.content['application/json']?.schema) {
const bodySchema = this.convertOpenApiSchemaToJsonSchema(bodyObj.content['application/json'].schema, new Set())
if (bodySchema.type === 'object' && bodySchema.properties) {
for (const [name, propSchema] of Object.entries(bodySchema.properties)) {
schema.properties![name] = propSchema
}
if (bodySchema.required) {
schema.required!.push(...bodySchema.required)
}
}
}
}
}
return schema
}
private isOperation(method: string, operation: any): operation is OpenAPIV3.OperationObject {
return ['get', 'post', 'put', 'delete', 'patch'].includes(method.toLowerCase())
}
private isParameterObject(param: OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject): param is OpenAPIV3.ParameterObject {
return !('$ref' in param)
}
private isRequestBodyObject(body: OpenAPIV3.RequestBodyObject | OpenAPIV3.ReferenceObject): body is OpenAPIV3.RequestBodyObject {
return !('$ref' in body)
}
private resolveParameter(param: OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject): OpenAPIV3.ParameterObject | null {
if (this.isParameterObject(param)) {
return param
} else {
const resolved = this.internalResolveRef(param.$ref, new Set())
if (resolved && (resolved as OpenAPIV3.ParameterObject).name) {
return resolved as OpenAPIV3.ParameterObject
}
}
return null
}
private resolveRequestBody(body: OpenAPIV3.RequestBodyObject | OpenAPIV3.ReferenceObject): OpenAPIV3.RequestBodyObject | null {
if (this.isRequestBodyObject(body)) {
return body
} else {
const resolved = this.internalResolveRef(body.$ref, new Set())
if (resolved) {
return resolved as OpenAPIV3.RequestBodyObject
}
}
return null
}
private resolveResponse(response: OpenAPIV3.ResponseObject | OpenAPIV3.ReferenceObject): OpenAPIV3.ResponseObject | null {
if ('$ref' in response) {
const resolved = this.internalResolveRef(response.$ref, new Set())
if (resolved) {
return resolved as OpenAPIV3.ResponseObject
} else {
return null
}
}
return response
}
private convertOperationToMCPMethod(operation: OpenAPIV3.OperationObject, method: string, path: string): NewToolMethod | null {
if (!operation.operationId) {
console.warn(`Operation without operationId at ${method} ${path}`)
return null
}
const methodName = operation.operationId
const inputSchema: IJsonSchema & { type: 'object' } = {
$defs: this.convertComponentsToJsonSchema(),
type: 'object',
properties: {},
required: [],
}
// Handle parameters (path, query, cookie — skip header params, they're sent automatically)
if (operation.parameters) {
for (const param of operation.parameters) {
const paramObj = this.resolveParameter(param)
if (paramObj && paramObj.in === 'header') continue
if (paramObj && paramObj.schema) {
const schema = this.convertOpenApiSchemaToJsonSchema(paramObj.schema, new Set(), false)
// Merge parameter-level description if available
if (paramObj.description) {
schema.description = paramObj.description
}
inputSchema.properties![paramObj.name] = this.withStringFallback(schema)
if (paramObj.required) {
inputSchema.required!.push(paramObj.name)
}
}
}
}
// Handle requestBody
if (operation.requestBody) {
const bodyObj = this.resolveRequestBody(operation.requestBody)
if (bodyObj?.content) {
// Handle multipart/form-data for file uploads
// We convert the multipart/form-data schema to a JSON schema and we require
// that the user passes in a string for each file that points to the local file
if (bodyObj.content['multipart/form-data']?.schema) {
const formSchema = this.convertOpenApiSchemaToJsonSchema(bodyObj.content['multipart/form-data'].schema, new Set(), false)
if (formSchema.type === 'object' && formSchema.properties) {
for (const [name, propSchema] of Object.entries(formSchema.properties)) {
inputSchema.properties![name] = this.withStringFallback(propSchema as IJsonSchema)
}
if (formSchema.required) {
inputSchema.required!.push(...formSchema.required!)
}
}
}
// Handle application/json
else if (bodyObj.content['application/json']?.schema) {
const bodySchema = this.convertOpenApiSchemaToJsonSchema(bodyObj.content['application/json'].schema, new Set(), false)
// Merge body schema into the inputSchema's properties
if (bodySchema.type === 'object' && bodySchema.properties) {
for (const [name, propSchema] of Object.entries(bodySchema.properties)) {
inputSchema.properties![name] = this.withStringFallback(propSchema as IJsonSchema)
}
if (bodySchema.required) {
inputSchema.required!.push(...bodySchema.required!)
}
} else {
// If the request body is not an object, just put it under "body"
inputSchema.properties!['body'] = this.withStringFallback(bodySchema)
inputSchema.required!.push('body')
}
}
}
}
// Build description including error responses
let description = operation.summary || operation.description || ''
if (operation.responses) {
const errorResponses = Object.entries(operation.responses)
.filter(([code]) => code.startsWith('4') || code.startsWith('5'))
.map(([code, response]) => {
const responseObj = this.resolveResponse(response)
let errorDesc = responseObj?.description || ''
return `${code}: ${errorDesc}`
})
if (errorResponses.length > 0) {
description += '\nError Responses:\n' + errorResponses.join('\n')
}
}
// Extract return type (response schema)
const returnSchema = this.extractResponseType(operation.responses)
// Generate Zod schema from input schema
try {
// const zodSchemaStr = jsonSchemaToZod(inputSchema, { module: "cjs" })
// console.log(zodSchemaStr)
// // Execute the function with the zod instance
// const zodSchema = eval(zodSchemaStr) as z.ZodType
return {
name: methodName,
description,
inputSchema,
...(returnSchema ? { returnSchema } : {}),
}
} catch (error) {
console.warn(`Failed to generate Zod schema for ${methodName}:`, error)
// Fallback to a basic object schema
return {
name: methodName,
description,
inputSchema,
...(returnSchema ? { returnSchema } : {}),
}
}
}
/**
* Wraps a complex schema to also accept a JSON-encoded string.
* Handles the case where MCP clients (e.g. Claude Desktop) double-serialize
* nested object parameters, sending them as JSON strings instead of objects.
* The actual string→object conversion is handled by deserializeParams() in proxy.ts.
* @see https://github.com/makenotion/notion-mcp-server/issues/208
*/
private withStringFallback(schema: IJsonSchema): IJsonSchema {
const isComplex =
schema.type === 'object' ||
'$ref' in schema ||
'anyOf' in schema ||
'oneOf' in schema ||
'allOf' in schema
if (isComplex) {
return { anyOf: [schema, { type: 'string' }] }
}
if (schema.type === 'array' && schema.items) {
return {
...schema,
items: {
anyOf: [
schema.items as IJsonSchema,
{ type: 'string' },
{ type: 'object', additionalProperties: true },
],
},
}
}
return schema
}
private extractResponseType(responses: OpenAPIV3.ResponsesObject | undefined): IJsonSchema | null {
// Look for a success response
const successResponse = responses?.['200'] || responses?.['201'] || responses?.['202'] || responses?.['204']
if (!successResponse) return null
const responseObj = this.resolveResponse(successResponse)
if (!responseObj || !responseObj.content) return null
if (responseObj.content['application/json']?.schema) {
const returnSchema = this.convertOpenApiSchemaToJsonSchema(responseObj.content['application/json'].schema, new Set(), false)
returnSchema['$defs'] = this.convertComponentsToJsonSchema()
// Preserve the response description if available and not already set
if (responseObj.description && !returnSchema.description) {
returnSchema.description = responseObj.description
}
return returnSchema
}
// If no JSON response, fallback to a generic string or known formats
if (responseObj.content['image/png'] || responseObj.content['image/jpeg']) {
return { type: 'string', format: 'binary', description: responseObj.description || '' }
}
// Fallback
return { type: 'string', description: responseObj.description || '' }
}
private ensureUniqueName(name: string): string {
if (name.length <= 64) {
return name
}
const truncatedName = name.slice(0, 64 - 5) // Reserve space for suffix
const uniqueSuffix = this.generateUniqueSuffix()
return `${truncatedName}-${uniqueSuffix}`
}
private generateUniqueSuffix(): string {
this.nameCounter += 1
return this.nameCounter.toString().padStart(4, '0')
}
private getDescription(description: string): string {
// Only add "Notion | " prefix for the Notion API
if (this.openApiSpec.info.title === 'Notion API') {
return "Notion | " + description
}
return description
}
}