-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathopenapi.ts
More file actions
322 lines (286 loc) · 9.74 KB
/
Copy pathopenapi.ts
File metadata and controls
322 lines (286 loc) · 9.74 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
import { z } from 'zod'
/**
* Minimal shape of an OpenAPI operation, as stored in our pre-processed spec.
*/
export interface OperationInfo {
summary?: string
description?: string
tags?: string[]
parameters?: Array<{
name: string
in: string
required?: boolean
schema?: unknown
description?: string
}>
requestBody?: {
required?: boolean
content?: Record<string, { schema?: unknown }>
}
responses?: Record<string, unknown>
}
/**
* TypeScript declarations describing the `spec` object exposed to the `search`
* tool's sandboxed code. Inlined into the search tool description.
*/
export const SPEC_TYPES = `
interface OperationInfo {
summary?: string;
description?: string;
tags?: string[];
parameters?: Array<{ name: string; in: string; required?: boolean; schema?: unknown; description?: string }>;
requestBody?: { required?: boolean; content?: Record<string, { schema?: unknown }> };
responses?: Record<string, { description?: string; content?: Record<string, { schema?: unknown }> }>;
}
interface PathItem {
get?: OperationInfo;
post?: OperationInfo;
put?: OperationInfo;
patch?: OperationInfo;
delete?: OperationInfo;
}
declare const spec: {
paths: Record<string, PathItem>;
};
`
/**
* Convert an OpenAPI path + method into a tool name.
* e.g. GET /accounts/{account_id}/workers/scripts → get_accounts_workers_scripts
*/
export function pathToToolName(method: string, path: string): string {
let cleaned = path
// Check if path ends with a {param} — keep it for disambiguation
const trailingParam = cleaned.match(/\/\{([^}]+)\}$/)
const suffix = trailingParam ? `_by_${trailingParam[1]}` : ''
const name =
method.toLowerCase() +
'_' +
cleaned
.replace(/^\//, '')
.replace(/\/\{[^}]+\}/g, '') // strip all {param} segments
.replace(/\//g, '_')
.replace(/[^a-z0-9_]/gi, '')
.replace(/_+/g, '_')
.replace(/_$/, '') +
suffix
// MCP spec: tool names SHOULD be between 1 and 128 characters
return name.length > 128 ? name.slice(0, 128).replace(/_$/, '') : name
}
const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete'] as const
export type HttpMethod = (typeof HTTP_METHODS)[number]
export type JsonObjectSchema = {
$schema?: string
type: 'object'
properties: Record<string, { type: 'string'; description: string }>
required?: string[]
}
/**
* Self-contained non-Code-Mode artifact entry. The protocol fields feed
* `tools/list`; routing fields feed the registered `tools/call` handler.
*/
export interface NonCodemodeTool {
name: string
description: string
inputSchema: JsonObjectSchema
execution: { taskSupport: 'forbidden' }
method: HttpMethod
path: string
queryParams: string[]
headerParams: Array<{ name: string; key: string }>
}
interface NonCodemodeOperation {
toolName: string
description: string
method: HttpMethod
path: string
operation: OperationInfo
}
function listNonCodemodeOperations(
paths: Record<string, Record<string, OperationInfo>>
): NonCodemodeOperation[] {
const operations: NonCodemodeOperation[] = []
const registeredNames = new Set<string>()
for (const [path, pathItem] of Object.entries(paths)) {
for (const method of HTTP_METHODS) {
const operation = pathItem[method]
if (!operation) continue
let toolName = pathToToolName(method, path)
// Deduplicate if truncation caused a collision
if (registeredNames.has(toolName)) {
let i = 2
let candidate: string
do {
const suffixStr = `_${i}`
const maxBase = 128 - suffixStr.length
const base =
toolName.length > maxBase ? toolName.slice(0, maxBase).replace(/_$/, '') : toolName
candidate = `${base}${suffixStr}`
i++
} while (registeredNames.has(candidate))
toolName = candidate
}
registeredNames.add(toolName)
const description =
`${method.toUpperCase()} ${path}` +
(operation.summary ? `\n\n${operation.summary}` : '') +
(operation.description ? `\n\n${operation.description}` : '')
operations.push({ toolName, description, method, path, operation })
}
}
return operations
}
/**
* Build the JSON-serializable artifact in the scheduled handler. This moves the
* full spec walk, name de-duplication, descriptions, routing metadata and wire
* JSON Schema out of the request path.
*/
export function buildNonCodemodeTools(
paths: Record<string, Record<string, OperationInfo>>
): NonCodemodeTool[] {
return listNonCodemodeOperations(paths).map(
({ toolName, description, method, path, operation }) => ({
name: toolName,
description,
inputSchema: buildJsonInputSchema(operation, path),
execution: { taskSupport: 'forbidden' },
method,
path,
queryParams: (operation.parameters ?? [])
.filter((parameter) => parameter.in === 'query')
.map((parameter) => parameter.name),
headerParams: (operation.parameters ?? [])
.filter((parameter) => parameter.in === 'header')
.map((parameter) => ({
name: parameter.name,
key: `header_${parameter.name.toLowerCase().replace(/-/g, '_')}`
}))
})
)
}
/** Rehydrate the small Zod shape required by the SDK's tools/call validation. */
export function zodInputSchemaFromJson(
inputSchema: JsonObjectSchema
): Record<string, z.ZodTypeAny> {
const required = new Set(inputSchema.required ?? [])
return Object.fromEntries(
Object.entries(inputSchema.properties).map(([name, property]) => {
const schema = z.string().describe(property.description)
return [name, required.has(name) ? schema : schema.optional()]
})
)
}
function buildJsonInputSchema(operation: OperationInfo, path: string): JsonObjectSchema {
const properties: JsonObjectSchema['properties'] = {}
const required = new Set<string>()
const pathParams = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1])
for (const name of pathParams) {
const parameter = operation.parameters?.find((item) => item.name === name && item.in === 'path')
properties[name] = {
type: 'string',
description: parameter?.description || `Path parameter: ${name}`
}
required.add(name)
}
for (const parameter of operation.parameters ?? []) {
if (parameter.in === 'query') {
properties[parameter.name] = {
type: 'string',
description: parameter.description || parameter.name
}
if (parameter.required) required.add(parameter.name)
}
if (parameter.in === 'header') {
const key = `header_${parameter.name.toLowerCase().replace(/-/g, '_')}`
properties[key] = {
type: 'string',
description: `Header: ${parameter.name}${parameter.description ? ` — ${parameter.description}` : ''}`
}
if (parameter.required) required.add(key)
}
}
if (operation.requestBody) {
properties['body'] = { type: 'string', description: 'Request body as string' }
const contentTypes = Object.keys(operation.requestBody.content ?? {})
if (contentTypes.some((contentType) => !contentType.includes('application/json'))) {
properties['content_type'] = {
type: 'string',
description: `Content-Type header. Supported: ${contentTypes.join(', ')}`
}
}
}
return {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties,
...(required.size > 0 ? { required: [...required] } : {})
}
}
/**
* Build a Zod input schema from OpenAPI operation parameters and requestBody.
*/
export function buildInputSchema(
operation: OperationInfo,
path: string
): Record<string, z.ZodTypeAny> {
const schema: Record<string, z.ZodTypeAny> = {}
// Extract path parameters from the path template
const pathParams = [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1])
// Add path parameters
for (const paramName of pathParams) {
const paramSpec = operation.parameters?.find(
(p: { name: string; in: string }) => p.name === paramName && p.in === 'path'
)
const desc = paramSpec?.description || `Path parameter: ${paramName}`
schema[paramName] = z.string().describe(desc)
}
// Add query parameters
if (operation.parameters) {
for (const param of operation.parameters) {
if (param.in === 'query') {
const field = param.required
? z.string().describe(param.description || param.name)
: z
.string()
.optional()
.describe(param.description || param.name)
schema[param.name] = field
}
}
}
// Add header parameters (e.g., If-Match for ETags)
if (operation.parameters) {
for (const param of operation.parameters) {
if (param.in === 'header') {
const headerKey = `header_${param.name.toLowerCase().replace(/-/g, '_')}`
const field = param.required
? z
.string()
.describe(
`Header: ${param.name}${param.description ? ` — ${param.description}` : ''}`
)
: z
.string()
.optional()
.describe(
`Header: ${param.name}${param.description ? ` — ${param.description}` : ''}`
)
schema[headerKey] = field
}
}
}
// Add body and content_type params if requestBody exists
if (operation.requestBody) {
const contentTypes = operation.requestBody.content
? Object.keys(operation.requestBody.content)
: []
const hasNonJson = contentTypes.some((ct) => !ct.includes('application/json'))
schema['body'] = z.string().optional().describe('Request body as string')
if (hasNonJson) {
schema['content_type'] = z
.string()
.optional()
.describe(`Content-Type header. Supported: ${contentTypes.join(', ')}`)
}
}
return schema
}