-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathcodegen.ts
More file actions
179 lines (148 loc) · 5.78 KB
/
Copy pathcodegen.ts
File metadata and controls
179 lines (148 loc) · 5.78 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
import fs from 'fs';
import { jsonSchemaToZod } from 'json-schema-to-zod';
import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
import path from 'path';
import prettier from 'prettier';
import { ParsedTool, parseOpenApi, ParseOpenApiOpts } from './parser';
type IsActionsEnabledOpt = Array<string> | ((actionName: string) => boolean);
type ActionConfig = Partial<{
title: string;
description: string;
normalizer: (args: any) => any;
/**
* Explicit MCP annotation overrides. When set, they beat the values derived
* from the HTTP method (e.g. a POST action that is actually idempotent can
* set `idempotentHint: true`).
*/
readOnlyHint: boolean;
destructiveHint: boolean;
idempotentHint: boolean;
openWorldHint: boolean;
}>;
const ANNOTATION_HINT_KEYS = [
'readOnlyHint',
'destructiveHint',
'idempotentHint',
'openWorldHint',
] as const;
const isActionsEnabled = (isActionsEnabledOpt: IsActionsEnabledOpt, actionName: string) => {
if (typeof isActionsEnabledOpt === 'function') {
return isActionsEnabledOpt(actionName);
}
return isActionsEnabledOpt.includes(actionName);
};
const generateToolInputFromParsedTool = (tool: ParsedTool) => {
const mergedSchema = JSON.parse(JSON.stringify(tool.inputSchema));
mergedSchema.properties = {
...mergedSchema.properties,
...tool.pathParamsSchema?.properties,
...tool.queryParamsSchema?.properties,
};
mergedSchema.required = [
...mergedSchema.required,
...(tool.pathParamsSchema?.required ?? []),
...(tool.queryParamsSchema?.required ?? []),
];
return `${jsonSchemaToZod(mergedSchema)}.shape`;
};
type CodegenOpts = {
path?: string;
document: OpenAPIV3_1.Document | OpenAPIV3.Document | OpenAPIV2.Document;
isActionsEnabled?: IsActionsEnabledOpt;
actions?: Record<string, ActionConfig>;
/**
* Name of the generated setup function. Defaults to `setupTools`. Override it
* (e.g. `setupToolsV2`) so a second generated tool set can be imported alongside
* the first without an export-name collision.
*/
exportName?: string;
/**
* Explicit tool-name overrides keyed by `"<lowercase-method> <path>"` — see
* `ParseOpenApiOpts.nameOverrides`. Use for operations without `operationId`
* whose path-derived names would collide (REST siblings like `GET /webhooks`
* and `GET /webhooks/{id}`).
*/
nameOverrides?: ParseOpenApiOpts['nameOverrides'];
};
export const codegen = async (opts: CodegenOpts) => {
const { document, path: outputPath } = opts;
const exportName = opts.exportName ?? 'setupTools';
const tools = parseOpenApi(document.paths ?? {}, { nameOverrides: opts.nameOverrides });
const runtime = fs.readFileSync(path.join(import.meta.dirname, 'runtime.ts'), 'utf8');
let output: string = `
/**
* This file is auto-generated by yarn generate:mcp-tools
* DO NOT EDIT THIS FILE MANUALLY
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
${runtime}\n
export const ${exportName} = (server: McpServer, opts: OpenAPIToolRuntimeConfigOpts) => {
const config = new OpenAPIToolRuntimeConfig(opts);
`;
tools.forEach((tool) => {
if (opts.isActionsEnabled && !isActionsEnabled(opts.isActionsEnabled, tool.name)) {
return;
}
// Derive MCP tool annotations from the HTTP method: GET/HEAD are read-only,
// DELETE is destructive, GET/HEAD/PUT/DELETE are idempotent per HTTP
// semantics (POST is not). openWorldHint is always false: this server only
// talks to the Taskade API — a closed world. A human-friendly title and
// explicit hint overrides can be supplied via opts.actions.
const method = tool.method.toUpperCase();
const annotations: Record<string, any> = {
readOnlyHint: method === 'GET' || method === 'HEAD',
destructiveHint: method === 'DELETE',
idempotentHint: ['GET', 'HEAD', 'PUT', 'DELETE'].includes(method),
openWorldHint: false,
};
const actionConfig = opts.actions?.[tool.name];
// Explicit per-action overrides beat derived values. Undefined-checked so
// an explicit `false` override wins too.
for (const hint of ANNOTATION_HINT_KEYS) {
const override = actionConfig?.[hint];
if (override !== undefined) {
annotations[hint] = override;
}
}
const actionTitle = actionConfig?.title;
if (actionTitle) {
annotations.title = actionTitle;
}
const description = actionConfig?.description ?? tool.description;
const toolArgs = [`"${tool.name}"`, `"${description}"`, generateToolInputFromParsedTool(tool)];
// annotations always carry the derived hint set, so always include them
toolArgs.push(JSON.stringify(annotations));
toolArgs.push(`async (args) => {
return await config.executeToolCall({
name: "${tool.name}",
path: "${tool.path}",
method: "${tool.method.toUpperCase()}",
input: args,
pathParamKeys: ${
tool.pathParamsSchema
? `[${Object.keys(tool.pathParamsSchema.properties ?? {})
.map((r) => `"${r}"`)
.join(',')}]`
: '[]'
},
queryParamKeys: ${
tool.queryParamsSchema
? `[${Object.keys(tool.queryParamsSchema.properties ?? {})
.map((r) => `"${r}"`)
.join(',')}]`
: '[]'
},
});
}`);
output += `server.tool(${toolArgs.join(',')});\n`;
});
output += `
}
`;
const formattedOutput = await prettier.format(output, { parser: 'typescript' });
if (outputPath) {
fs.writeFileSync(outputPath, formattedOutput);
}
return formattedOutput;
};