* Execute Node.js code via temp file (fallback when Python unavailable) * Creates temp .mjs file in MCP directory for ES module import access
(code: string, timeout_ms: number = 30000)
| 25 | * Creates temp .mjs file in MCP directory for ES module import access |
| 26 | */ |
| 27 | async function executeNodeCode(code: string, timeout_ms: number = 30000): Promise<ServerResult> { |
| 28 | const tempFile = path.join(mcpRoot, `.mcp-exec-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`); |
| 29 | |
| 30 | try { |
| 31 | await fs.writeFile(tempFile, code, 'utf8'); |
| 32 | |
| 33 | const result = await new Promise<{ stdout: string; stderr: string; exitCode: number }>((resolve) => { |
| 34 | const proc = spawn(process.execPath, [tempFile], { |
| 35 | cwd: mcpRoot, |
| 36 | timeout: timeout_ms, |
| 37 | windowsHide: true // Prevent visible console windows on Windows |
| 38 | }); |
| 39 | |
| 40 | let stdout = ''; |
| 41 | let stderr = ''; |
| 42 | |
| 43 | proc.stdout.on('data', (data) => { |
| 44 | stdout += data.toString(); |
| 45 | }); |
| 46 | |
| 47 | proc.stderr.on('data', (data) => { |
| 48 | stderr += data.toString(); |
| 49 | }); |
| 50 | |
| 51 | proc.on('close', (exitCode) => { |
| 52 | resolve({ stdout, stderr, exitCode: exitCode ?? 1 }); |
| 53 | }); |
| 54 | |
| 55 | proc.on('error', (err) => { |
| 56 | resolve({ stdout, stderr: stderr + '\n' + err.message, exitCode: 1 }); |
| 57 | }); |
| 58 | }); |
| 59 | |
| 60 | // Clean up temp file |
| 61 | await fs.unlink(tempFile).catch(() => {}); |
| 62 | |
| 63 | if (result.exitCode !== 0) { |
| 64 | return { |
| 65 | content: [{ |
| 66 | type: "text", |
| 67 | text: `Execution failed (exit code ${result.exitCode}):\n${result.stderr}\n${result.stdout}` |
| 68 | }], |
| 69 | isError: true |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | return { |
| 74 | content: [{ |
| 75 | type: "text", |
| 76 | text: result.stdout || '(no output)' |
| 77 | }] |
| 78 | }; |
| 79 | |
| 80 | } catch (error) { |
| 81 | // Clean up temp file on error |
| 82 | await fs.unlink(tempFile).catch(() => {}); |
| 83 | |
| 84 | return { |
no test coverage detected