|
| 1 | +#!/usr/bin/env node |
| 2 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 3 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 4 | +import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; |
| 5 | +import { randomBytes } from 'crypto'; |
| 6 | +import { join } from 'path'; |
| 7 | +import { mkdir, writeFile } from 'fs/promises'; |
| 8 | +import { exec } from 'child_process'; |
| 9 | +import { promisify } from 'util'; |
| 10 | +import { platform } from 'os'; |
| 11 | +// Environment variables |
| 12 | +const CODE_STORAGE_DIR = process.env.CODE_STORAGE_DIR; |
| 13 | +const CONDA_ENV_NAME = process.env.CONDA_ENV_NAME; |
| 14 | +if (!CODE_STORAGE_DIR || !CONDA_ENV_NAME) { |
| 15 | + throw new Error('Missing required environment variables: CODE_STORAGE_DIR and CONDA_ENV_NAME'); |
| 16 | +} |
| 17 | +// Ensure storage directory exists |
| 18 | +await mkdir(CODE_STORAGE_DIR, { recursive: true }); |
| 19 | +const execAsync = promisify(exec); |
| 20 | +/** |
| 21 | + * Get platform-specific command for Conda activation |
| 22 | + */ |
| 23 | +function getPlatformSpecificCommand(pythonCommand) { |
| 24 | + const isWindows = platform() === 'win32'; |
| 25 | + if (isWindows) { |
| 26 | + return { |
| 27 | + command: `conda activate ${CONDA_ENV_NAME} && ${pythonCommand}`, |
| 28 | + options: { |
| 29 | + shell: 'cmd.exe' |
| 30 | + } |
| 31 | + }; |
| 32 | + } |
| 33 | + else { |
| 34 | + return { |
| 35 | + command: `source $(conda info --base)/etc/profile.d/conda.sh && conda activate ${CONDA_ENV_NAME} && ${pythonCommand}`, |
| 36 | + options: { |
| 37 | + shell: '/bin/bash' |
| 38 | + } |
| 39 | + }; |
| 40 | + } |
| 41 | +} |
| 42 | +/** |
| 43 | + * Execute Python code and return the result |
| 44 | + */ |
| 45 | +async function executeCode(code, filePath) { |
| 46 | + try { |
| 47 | + // Write code to file |
| 48 | + await writeFile(filePath, code, 'utf-8'); |
| 49 | + // Get platform-specific command |
| 50 | + const pythonCmd = `python3 "${filePath}"`; |
| 51 | + const { command, options } = getPlatformSpecificCommand(pythonCmd); |
| 52 | + // Execute code |
| 53 | + const { stdout, stderr } = await execAsync(command, { |
| 54 | + cwd: CODE_STORAGE_DIR, |
| 55 | + env: { ...process.env }, |
| 56 | + ...options |
| 57 | + }); |
| 58 | + const response = { |
| 59 | + status: stderr ? 'error' : 'success', |
| 60 | + output: stderr || stdout, |
| 61 | + file_path: filePath |
| 62 | + }; |
| 63 | + return { |
| 64 | + type: 'text', |
| 65 | + text: JSON.stringify(response), |
| 66 | + isError: !!stderr |
| 67 | + }; |
| 68 | + } |
| 69 | + catch (error) { |
| 70 | + const response = { |
| 71 | + status: 'error', |
| 72 | + error: error instanceof Error ? error.message : String(error), |
| 73 | + file_path: filePath |
| 74 | + }; |
| 75 | + return { |
| 76 | + type: 'text', |
| 77 | + text: JSON.stringify(response), |
| 78 | + isError: true |
| 79 | + }; |
| 80 | + } |
| 81 | +} |
| 82 | +/** |
| 83 | + * Create an MCP server to handle code execution |
| 84 | + */ |
| 85 | +const server = new Server({ |
| 86 | + name: "code-executor", |
| 87 | + version: "0.1.0", |
| 88 | +}, { |
| 89 | + capabilities: { |
| 90 | + tools: {}, |
| 91 | + }, |
| 92 | +}); |
| 93 | +/** |
| 94 | + * Handler for listing available tools. |
| 95 | + * Provides a tool to execute code in Python environment. |
| 96 | + */ |
| 97 | +server.setRequestHandler(ListToolsRequestSchema, async () => { |
| 98 | + return { |
| 99 | + tools: [ |
| 100 | + { |
| 101 | + name: "execute_code", |
| 102 | + description: "Execute Python code in the specified conda environment", |
| 103 | + inputSchema: { |
| 104 | + type: "object", |
| 105 | + properties: { |
| 106 | + code: { |
| 107 | + type: "string", |
| 108 | + description: "Python code to execute" |
| 109 | + }, |
| 110 | + filename: { |
| 111 | + type: "string", |
| 112 | + description: "Optional: Name of the file to save the code (default: generated UUID)" |
| 113 | + } |
| 114 | + }, |
| 115 | + required: ["code"] |
| 116 | + } |
| 117 | + } |
| 118 | + ] |
| 119 | + }; |
| 120 | +}); |
| 121 | +/** |
| 122 | + * Handler for the execute_code tool. |
| 123 | + * Executes code and returns the result. |
| 124 | + */ |
| 125 | +server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 126 | + switch (request.params.name) { |
| 127 | + case "execute_code": { |
| 128 | + const args = request.params.arguments; |
| 129 | + if (!args?.code) { |
| 130 | + throw new Error("Code is required"); |
| 131 | + } |
| 132 | + const defaultFilename = `code_${randomBytes(4).toString('hex')}.py`; |
| 133 | + const userFilename = args.filename || defaultFilename; |
| 134 | + const filename = typeof userFilename === 'string' ? userFilename : defaultFilename; |
| 135 | + const filePath = join(CODE_STORAGE_DIR, filename.endsWith('.py') ? filename : `${filename}.py`); |
| 136 | + const result = await executeCode(args.code, filePath); |
| 137 | + return { |
| 138 | + content: [{ |
| 139 | + type: "text", |
| 140 | + text: result.text, |
| 141 | + isError: result.isError |
| 142 | + }] |
| 143 | + }; |
| 144 | + } |
| 145 | + default: |
| 146 | + throw new Error("Unknown tool"); |
| 147 | + } |
| 148 | +}); |
| 149 | +/** |
| 150 | + * Start the server using stdio transport. |
| 151 | + */ |
| 152 | +async function main() { |
| 153 | + const transport = new StdioServerTransport(); |
| 154 | + await server.connect(transport); |
| 155 | +} |
| 156 | +main().catch((error) => { |
| 157 | + console.error("Server error:", error); |
| 158 | + process.exit(1); |
| 159 | +}); |
0 commit comments