-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
226 lines (196 loc) · 5.58 KB
/
Copy pathindex.ts
File metadata and controls
226 lines (196 loc) · 5.58 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
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { spawn } from "child_process";
import { writeFileSync, unlinkSync, mkdtempSync } from "fs";
import { join } from "path";
import { tmpdir } from "os";
interface ExecutionResult {
success: boolean;
output?: string;
error?: string;
executionTime?: number;
}
class CodeExecutor {
private tempDir: string;
constructor() {
// Create a temporary directory for code execution
this.tempDir = mkdtempSync(join(tmpdir(), "qcode-"));
}
async executeJavaScript(
code: string,
timeout: number = 30000
): Promise<ExecutionResult> {
const startTime = Date.now();
try {
// Create a temporary file with the code
const tempFile = join(this.tempDir, `code_${Date.now()}.js`);
writeFileSync(tempFile, code, "utf8");
return new Promise((resolve) => {
let output = "";
let error = "";
let hasResolved = false;
// Set up timeout
const timeoutId = setTimeout(() => {
if (!hasResolved) {
hasResolved = true;
try {
unlinkSync(tempFile);
} catch (e) {
// Ignore cleanup errors
}
resolve({
success: false,
error: `Execution timed out after ${timeout}ms`,
executionTime: Date.now() - startTime,
});
}
}, timeout);
// Execute the code using Node.js
const child = spawn("node", [tempFile], {
cwd: this.tempDir,
stdio: ["pipe", "pipe", "pipe"],
timeout: timeout,
});
// Capture stdout
child.stdout.on("data", (data) => {
output += data.toString();
});
// Capture stderr
child.stderr.on("data", (data) => {
error += data.toString();
});
// Handle process completion
child.on("close", (code) => {
if (!hasResolved) {
hasResolved = true;
clearTimeout(timeoutId);
try {
unlinkSync(tempFile);
} catch (e) {
// Ignore cleanup errors
}
const executionTime = Date.now() - startTime;
if (code === 0) {
resolve({
success: true,
output: output.trim(),
executionTime,
});
} else {
resolve({
success: false,
output: output.trim(),
error: error.trim() || `Process exited with code ${code}`,
executionTime,
});
}
}
});
// Handle process errors
child.on("error", (err) => {
if (!hasResolved) {
hasResolved = true;
clearTimeout(timeoutId);
try {
unlinkSync(tempFile);
} catch (e) {
// Ignore cleanup errors
}
resolve({
success: false,
error: `Failed to execute code: ${err.message}`,
executionTime: Date.now() - startTime,
});
}
});
});
} catch (err) {
return {
success: false,
error: `Failed to prepare code execution: ${
err instanceof Error ? err.message : String(err)
}`,
executionTime: Date.now() - startTime,
};
}
}
}
// Create the code executor instance
const codeExecutor = new CodeExecutor();
// The server instance and tools exposed to Claude
const server = new Server(
{
name: "code-interpreter-server",
version: "0.0.1",
},
{
capabilities: {
tools: {},
},
}
);
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "execute_javascript",
description:
"Execute JavaScript code in a Node.js environment and return the output",
inputSchema: {
type: "object",
properties: {
code: {
type: "string",
description: "The JavaScript code to execute",
},
timeout: {
type: "number",
description: "Timeout in milliseconds (default: 30000)",
default: 30000,
},
},
required: ["code"],
},
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (!args) {
throw new Error(`No arguments provided for tool: ${name}`);
}
switch (name) {
case "execute_javascript":
const code = args.code as string;
const timeout = (args.timeout as number) || 30000;
if (!code || typeof code !== "string") {
throw new Error("Code parameter is required and must be a string");
}
const result = await codeExecutor.executeJavaScript(code, timeout);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
default:
throw new Error(`Unknown tool: ${name}`);
}
});
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Code Interpreter MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});