-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathserver-code.ts
More file actions
289 lines (261 loc) · 8.39 KB
/
server-code.ts
File metadata and controls
289 lines (261 loc) · 8.39 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
import { OpenAPIV3 } from 'openapi-types';
import { CliOptions } from '../types/index.js';
import { extractToolsFromApi } from '../parser/extract-tools.js';
import { determineBaseUrl } from '../utils/index.js';
import {
generateToolDefinitionMap,
generateCallToolHandler,
generateListToolsHandler,
} from '../utils/code-gen.js';
import { generateExecuteApiToolFunction } from '../utils/security.js';
/**
* Generates MCPcat tracking code based on options
*/
function generateMcpcatTracking(options: CliOptions): string {
if (!options.withMcpcat && !options.withOtel) {
return '';
}
let trackingCode = '\n// MCPcat Product analytics and OpenTelemetry exporters\n';
if (options.withMcpcat && options.withOtel) {
// Both flags enabled
trackingCode += `mcpcat.track(server, process.env.MCPCAT_PROJECT_ID || null, {
exporters: {
otlp: {
type: "otlp",
endpoint: process.env.OTLP_ENDPOINT || "http://localhost:4318/v1/traces"
}
}
});`;
} else if (options.withMcpcat) {
// Only MCPcat enabled
trackingCode += `mcpcat.track(server, process.env.MCPCAT_PROJECT_ID || null);`;
} else if (options.withOtel) {
// Only OTEL enabled
trackingCode += `mcpcat.track(server, null, {
enableToolCallContext: false,
enableReportMissing: false,
exporters: {
otlp: {
type: "otlp",
endpoint: process.env.OTLP_ENDPOINT || "http://localhost:4318/v1/traces"
}
}
});`;
}
return trackingCode + '\n';
}
/**
* Generates the TypeScript code for the MCP server
*
* @param api OpenAPI document
* @param options CLI options
* @param serverName Server name
* @param serverVersion Server version
* @returns Generated TypeScript code
*/
export function generateMcpServerCode(
api: OpenAPIV3.Document,
options: CliOptions,
serverName: string,
serverVersion: string
): string {
// Extract tools from API
const tools = extractToolsFromApi(api, options.defaultInclude ?? true);
// Determine base URL
const determinedBaseUrl = determineBaseUrl(api, options.baseUrl);
// Generate code for tool definition map
const toolDefinitionMapCode = generateToolDefinitionMap(tools, api.components?.securitySchemes);
// Generate code for API tool execution
const executeApiToolFunctionCode = generateExecuteApiToolFunction(
api.components?.securitySchemes
);
// Generate code for request handlers
const callToolHandlerCode = generateCallToolHandler();
const listToolsHandlerCode = generateListToolsHandler();
// Determine which transport to include
let transportImport = '';
let transportCode = '';
switch (options.transport) {
case 'web':
transportImport = `\nimport { setupWebServer } from "./web-server.js";`;
transportCode = `// Set up Web Server transport
try {
await setupWebServer(server, ${options.port || 3000});
} catch (error) {
console.error("Error setting up web server:", error);
process.exit(1);
}`;
break;
case 'streamable-http':
transportImport = `\nimport { setupStreamableHttpServer } from "./streamable-http.js";`;
transportCode = `// Set up StreamableHTTP transport
try {
await setupStreamableHttpServer(server, ${options.port || 3000});
} catch (error) {
console.error("Error setting up StreamableHTTP server:", error);
process.exit(1);
}`;
break;
default: // stdio
transportImport = '';
transportCode = `// Set up stdio transport
try {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(\`\${SERVER_NAME} MCP Server (v\${SERVER_VERSION}) running on stdio\${API_BASE_URL ? \`, proxying API at \${API_BASE_URL}\` : ''}\`);
} catch (error) {
console.error("Error during server startup:", error);
process.exit(1);
}`;
break;
}
let mcpcatImport = '';
if (options.withMcpcat || options.withOtel) {
mcpcatImport = `import * as mcpcat from "mcpcat";`;
}
// Generate the full server code
return `#!/usr/bin/env node
/**
* MCP Server generated from OpenAPI spec for ${serverName} v${serverVersion}
* Generated on: ${new Date().toISOString()}
*/
// Load environment variables from .env file
import dotenv from 'dotenv';
dotenv.config();
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
type Tool,
type CallToolResult,
type CallToolRequest
} from "@modelcontextprotocol/sdk/types.js";${transportImport}
${mcpcatImport}
import { z, ZodError } from 'zod';
import { jsonSchemaToZod } from 'json-schema-to-zod';
import axios, { type AxiosRequestConfig, type AxiosError } from 'axios';
/**
* Type definition for JSON objects
*/
type JsonObject = Record<string, any>;
/**
* Interface for MCP Tool Definition
*/
interface McpToolDefinition {
name: string;
description: string;
inputSchema: any;
method: string;
pathTemplate: string;
executionParameters: { name: string, in: string }[];
requestBodyContentType?: string;
securityRequirements: any[];
}
/**
* Server configuration
*/
export const SERVER_NAME = "${serverName}";
export const SERVER_VERSION = "${serverVersion}";
export const API_BASE_URL = "${determinedBaseUrl || ''}";
/**
* MCP Server instance
*/
const server = new Server(
{ name: SERVER_NAME, version: SERVER_VERSION },
{ capabilities: { tools: {} } }
);
/**
* Map of tool definitions by name
*/
const toolDefinitionMap: Map<string, McpToolDefinition> = new Map([
${toolDefinitionMapCode}
]);
/**
* Security schemes from the OpenAPI spec
*/
const securitySchemes = ${JSON.stringify(api.components?.securitySchemes || {}, null, 2).replace(/^/gm, ' ')};
${listToolsHandlerCode}
${callToolHandlerCode}
${executeApiToolFunctionCode}
${generateMcpcatTracking(options)}
/**
* Main function to start the server
*/
async function main() {
${transportCode}
}
/**
* Cleanup function for graceful shutdown
*/
async function cleanup() {
console.error("Shutting down MCP server...");
process.exit(0);
}
// Register signal handlers
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
// Start the server
main().catch((error) => {
console.error("Fatal error in main execution:", error);
process.exit(1);
});
/**
* Formats API errors for better readability
*
* @param error Axios error
* @returns Formatted error message
*/
function formatApiError(error: AxiosError): string {
let message = 'API request failed.';
if (error.response) {
message = \`API Error: Status \${error.response.status} (\${error.response.statusText || 'Status text not available'}). \`;
const responseData = error.response.data;
const MAX_LEN = 200;
if (typeof responseData === 'string') {
message += \`Response: \${responseData.substring(0, MAX_LEN)}\${responseData.length > MAX_LEN ? '...' : ''}\`;
}
else if (responseData) {
try {
const jsonString = JSON.stringify(responseData);
message += \`Response: \${jsonString.substring(0, MAX_LEN)}\${jsonString.length > MAX_LEN ? '...' : ''}\`;
} catch {
message += 'Response: [Could not serialize data]';
}
}
else {
message += 'No response body received.';
}
} else if (error.request) {
message = 'API Network Error: No response received from server.';
if (error.code) message += \` (Code: \${error.code})\`;
} else {
message += \`API Request Setup Error: \${error.message}\`;
}
return message;
}
/**
* Converts a JSON Schema to a Zod schema for runtime validation
*
* @param jsonSchema JSON Schema
* @param toolName Tool name for error reporting
* @returns Zod schema
*/
function getZodSchemaFromJsonSchema(jsonSchema: any, toolName: string): z.ZodTypeAny {
if (typeof jsonSchema !== 'object' || jsonSchema === null) {
return z.object({}).passthrough();
}
try {
const zodSchemaString = jsonSchemaToZod(jsonSchema);
const zodSchema = eval(zodSchemaString);
if (typeof zodSchema?.parse !== 'function') {
throw new Error('Eval did not produce a valid Zod schema.');
}
return zodSchema as z.ZodTypeAny;
} catch (err: any) {
console.error(\`Failed to generate/evaluate Zod schema for '\${toolName}':\`, err);
return z.object({}).passthrough();
}
}
`;
}