diff --git a/src/config/loader.ts b/src/config/loader.ts index 24904fb..21b1261 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -547,3 +547,47 @@ export function getClientCloseTimeoutMs(): number { MAX_CLIENT_CLOSE_TIMEOUT_MS ); } + +/** + * HTTP server mode (single shared instance). + * + * When `CODE_EXECUTOR_ROLE=http`, the server runs one Streamable HTTP MCP + * endpoint on loopback that every host connects to (instead of each host + * spawning its own stdio child). The port is fixed/known so hosts can point a + * `url` at it; the host is ALWAYS loopback — a code-execution server must never + * bind a routable interface. + */ +export const DEFAULT_HTTP_PORT = 39273; +const MIN_HTTP_PORT = 1024; +const MAX_HTTP_PORT = 65535; + +/** Loopback TCP port for the HTTP MCP endpoint. `CODE_EXECUTOR_HTTP_PORT` (1024–65535). */ +export function getHttpPort(): number { + return getBoundedEnvMs( + process.env.CODE_EXECUTOR_HTTP_PORT, + DEFAULT_HTTP_PORT, + MIN_HTTP_PORT, + MAX_HTTP_PORT + ); +} + +/** Bind host for the HTTP MCP endpoint — loopback only, not configurable by design. */ +export function getHttpHost(): string { + return '127.0.0.1'; +} + +/** + * Whether the HTTP endpoint requires a bearer token. ON by default; a code-execution + * server on a TCP port is reachable by any local process (and browsers via + * DNS-rebinding), so auth is the norm. Disable only on a trusted single-user box + * via `CODE_EXECUTOR_HTTP_AUTH=off`. + */ +export function isHttpAuthEnabled(): boolean { + return process.env.CODE_EXECUTOR_HTTP_AUTH !== 'off'; +} + +/** The expected bearer token (`CODE_EXECUTOR_HTTP_TOKEN`), or undefined if unset. */ +export function getHttpAuthToken(): string | undefined { + const token = process.env.CODE_EXECUTOR_HTTP_TOKEN; + return token && token.length > 0 ? token : undefined; +} diff --git a/src/core/shared-core.ts b/src/core/shared-core.ts new file mode 100644 index 0000000..2d04387 --- /dev/null +++ b/src/core/shared-core.ts @@ -0,0 +1,831 @@ +/** + * SharedCore — transport-agnostic core for the Code Executor MCP server. + * + * Owns the shared, long-lived components (downstream MCP client pool, security + * validator, connection pool, rate limiter, health-check server) and the + * free-function tool registration that a per-connection `McpServer` binds to. + * + * Extracted from the original `CodeExecutorServer` class so a future HTTP + * transport can build these shared pieces ONCE and register the same tools on a + * per-session `McpServer`, while the stdio entrypoint (src/index.ts) stays a + * thin wrapper. Behavior over stdio is unchanged — this is a pure extraction. + */ + +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; +import { z } from 'zod'; +import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck } from '../config/loader.js'; +import { ExecuteTypescriptInputSchema, ExecutePythonInputSchema, ExecutionResultSchema } from '../config/schemas.js'; +import { MCPClientPool } from '../mcp/client-pool.js'; +import { SecurityValidator } from '../validation/security-validator.js'; +import { ConnectionPool } from '../mcp/connection-pool.js'; +import { RateLimiter } from '../security/rate-limiter.js'; +import { executeTypescriptInSandbox } from '../executors/sandbox-executor.js'; +import { executePythonInSandbox as executePythonNative } from '../executors/python-executor.js'; +// Pyodide is loaded lazily — only imported when PYTHON_SANDBOX_READY=true. +// This keeps the 13MB pyodide WASM out of `bun --compile` binaries that don't need it. +type ExecutePythonPyodideFn = typeof import('../executors/pyodide-executor.js').executePythonInSandbox; +import { formatErrorResponse, formatExecutionResultForCli } from '../utils/utils.js'; +import { ErrorType } from '../types.js'; +import { checkDenoAvailable, getDenoVersion, getDenoInstallMessage } from '../executors/deno-checker.js'; +import { HealthCheckServer } from '../core/server/health-check.js'; +import { VERSION } from '../version.js'; +import type { MCPExecutionResult } from '../types.js'; + +/** + * Health check response schema (Zod) + * Used as outputSchema for the health tool + */ +export const HealthCheckOutputSchema = z.object({ + healthy: z.boolean().describe('Overall health status'), + auditLog: z.object({ + enabled: z.boolean().describe('Audit logging enabled'), + }).describe('Audit log configuration'), + mcpClients: z.object({ + connected: z.number().describe('Number of connected MCP tools'), + }).describe('MCP client connections'), + connectionPool: z.object({ + active: z.number().describe('Active concurrent executions'), + waiting: z.number().describe('Queued executions waiting'), + max: z.number().describe('Maximum concurrent limit'), + }).describe('Connection pool status'), + uptime: z.number().describe('Server uptime in seconds'), + timestamp: z.string().describe('ISO 8601 timestamp'), +}); + +/** + * Transport-agnostic shared core. + * + * Built once per process; the tool set (see {@link registerTools}) is bound to + * whatever `McpServer` a transport creates. + */ +export class SharedCore { + readonly mcpClientPool: MCPClientPool; + readonly securityValidator: SecurityValidator; + readonly connectionPool: ConnectionPool; + rateLimiter: RateLimiter | null = null; + denoAvailable = false; + // Resolves when the downstream MCP client pool has finished initializing. + // The pool is initialized in the BACKGROUND (see startBackgroundServices) so + // the upstream MCP handshake is never blocked by slow/unreachable downstream + // servers. Tool handlers await this before executing so downstream tools are + // ready (or have been determined unavailable) by the time code runs. + poolReady: Promise = Promise.resolve(); + private healthCheckServer: HealthCheckServer | null = null; + private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts + + constructor() { + // Initialize components + this.mcpClientPool = new MCPClientPool(); + this.securityValidator = new SecurityValidator(); + this.connectionPool = new ConnectionPool(100); // Max 100 concurrent executions + } + + /** + * Pre-tools shared setup: load config, detect Deno, init rate limiter. + * + * Must run before {@link registerTools} (registration reads `denoAvailable`). + */ + async initialize(): Promise { + // Initialize configuration + console.error('Loading configuration...'); + await initConfig(); + + // Check Deno availability + console.error('Checking Deno availability...'); + this.denoAvailable = await checkDenoAvailable(); + + if (this.denoAvailable) { + const version = getDenoVersion(); + console.error(`✓ Deno ${version ?? 'found'} - TypeScript execution enabled`); + } else { + console.error(getDenoInstallMessage()); + console.error(''); // Empty line for readability + } + + // Initialize rate limiter if enabled + if (isRateLimitEnabled()) { + const rateLimitConfig = getRateLimitConfig(); + if (rateLimitConfig) { + this.rateLimiter = new RateLimiter({ + maxRequests: rateLimitConfig.maxRequests, + windowMs: rateLimitConfig.windowMs, + }); + console.error(`Rate limiting enabled: ${rateLimitConfig.maxRequests} requests per ${rateLimitConfig.windowMs / 1000}s`); + } + } + } + + /** + * Post-transport background services: kick off the downstream MCP client pool + * (in the background — not awaited) and start the optional health-check server. + */ + async startBackgroundServices(): Promise { + // Initialize MCP client pool in the background. Tool handlers await + // `poolReady` before executing (see registerTools). Failures are logged but + // never crash the server — code-executor keeps serving whatever connected. + console.error('Initializing MCP client pool...'); + this.poolReady = this.mcpClientPool + .initialize() + .then(() => { + const tools = this.mcpClientPool.listAllTools(); + console.error(`Connected to ${tools.length} MCP tools across multiple servers`); + }) + .catch((error) => { + const message = error instanceof Error ? error.message : String(error); + console.error( + `MCP client pool initialization failed — continuing without downstream tools: ${message}` + ); + }); + + // Initialize health check server (optional, enabled via env var) + const enableHealthCheck = process.env.ENABLE_HEALTH_CHECK !== 'false'; + if (enableHealthCheck) { + console.error('Starting health check server...'); + this.healthCheckServer = new HealthCheckServer({ + mcpClientPool: this.mcpClientPool, + connectionPool: this.connectionPool, + version: VERSION, + }); + + try { + await this.healthCheckServer.start(); + } catch (error) { + console.error('Warning: Failed to start health check server:', error); + // Don't fail the entire server if health check fails to start + this.healthCheckServer = null; + } + } + } + + /** + * Graceful shutdown with request draining + * + * P1: Wait for in-flight executions to complete before shutdown. + * Fixes race condition where active TypeScript/Python executions are killed mid-operation. + * + * Shutdown sequence: + * 1. Drain connection pool (wait for active executions with 30s timeout) + * 2. Stop health check server + * 3. Clean up rate limiter + * 4. Disconnect MCP clients (with 2s SIGTERM grace period) + * + * The caller decides when to terminate the process — this method never calls + * process.exit so it is reusable across transports. + * + * @param timeoutMs - Maximum time for entire shutdown (default: 35s = 30s drain + 5s cleanup) + */ + async shutdown(timeoutMs: number = 35000): Promise { + // P1: Prevent concurrent shutdown attempts (manual + signal handler races) + if (this.shutdownInProgress) { + console.error('Shutdown already in progress - ignoring duplicate call'); + return; + } + this.shutdownInProgress = true; + + const shutdownStart = Date.now(); + + // Wrap entire shutdown in timeout protection + const shutdownPromise = (async () => { + // Phase 1: Drain connection pool (wait for active executions) + console.error('Phase 1: Draining connection pool...'); + try { + await this.connectionPool.drain(30000); // 30s timeout for executions + } catch (error) { + console.error('Error draining connection pool:', error); + } + + // Phase 2: Stop health check server + console.error('Phase 2: Stopping health check server...'); + if (this.healthCheckServer) { + try { + await this.healthCheckServer.stop(); + } catch (error) { + console.error('Error stopping health check server:', error); + } + } + + // Phase 3: Clean up rate limiter + console.error('Phase 3: Cleaning up rate limiter...'); + if (this.rateLimiter) { + this.rateLimiter.destroy(); + } + + // Phase 4: Disconnect MCP clients (with 2s SIGTERM grace period) + console.error('Phase 4: Disconnecting MCP clients...'); + await this.mcpClientPool.disconnect(); + + const elapsed = Date.now() - shutdownStart; + console.error(`✓ Graceful shutdown completed in ${elapsed}ms`); + })(); + + // Race against timeout + const timeoutPromise = new Promise((resolve) => { + setTimeout(() => { + const elapsed = Date.now() - shutdownStart; + console.error( + `⚠️ Shutdown timeout after ${timeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit` + ); + resolve(); + }, timeoutMs); + }); + + await Promise.race([shutdownPromise, timeoutPromise]); + } + + /** + * Synchronously kill all spawned downstream child processes. + * Backstop for the process 'exit' handler (see the stdio entrypoint). + */ + killChildrenSync(): void { + this.mcpClientPool.killChildrenSync(); + } +} + +/** + * Handle tool execution errors with standardized response format + */ +export function handleToolError(error: unknown, errorType: ErrorType) { + const errorResponse = formatErrorResponse(error, errorType); + return { + content: [{ + type: 'text' as const, + text: JSON.stringify(errorResponse, null, 2), + }], + isError: true, + }; +} + +/** + * Check rate limit before executing code + * + * Returns error response if rate limited, null otherwise. `clientId` scopes the + * rate-limit bucket to the caller's session so one host cannot exhaust another + * host's budget (in HTTP mode a distinct id per session; 'stdio' over stdio). + */ +export async function checkRateLimit( + core: SharedCore, + clientId: string +): Promise | null> { + if (!core.rateLimiter) { + return null; // Rate limiting disabled + } + + const result = await core.rateLimiter.checkLimit(clientId); + + if (!result.allowed) { + const error = new Error( + `Rate limit exceeded. Maximum ${getRateLimitConfig()?.maxRequests ?? 30} requests per ` + + `${(getRateLimitConfig()?.windowMs ?? 60000) / 1000}s. ` + + `Try again in ${Math.ceil(result.resetIn / 1000)}s.` + ); + return handleToolError(error, ErrorType.VALIDATION); + } + + return null; +} + +/** + * Register MCP tools on the given server, backed by the shared core. + * + * `clientId` identifies the calling session — a distinct id per HTTP session + * (so multiple hosts sharing one process are attributed and rate-limited + * independently), or 'stdio' for the one-host-per-process stdio transport. It + * is threaded into the rate-limit bucket and the audit-log client id. + */ +export function registerTools(core: SharedCore, server: McpServer, clientId: string): void { + // Tool 1: Execute TypeScript (only if Deno is available) + if (core.denoAvailable) { + const typescriptToolConfig: Parameters[1] = { + title: 'Execute TypeScript with MCP Access', + description: `Execute TypeScript/JavaScript code in a secure Deno sandbox with access to MCP tools. + +Executed code has access to callMCPTool(toolName, params) function for calling other MCP servers. +Import DopaMind wrappers: import { codereview } from './servers/zen/codereview' + +**NEW: In-Sandbox Tool Discovery** +Three discovery functions are injected into the sandbox for self-service tool exploration: + +1. discoverMCPTools(options?) - Discover all available MCP tools + - Options: { search?: string[] } - Array of keywords to filter tools (OR logic) + - Returns: ToolSchema[] - Array of tool schemas + - Example: const tools = await discoverMCPTools({ search: ['file', 'read'] }); + +2. getToolSchema(toolName) - Get detailed schema for a specific tool + - Parameter: toolName (string) - Full tool name (e.g., 'mcp__filesystem__read_file') + - Returns: ToolSchema | null - Tool schema or null if not found + - Example: const schema = await getToolSchema('mcp__filesystem__read_file'); + +3. searchTools(query, limit?) - Search tools by keywords with result limiting + - Parameters: query (string), limit (number, default: 10) + - Returns: ToolSchema[] - Filtered and limited tool schemas + - Example: const fileTools = await searchTools('file read write', 5); + +**Proactive Workflow Example:** +// Discover tools, inspect schema, then execute +const networkTools = await searchTools('fetch url'); +const schema = await getToolSchema(networkTools[0].name); +const result = await callMCPTool(networkTools[0].name, { url: 'https://...' }); + +Security: +- Only tools in allowedTools array can be called +- Deno sandbox permissions enforce file system and network restrictions +- Execution timeout prevents infinite loops +- All executions are audit logged + +Args: + - code (string): TypeScript/JavaScript code to execute + - allowedTools (string[]): MCP tools whitelist (default: []) + Format: ['mcp____', ...] + Example: ['mcp__zen__codereview', 'mcp__filesystem__read_file'] + - timeoutMs (number): Execution timeout in milliseconds (default: 30000) + - permissions (object): Deno sandbox permissions + - read (string[]): Allowed read paths + - write (string[]): Allowed write paths + - net (string[]): Allowed network hosts + - skipDangerousPatternCheck (boolean): Accepted for backward compatibility but IGNORED (issue #56) + Per-call skipping is intentionally disabled so a caller cannot bypass the check. + Validation can only be disabled SERVER-SIDE via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS + env var (=true) or the security.skipDangerousPatternCheck config option (operator decision). + NOTE: Dangerous pattern validation is defense-in-depth only, NOT a security boundary + Real security comes from sandbox permissions, resource limits, and process isolation + +Returns: + { + "success": boolean, + "output": string, // stdout from console.log() + "error": string, // Error message if failed + "executionTimeMs": number, + "toolCallsMade": string[], // MCP tools called + "toolCallSummary": ToolCallSummaryEntry[] // Aggregated tool call metrics + } + +Example: + { + "code": "const result = await callMCPTool('mcp__zen__codereview', {...}); console.log(result);", + "allowedTools": ["mcp__zen__codereview"], + "timeoutMs": 60000 + }`, + inputSchema: { + code: z.string().min(1).describe('TypeScript/JavaScript code to execute'), + allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist'), + timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout in milliseconds'), + permissions: z.object({ + read: z.array(z.string()).optional(), + write: z.array(z.string()).optional(), + net: z.array(z.string()).optional(), + }).default({}).describe('Deno sandbox permissions'), + skipDangerousPatternCheck: z.boolean().optional().describe('Accepted but IGNORED for security (issue #56): per-call skipping is disabled. Validation can only be disabled server-side via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS env var or security.skipDangerousPatternCheck config option.'), + enableSampling: z.boolean().optional().default(false).describe('Enable LLM sampling (llm.ask/llm.think helpers)'), + maxSamplingRounds: z.number().int().min(1).max(100).optional().default(10).describe('Max sampling rounds'), + maxSamplingTokens: z.number().int().min(100).max(100000).optional().default(10000).describe('Max sampling tokens'), + samplingSystemPrompt: z.string().optional().describe('Custom system prompt for sampling'), + allowedSamplingModels: z.array(z.string()).optional().describe('Allowed Claude models for sampling'), + }, + outputSchema: ExecutionResultSchema.shape, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: true, + }, + }; + + const typescriptToolHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { + try { + // Check rate limit + const rateLimitError = await checkRateLimit(core, clientId); + if (rateLimitError) { + return rateLimitError; + } + + // Validate input with Zod schema (runtime validation) + const parseResult = ExecuteTypescriptInputSchema.safeParse(args); + if (!parseResult.success) { + return { + content: [{ + type: 'text' as const, + text: JSON.stringify({ + success: false, + output: '', + error: `Input validation failed: ${parseResult.error.message}`, + executionTimeMs: 0, + }, null, 2), + }], + isError: true, + }; + } + const input = parseResult.data; + + // Validate security + core.securityValidator.validateAllowlist(input.allowedTools); + await core.securityValidator.validatePermissions(input.permissions); + + // Hybrid skip logic: + // 1. Config/Env variable ONLY (Issue #56 - Security Fix) + // User input is ignored to prevent security bypass + const skipPatternCheck = shouldSkipDangerousPatternCheck(); + const codeValidation = core.securityValidator.validateCode(input.code, skipPatternCheck); + + if (!codeValidation.valid) { + return { + content: [{ + type: 'text' as const, + text: JSON.stringify({ + success: false, + output: '', + error: codeValidation.errors.join('\n'), + executionTimeMs: 0, + }, null, 2), + }], + isError: true, + }; + } + + // Ensure the downstream MCP pool has finished initializing (it is set + // up in the background at startup) so callMCPTool/discovery see the + // connected servers. Bounded by per-server connect timeouts. + await core.poolReady; + + // Execute code with connection pooling + const result = await core.connectionPool.execute(async () => { + return await executeTypescriptInSandbox( + { + code: input.code, + allowedTools: input.allowedTools, + timeoutMs: input.timeoutMs, + permissions: input.permissions, + skipDangerousPatternCheck: skipPatternCheck, + enableSampling: input.enableSampling, + maxSamplingRounds: input.maxSamplingRounds, + maxSamplingTokens: input.maxSamplingTokens, + samplingSystemPrompt: input.samplingSystemPrompt, + allowedSamplingModels: input.allowedSamplingModels, + }, + core.mcpClientPool, + server.server // Pass underlying Server instance with request() method for MCP sampling + ); + }); + + // Audit log + await core.securityValidator.auditLog( + { + executor: 'typescript', + allowedTools: input.allowedTools, + toolsCalled: result.toolCallsMade ?? [], + executionTimeMs: result.executionTimeMs, + success: result.success, + error: result.error, + clientId, // per-session id (HTTP session id, or 'stdio') + memoryUsage: process.memoryUsage().heapUsed, + }, + input.code + ); + + return { + content: [{ + type: 'text' as const, + text: formatExecutionResultForCli(result), + }], + structuredContent: result as MCPExecutionResult, + isError: !result.success, + }; + } catch (error) { + return handleToolError(error, ErrorType.EXECUTION); + } + }; + + server.registerTool( + 'executeTypescript', + typescriptToolConfig, + typescriptToolHandler + ); + } + + // Tool 2: Execute Python (optional, enabled via config) + // SECURITY GATE: Check if Python sandbox is ready + // Issue #50/#59: Python executor has NO sandbox isolation until Pyodide is implemented + const PYTHON_SANDBOX_READY = process.env.PYTHON_SANDBOX_READY === 'true'; + + if (isPythonEnabled()) { + if (!PYTHON_SANDBOX_READY) { + // Register stub handler that returns security warning + console.error('⚠️ Python executor DISABLED (CRITICAL security vulnerability #50)'); + console.error(' Current Python executor has NO sandbox - full filesystem/network access!'); + console.error(' Set PYTHON_SANDBOX_READY=true only after implementing Pyodide sandbox (issue #59)'); + + const pythonSecurityStubConfig: Parameters[1] = { + title: 'Execute Python with MCP Access (DISABLED - Security Issue)', + description: `⚠️ CRITICAL SECURITY WARNING ⚠️ + +Python executor is currently DISABLED due to lack of sandbox isolation. + +VULNERABILITY: Issue #50 - Python executor has NO sandbox +- Current implementation runs with full filesystem access +- No network isolation (can access localhost services, cloud metadata) +- Pattern-based security is easily bypassed +- Execution via native subprocess.spawn() with zero restrictions + +SOLUTION IN PROGRESS: Issue #59 - Pyodide WebAssembly sandbox +- Same security model as Deno (WASM isolation) +- Virtual filesystem (no host access) +- Network restricted to MCP proxy only +- Industry-proven approach (Pydantic, JupyterLite) + +DO NOT enable this tool until Pyodide implementation is complete. +See: https://github.com/aberemia24/code-executor-MCP/issues/50 + +This tool is DISABLED for your protection.`, + inputSchema: { + code: z.string().min(1).describe('Python code (DISABLED)'), + allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist (DISABLED)'), + timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout (DISABLED)'), + }, + outputSchema: ExecutionResultSchema.shape, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + }; + + const pythonSecurityStubHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { + return { + content: [{ + type: 'text' as const, + text: JSON.stringify({ + success: false, + output: '', + error: '🔴 CRITICAL: Python executor disabled due to security vulnerability.\n\n' + + 'ISSUE: No sandbox protection exists in current implementation (issue #50).\n' + + '- Full filesystem access (can read /etc/passwd, SSH keys, etc.)\n' + + '- Full network access (SSRF to localhost services, cloud metadata endpoints)\n' + + '- Pattern-based blocking is easily bypassed\n\n' + + 'SOLUTION: Pyodide WebAssembly sandbox implementation in progress (issue #59).\n' + + '- Same security model as Deno executor\n' + + '- Virtual filesystem isolation\n' + + '- Network restricted to authenticated MCP proxy\n\n' + + 'This tool will remain disabled until the security fix is complete.\n' + + 'For updates: https://github.com/aberemia24/code-executor-MCP/issues/50', + executionTimeMs: 0, + }, null, 2), + }], + isError: true, + }; + }; + + server.registerTool( + 'executePython', + pythonSecurityStubConfig, + pythonSecurityStubHandler + ); + + return; // Exit early - don't register real Python handler + } + + // PYTHON_SANDBOX_READY === true - register real Pyodide handler + const pythonToolConfig: Parameters[1] = { + title: 'Execute Python with MCP Access (Pyodide Sandbox)', + description: `Execute Python code in Pyodide WebAssembly sandbox with access to MCP tools. + +Executed code has access to call_mcp_tool(toolName, params) function for calling other MCP servers. + +Security (Pyodide Sandbox): +- WebAssembly isolation (same security model as Deno) +- Virtual filesystem (no host file access) +- Network restricted to authenticated MCP proxy only +- Only tools in allowedTools array can be called +- Execution timeout prevents infinite loops +- All executions are audit logged + +Args: + - code (string): Python code to execute + - allowedTools (string[]): MCP tools whitelist (default: []) + Format: ['mcp____', ...] + Example: ['mcp__zen__codereview', 'mcp__filesystem__read_file'] + - timeoutMs (number): Execution timeout in milliseconds (default: 30000) + - permissions (object): Subprocess permissions (limited to temp directory and localhost) + - skipDangerousPatternCheck (boolean): Accepted for backward compatibility but IGNORED (issue #56) + Per-call skipping is intentionally disabled so a caller cannot bypass the check. + Validation can only be disabled SERVER-SIDE via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS + env var (=true) or the security.skipDangerousPatternCheck config option (operator decision). + NOTE: Dangerous pattern validation is defense-in-depth only, NOT a security boundary + Real security comes from sandbox permissions, resource limits, and process isolation + +Returns: + { + "success": boolean, + "output": string, // stdout from print() + "error": string, // Error message if failed + "executionTimeMs": number, + "toolCallsMade": string[], // MCP tools called + "toolCallSummary": ToolCallSummaryEntry[] // Aggregated tool call metrics + } + +Example: + { + "code": "result = call_mcp_tool('mcp__zen__codereview', {...}); print(result)", + "allowedTools": ["mcp__zen__codereview"], + "timeoutMs": 60000 + }`, + inputSchema: { + code: z.string().min(1).describe('Python code to execute'), + allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist'), + timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout in milliseconds'), + permissions: z.object({ + read: z.array(z.string()).optional(), + write: z.array(z.string()).optional(), + net: z.array(z.string()).optional(), + }).default({}).describe('Subprocess permissions'), + skipDangerousPatternCheck: z.boolean().optional().describe('Accepted but IGNORED for security (issue #56): per-call skipping is disabled. Validation can only be disabled server-side via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS env var or security.skipDangerousPatternCheck config option.'), + enableSampling: z.boolean().optional().default(false).describe('Enable LLM sampling (llm.ask/llm.think helpers)'), + maxSamplingRounds: z.number().int().min(1).max(100).optional().default(10).describe('Max sampling rounds'), + maxSamplingTokens: z.number().int().min(100).max(100000).optional().default(10000).describe('Max sampling tokens'), + samplingSystemPrompt: z.string().optional().describe('Custom system prompt for sampling'), + allowedSamplingModels: z.array(z.string()).optional().describe('Allowed Claude models for sampling'), + }, + outputSchema: ExecutionResultSchema.shape, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: true, + }, + }; + + const pythonToolHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { + try { + // Check rate limit + const rateLimitError = await checkRateLimit(core, clientId); + if (rateLimitError) { + return rateLimitError; + } + + // Validate input with Zod schema + const parseResult = ExecutePythonInputSchema.safeParse(args); + if (!parseResult.success) { + return { + content: [{ + type: 'text' as const, + text: JSON.stringify({ + success: false, + output: '', + error: `Input validation failed: ${parseResult.error.message}`, + executionTimeMs: 0, + }, null, 2), + }], + isError: true, + }; + } + const input = parseResult.data; + + // Validate security + core.securityValidator.validateAllowlist(input.allowedTools); + await core.securityValidator.validatePermissions(input.permissions); + + // Hybrid skip logic: + // 1. Config/Env variable ONLY (Issue #56 - Security Fix) + // User input is ignored to prevent security bypass + const skipPatternCheck = shouldSkipDangerousPatternCheck(); + const codeValidation = core.securityValidator.validateCode(input.code, skipPatternCheck); + + if (!codeValidation.valid) { + return { + content: [{ + type: 'text' as const, + text: JSON.stringify({ + success: false, + output: '', + error: codeValidation.errors.join('\n'), + executionTimeMs: 0, + }, null, 2), + }], + isError: true, + }; + } + + // Ensure the downstream MCP pool has finished initializing (background + // startup) before executing. Bounded by per-server connect timeouts. + await core.poolReady; + + // Execute code with connection pooling + // Use Pyodide (secure) when PYTHON_SANDBOX_READY, otherwise native (insecure) + // Pyodide loaded lazily so its 13MB WASM stays out of compiled binaries that don't enable it. + let executePythonInSandbox: ExecutePythonPyodideFn; + if (PYTHON_SANDBOX_READY) { + const pyodideMod = await import('../executors/pyodide-executor.js'); + executePythonInSandbox = pyodideMod.executePythonInSandbox; + } else { + executePythonInSandbox = executePythonNative; + } + + const result = await core.connectionPool.execute(async () => { + return await executePythonInSandbox( + { + code: input.code, + allowedTools: input.allowedTools, + timeoutMs: input.timeoutMs, + permissions: input.permissions, + skipDangerousPatternCheck: skipPatternCheck, + enableSampling: input.enableSampling, + maxSamplingRounds: input.maxSamplingRounds, + maxSamplingTokens: input.maxSamplingTokens, + samplingSystemPrompt: input.samplingSystemPrompt, + allowedSamplingModels: input.allowedSamplingModels, + }, + core.mcpClientPool, + server.server // Pass underlying Server instance with request() method for MCP sampling + ); + }); + + // Audit log + await core.securityValidator.auditLog( + { + executor: 'python', + allowedTools: input.allowedTools, + toolsCalled: result.toolCallsMade ?? [], + executionTimeMs: result.executionTimeMs, + success: result.success, + error: result.error, + clientId, // per-session id (HTTP session id, or 'stdio') + memoryUsage: process.memoryUsage().heapUsed, + }, + input.code + ); + + return { + content: [{ + type: 'text' as const, + text: formatExecutionResultForCli(result), + }], + structuredContent: result as MCPExecutionResult, + isError: !result.success, + }; + } catch (error) { + return handleToolError(error, ErrorType.EXECUTION); + } + }; + + server.registerTool( + 'executePython', + pythonToolConfig, + pythonToolHandler + ); + } + + // Tool 3: Health Check + server.registerTool( + 'health', + { + title: 'Server Health Check', + description: `Get server health status including audit log, MCP connections, connection pool, and uptime. + +Returns: + { + "healthy": boolean, + "auditLog": { "enabled": boolean }, + "mcpClients": { "connected": number }, + "connectionPool": { "active": number, "waiting": number, "max": number }, + "uptime": number + }`, + inputSchema: {}, + outputSchema: HealthCheckOutputSchema.shape, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, + async (args: any, extra: RequestHandlerExtra) => { + try { + const tools = core.mcpClientPool.listAllTools(); + const poolStats = core.connectionPool.getStats(); + + const health = { + healthy: true, + auditLog: { + enabled: core.securityValidator.isAuditLogEnabled(), + }, + mcpClients: { + connected: tools.length, + }, + connectionPool: poolStats, + uptime: process.uptime(), + timestamp: new Date().toISOString(), + }; + + return { + content: [{ + type: 'text' as const, + text: JSON.stringify(health, null, 2), + }], + structuredContent: health, + }; + } catch (error) { + return handleToolError(error, ErrorType.EXECUTION); + } + } + ); +} diff --git a/src/http/http-server.ts b/src/http/http-server.ts new file mode 100644 index 0000000..cf791ee --- /dev/null +++ b/src/http/http-server.ts @@ -0,0 +1,255 @@ +/** + * Streamable HTTP MCP server — the single-shared-instance transport. + * + * WHY: over stdio, every MCP host spawns its own code-executor child, and each + * one independently spawns the whole downstream MCP pool (the "thundering + * herd"). In HTTP mode a single resident process serves one Streamable HTTP + * endpoint on loopback that every host connects to via a `url`, so the + * expensive downstream pool is built ONCE for the machine. + * + * The shared, transport-agnostic state (downstream pool, validators, connection + * pool) lives in a single {@link SharedCore}; each connected host gets its own + * MCP session — a fresh `McpServer` bound to a per-session + * `StreamableHTTPServerTransport` — so request/response id spaces are isolated + * and server→client requests (sampling / elicitation / roots) route back to the + * originating host automatically (the SDK routes them over that session's + * transport). All sessions share the one SharedCore. + * + * Security: bound to 127.0.0.1 only; every /mcp request requires a bearer token + * (a code-execution endpoint on a TCP port is reachable by any local process and, + * via DNS-rebinding, by browsers — so auth is on by default), and the SDK's DNS + * rebinding protection validates the Host header. Auth may be disabled only via + * CODE_EXECUTOR_HTTP_AUTH=off on a trusted single-user machine. + */ + +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import { randomUUID, timingSafeEqual } from 'node:crypto'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js'; +import { SharedCore, registerTools } from '../core/shared-core.js'; +import { + getHttpPort, + getHttpHost, + isHttpAuthEnabled, + getHttpAuthToken, +} from '../config/loader.js'; +import { VERSION } from '../version.js'; + +const MCP_PATH = '/mcp'; +const HEALTH_PATH = '/health'; +const MAX_BODY_BYTES = 4 * 1024 * 1024; // cap the initialize-body read (SDK bounds the rest) + +/** Write a JSON body with a status code. */ +function sendJson(res: ServerResponse, status: number, body: unknown): void { + res.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify(body)); +} + +/** Write a JSON-RPC error envelope (the shape MCP clients expect). */ +function sendRpcError(res: ServerResponse, status: number, message: string, code = -32000): void { + sendJson(res, status, { jsonrpc: '2.0', error: { code, message }, id: null }); +} + +/** Constant-time bearer-token check. */ +function isAuthorized(req: IncomingMessage, expectedToken: string): boolean { + const header = req.headers['authorization']; + if (typeof header !== 'string') { + return false; + } + const provided = Buffer.from(header); + const expected = Buffer.from(`Bearer ${expectedToken}`); + return provided.length === expected.length && timingSafeEqual(provided, expected); +} + +/** Read and JSON-parse a request body (used only for the session-less initialize). */ +async function readJsonBody(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + size += (chunk as Buffer).length; + if (size > MAX_BODY_BYTES) { + throw new Error('Request body too large'); + } + chunks.push(chunk as Buffer); + } + return JSON.parse(Buffer.concat(chunks).toString('utf-8')); +} + +/** + * Run the single shared HTTP MCP server. Never returns (owns the process + * lifecycle); resolves only if `listen` fails before startup. + */ +export async function runHttpServer(): Promise { + const authEnabled = isHttpAuthEnabled(); + const token = getHttpAuthToken(); + if (authEnabled && !token) { + console.error('FATAL: HTTP auth is enabled but CODE_EXECUTOR_HTTP_TOKEN is not set.'); + console.error('Set a bearer token, or set CODE_EXECUTOR_HTTP_AUTH=off on a trusted single-user machine.'); + process.exit(1); + } + + // Build the shared, transport-agnostic core ONCE (config, Deno, rate limiter), + // then kick off the downstream pool + health server. All sessions share it. + const core = new SharedCore(); + await core.initialize(); + await core.startBackgroundServices(); + + const port = getHttpPort(); + const host = getHttpHost(); + const allowedHosts = [`${host}:${port}`, `localhost:${port}`]; + + // One transport (+ its own McpServer) per live MCP session, keyed by session id. + const sessions = new Map(); + + /** Create a fresh per-session transport + McpServer sharing the one core. */ + async function openSession(): Promise { + // Pre-generate the session id so it can scope this session's audit-log + // client id and rate-limit bucket: registerTools needs it now, whereas the + // transport would only assign transport.sessionId later, during initialize. + const sessionId = randomUUID(); + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => sessionId, + enableDnsRebindingProtection: true, + allowedHosts, + onsessioninitialized: (id) => { + sessions.set(id, transport); + console.error(`MCP session opened: ${id} (active: ${sessions.size})`); + }, + onsessionclosed: (id) => { + sessions.delete(id); + console.error(`MCP session closed: ${id} (active: ${sessions.size})`); + }, + }); + transport.onclose = () => { + if (transport.sessionId) { + sessions.delete(transport.sessionId); + } + }; + + const server = new McpServer({ name: 'code-executor-mcp-server', version: VERSION }); + registerTools(core, server, sessionId); + // Must finish connecting (wires onmessage + starts the transport) BEFORE the + // initialize message is handled, or the first message would be dropped. + await server.connect(transport); + return transport; + } + + const httpServer = createServer((req, res) => { + void handleHttp(req, res).catch((error) => { + console.error('HTTP request error:', error); + if (!res.headersSent) { + sendRpcError(res, 500, 'Internal server error'); + } + }); + }); + + async function handleHttp(req: IncomingMessage, res: ServerResponse): Promise { + const url = new URL(req.url ?? '/', `http://${host}:${port}`); + + // Unauthenticated readiness probe for cectl / launchd (no code execution). + if (req.method === 'GET' && url.pathname === HEALTH_PATH) { + sendJson(res, 200, { healthy: true, sessions: sessions.size, version: VERSION }); + return; + } + + if (url.pathname !== MCP_PATH) { + sendRpcError(res, 404, 'Not found'); + return; + } + + if (authEnabled && !isAuthorized(req, token as string)) { + res + .writeHead(401, { 'Content-Type': 'application/json', 'WWW-Authenticate': 'Bearer' }) + .end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32001, message: 'Unauthorized' }, id: null })); + return; + } + + const sessionId = req.headers['mcp-session-id']; + const existing = typeof sessionId === 'string' ? sessions.get(sessionId) : undefined; + + if (req.method === 'POST') { + if (existing) { + // Established session — let the SDK read/handle the body. + await existing.handleRequest(req, res); + return; + } + if (typeof sessionId === 'string') { + // A session id was presented but we do not know it (expired / restarted). + sendRpcError(res, 404, 'Unknown or expired session — re-initialize'); + return; + } + // No session id: only an initialize request may open a new session. + let body: unknown; + try { + body = await readJsonBody(req); + } catch { + sendRpcError(res, 400, 'Invalid JSON body'); + return; + } + if (!isInitializeRequest(body)) { + sendRpcError(res, 400, 'Missing Mcp-Session-Id (only an initialize request may omit it)'); + return; + } + const transport = await openSession(); + await transport.handleRequest(req, res, body); + return; + } + + if (req.method === 'GET' || req.method === 'DELETE') { + // SSE stream (GET) or explicit session close (DELETE) — both require a known session. + if (!existing) { + sendRpcError(res, 404, 'Unknown or expired session — re-initialize'); + return; + } + await existing.handleRequest(req, res); + return; + } + + sendRpcError(res, 405, 'Method not allowed'); + } + + await new Promise((resolve, reject) => { + httpServer.once('error', reject); + httpServer.listen(port, host, () => { + httpServer.removeListener('error', reject); + resolve(); + }); + }); + console.error( + `Code Executor MCP HTTP server listening on http://${host}:${port}${MCP_PATH} (auth: ${authEnabled ? 'on' : 'OFF'})` + ); + + // Lifecycle: on a signal, stop accepting connections, close every session, then + // drain the shared core and exit. launchd restarts the process on the next need. + let shuttingDown = false; + const shutdown = async (signal: string): Promise => { + if (shuttingDown) { + return; + } + shuttingDown = true; + console.error(`Received ${signal}, shutting down HTTP server...`); + httpServer.close(); + for (const transport of sessions.values()) { + try { + await transport.close(); + } catch { + // best effort — the core drain + exit backstop below still runs + } + } + sessions.clear(); + await core.shutdown(); + process.exit(0); + }; + + process.on('SIGINT', () => void shutdown('SIGINT')); + process.on('SIGTERM', () => void shutdown('SIGTERM')); + process.on('SIGHUP', () => void shutdown('SIGHUP')); + // Synchronous last-resort cleanup so a hard exit never orphans downstream children. + process.on('exit', () => { + try { + core.killChildrenSync(); + } catch { + // Nothing actionable during exit. + } + }); +} diff --git a/src/index.ts b/src/index.ts index d067501..be1290b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,676 +10,46 @@ */ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; -import { z } from 'zod'; -import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck, getParentPollIntervalMs } from './config/loader.js'; -import { ExecuteTypescriptInputSchema, ExecutePythonInputSchema, ExecutionResultSchema } from './config/schemas.js'; -import { MCPClientPool } from './mcp/client-pool.js'; +import { getParentPollIntervalMs } from './config/loader.js'; import { watchClientDisconnect } from './mcp/stdin-watcher.js'; import { watchParentExit } from './mcp/parent-watcher.js'; import { redirectConsoleLogToStderr } from './utils/stdio-guard.js'; -import { SecurityValidator } from './validation/security-validator.js'; -import { ConnectionPool } from './mcp/connection-pool.js'; -import { RateLimiter } from './security/rate-limiter.js'; -import { executeTypescriptInSandbox } from './executors/sandbox-executor.js'; -import { executePythonInSandbox as executePythonNative } from './executors/python-executor.js'; -// Pyodide is loaded lazily — only imported when PYTHON_SANDBOX_READY=true. -// This keeps the 13MB pyodide WASM out of `bun --compile` binaries that don't need it. -type ExecutePythonPyodideFn = typeof import('./executors/pyodide-executor.js').executePythonInSandbox; -import { formatErrorResponse, formatExecutionResultForCli } from './utils/utils.js'; -import { ErrorType } from './types.js'; -import { checkDenoAvailable, getDenoVersion, getDenoInstallMessage } from './executors/deno-checker.js'; -import { HealthCheckServer } from './core/server/health-check.js'; import { VERSION } from './version.js'; -import type { MCPExecutionResult } from './types.js'; import { detectMCPConfigLocation, getToolDisplayName } from './cli/config-location-detector.js'; +import { SharedCore, registerTools } from './core/shared-core.js'; /** - * Health check response schema (Zod) - * Used as outputSchema for the health tool - */ -const HealthCheckOutputSchema = z.object({ - healthy: z.boolean().describe('Overall health status'), - auditLog: z.object({ - enabled: z.boolean().describe('Audit logging enabled'), - }).describe('Audit log configuration'), - mcpClients: z.object({ - connected: z.number().describe('Number of connected MCP tools'), - }).describe('MCP client connections'), - connectionPool: z.object({ - active: z.number().describe('Active concurrent executions'), - waiting: z.number().describe('Queued executions waiting'), - max: z.number().describe('Maximum concurrent limit'), - }).describe('Connection pool status'), - uptime: z.number().describe('Server uptime in seconds'), - timestamp: z.string().describe('ISO 8601 timestamp'), -}); - -/** - * Main server class + * Main server class (stdio transport) + * + * Thin wrapper over {@link SharedCore}: builds the shared, transport-agnostic + * components once and registers the tool set on the stdio `McpServer`. All + * shared behavior lives in SharedCore so a future HTTP transport can reuse it; + * this class owns only the stdio-specific concerns (transport, disconnect / + * parent-death watchers, and process exit). */ class CodeExecutorServer { + private core: SharedCore; private server: McpServer; - private mcpClientPool: MCPClientPool; - private securityValidator: SecurityValidator; - private connectionPool: ConnectionPool; - private rateLimiter: RateLimiter | null = null; - private denoAvailable: boolean = false; - private healthCheckServer: HealthCheckServer | null = null; - private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts - // Resolves when the downstream MCP client pool has finished initializing. - // The pool is initialized in the BACKGROUND (see start()) so the upstream MCP - // handshake is never blocked by slow/unreachable downstream servers. Tool - // handlers await this before executing so downstream tools are ready (or have - // been determined unavailable) by the time code runs. - private poolReady: Promise = Promise.resolve(); // Halts the active parent-liveness poll (see start()). Null until start() wires it. private stopParentWatch: (() => void) | null = null; + // Guards process exit against concurrent shutdown triggers (signal-handler + // races, or a signal racing the stdin/parent watchers). The original class + // used a single shutdown() whose in-progress guard ensured only the FIRST + // trigger drained-then-exited while later triggers were ignored; keeping that + // here preserves that behavior so the graceful drain is never cut short by a + // duplicate trigger reaching process.exit. + private shuttingDown = false; constructor() { + // Build the shared core (downstream MCP pool, validators, connection pool). + this.core = new SharedCore(); + // Initialize MCP server this.server = new McpServer({ name: 'code-executor-mcp-server', version: VERSION, }); - - // Initialize components - this.mcpClientPool = new MCPClientPool(); - this.securityValidator = new SecurityValidator(); - this.connectionPool = new ConnectionPool(100); // Max 100 concurrent executions - - // Rate limiter will be initialized after config is loaded - this.rateLimiter = null; - - // Deno availability checked in start() - this.denoAvailable = false; - - // Health check server will be initialized in start() - this.healthCheckServer = null; - - // Note: registerTools() is called in start() after config initialization - } - - /** - * Handle tool execution errors with standardized response format - */ - private handleToolError(error: unknown, errorType: ErrorType) { - const errorResponse = formatErrorResponse(error, errorType); - return { - content: [{ - type: 'text' as const, - text: JSON.stringify(errorResponse, null, 2), - }], - isError: true, - }; - } - - /** - * Check rate limit before executing code - * - * Returns error response if rate limited, null otherwise. - */ - private async checkRateLimit(): Promise | null> { - if (!this.rateLimiter) { - return null; // Rate limiting disabled - } - - // Use 'default' as client ID since MCP servers run locally - // In a networked environment, this would be the client IP - const result = await this.rateLimiter.checkLimit('default'); - - if (!result.allowed) { - const error = new Error( - `Rate limit exceeded. Maximum ${getRateLimitConfig()?.maxRequests ?? 30} requests per ` + - `${(getRateLimitConfig()?.windowMs ?? 60000) / 1000}s. ` + - `Try again in ${Math.ceil(result.resetIn / 1000)}s.` - ); - return this.handleToolError(error, ErrorType.VALIDATION); - } - - return null; - } - - - /** - * Register MCP tools - */ - private registerTools(): void { - // Tool 1: Execute TypeScript (only if Deno is available) - if (this.denoAvailable) { - const typescriptToolConfig: Parameters[1] = { - title: 'Execute TypeScript with MCP Access', - description: `Execute TypeScript/JavaScript code in a secure Deno sandbox with access to MCP tools. - -Executed code has access to callMCPTool(toolName, params) function for calling other MCP servers. -Import DopaMind wrappers: import { codereview } from './servers/zen/codereview' - -**NEW: In-Sandbox Tool Discovery** -Three discovery functions are injected into the sandbox for self-service tool exploration: - -1. discoverMCPTools(options?) - Discover all available MCP tools - - Options: { search?: string[] } - Array of keywords to filter tools (OR logic) - - Returns: ToolSchema[] - Array of tool schemas - - Example: const tools = await discoverMCPTools({ search: ['file', 'read'] }); - -2. getToolSchema(toolName) - Get detailed schema for a specific tool - - Parameter: toolName (string) - Full tool name (e.g., 'mcp__filesystem__read_file') - - Returns: ToolSchema | null - Tool schema or null if not found - - Example: const schema = await getToolSchema('mcp__filesystem__read_file'); - -3. searchTools(query, limit?) - Search tools by keywords with result limiting - - Parameters: query (string), limit (number, default: 10) - - Returns: ToolSchema[] - Filtered and limited tool schemas - - Example: const fileTools = await searchTools('file read write', 5); - -**Proactive Workflow Example:** -// Discover tools, inspect schema, then execute -const networkTools = await searchTools('fetch url'); -const schema = await getToolSchema(networkTools[0].name); -const result = await callMCPTool(networkTools[0].name, { url: 'https://...' }); - -Security: -- Only tools in allowedTools array can be called -- Deno sandbox permissions enforce file system and network restrictions -- Execution timeout prevents infinite loops -- All executions are audit logged - -Args: - - code (string): TypeScript/JavaScript code to execute - - allowedTools (string[]): MCP tools whitelist (default: []) - Format: ['mcp____', ...] - Example: ['mcp__zen__codereview', 'mcp__filesystem__read_file'] - - timeoutMs (number): Execution timeout in milliseconds (default: 30000) - - permissions (object): Deno sandbox permissions - - read (string[]): Allowed read paths - - write (string[]): Allowed write paths - - net (string[]): Allowed network hosts - - skipDangerousPatternCheck (boolean): Accepted for backward compatibility but IGNORED (issue #56) - Per-call skipping is intentionally disabled so a caller cannot bypass the check. - Validation can only be disabled SERVER-SIDE via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS - env var (=true) or the security.skipDangerousPatternCheck config option (operator decision). - NOTE: Dangerous pattern validation is defense-in-depth only, NOT a security boundary - Real security comes from sandbox permissions, resource limits, and process isolation - -Returns: - { - "success": boolean, - "output": string, // stdout from console.log() - "error": string, // Error message if failed - "executionTimeMs": number, - "toolCallsMade": string[], // MCP tools called - "toolCallSummary": ToolCallSummaryEntry[] // Aggregated tool call metrics - } - -Example: - { - "code": "const result = await callMCPTool('mcp__zen__codereview', {...}); console.log(result);", - "allowedTools": ["mcp__zen__codereview"], - "timeoutMs": 60000 - }`, - inputSchema: { - code: z.string().min(1).describe('TypeScript/JavaScript code to execute'), - allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist'), - timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout in milliseconds'), - permissions: z.object({ - read: z.array(z.string()).optional(), - write: z.array(z.string()).optional(), - net: z.array(z.string()).optional(), - }).default({}).describe('Deno sandbox permissions'), - skipDangerousPatternCheck: z.boolean().optional().describe('Accepted but IGNORED for security (issue #56): per-call skipping is disabled. Validation can only be disabled server-side via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS env var or security.skipDangerousPatternCheck config option.'), - enableSampling: z.boolean().optional().default(false).describe('Enable LLM sampling (llm.ask/llm.think helpers)'), - maxSamplingRounds: z.number().int().min(1).max(100).optional().default(10).describe('Max sampling rounds'), - maxSamplingTokens: z.number().int().min(100).max(100000).optional().default(10000).describe('Max sampling tokens'), - samplingSystemPrompt: z.string().optional().describe('Custom system prompt for sampling'), - allowedSamplingModels: z.array(z.string()).optional().describe('Allowed Claude models for sampling'), - }, - outputSchema: ExecutionResultSchema.shape, - annotations: { - readOnlyHint: false, - destructiveHint: false, - idempotentHint: false, - openWorldHint: true, - }, - }; - - const typescriptToolHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { - try { - // Check rate limit - const rateLimitError = await this.checkRateLimit(); - if (rateLimitError) { - return rateLimitError; - } - - // Validate input with Zod schema (runtime validation) - const parseResult = ExecuteTypescriptInputSchema.safeParse(args); - if (!parseResult.success) { - return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - output: '', - error: `Input validation failed: ${parseResult.error.message}`, - executionTimeMs: 0, - }, null, 2), - }], - isError: true, - }; - } - const input = parseResult.data; - - // Validate security - this.securityValidator.validateAllowlist(input.allowedTools); - await this.securityValidator.validatePermissions(input.permissions); - - // Hybrid skip logic: - // 1. Config/Env variable ONLY (Issue #56 - Security Fix) - // User input is ignored to prevent security bypass - const skipPatternCheck = shouldSkipDangerousPatternCheck(); - const codeValidation = this.securityValidator.validateCode(input.code, skipPatternCheck); - - if (!codeValidation.valid) { - return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - output: '', - error: codeValidation.errors.join('\n'), - executionTimeMs: 0, - }, null, 2), - }], - isError: true, - }; - } - - // Ensure the downstream MCP pool has finished initializing (it is set - // up in the background at startup) so callMCPTool/discovery see the - // connected servers. Bounded by per-server connect timeouts. - await this.poolReady; - - // Execute code with connection pooling - const result = await this.connectionPool.execute(async () => { - return await executeTypescriptInSandbox( - { - code: input.code, - allowedTools: input.allowedTools, - timeoutMs: input.timeoutMs, - permissions: input.permissions, - skipDangerousPatternCheck: skipPatternCheck, - enableSampling: input.enableSampling, - maxSamplingRounds: input.maxSamplingRounds, - maxSamplingTokens: input.maxSamplingTokens, - samplingSystemPrompt: input.samplingSystemPrompt, - allowedSamplingModels: input.allowedSamplingModels, - }, - this.mcpClientPool, - this.server.server // Pass underlying Server instance with request() method for MCP sampling - ); - }); - - // Audit log - await this.securityValidator.auditLog( - { - executor: 'typescript', - allowedTools: input.allowedTools, - toolsCalled: result.toolCallsMade ?? [], - executionTimeMs: result.executionTimeMs, - success: result.success, - error: result.error, - clientId: 'default', // MCP servers run locally - memoryUsage: process.memoryUsage().heapUsed, - }, - input.code - ); - - return { - content: [{ - type: 'text' as const, - text: formatExecutionResultForCli(result), - }], - structuredContent: result as MCPExecutionResult, - isError: !result.success, - }; - } catch (error) { - return this.handleToolError(error, ErrorType.EXECUTION); - } - }; - - this.server.registerTool( - 'executeTypescript', - typescriptToolConfig, - typescriptToolHandler - ); - } - - // Tool 2: Execute Python (optional, enabled via config) - // SECURITY GATE: Check if Python sandbox is ready - // Issue #50/#59: Python executor has NO sandbox isolation until Pyodide is implemented - const PYTHON_SANDBOX_READY = process.env.PYTHON_SANDBOX_READY === 'true'; - - if (isPythonEnabled()) { - if (!PYTHON_SANDBOX_READY) { - // Register stub handler that returns security warning - console.error('⚠️ Python executor DISABLED (CRITICAL security vulnerability #50)'); - console.error(' Current Python executor has NO sandbox - full filesystem/network access!'); - console.error(' Set PYTHON_SANDBOX_READY=true only after implementing Pyodide sandbox (issue #59)'); - - const pythonSecurityStubConfig: Parameters[1] = { - title: 'Execute Python with MCP Access (DISABLED - Security Issue)', - description: `⚠️ CRITICAL SECURITY WARNING ⚠️ - -Python executor is currently DISABLED due to lack of sandbox isolation. - -VULNERABILITY: Issue #50 - Python executor has NO sandbox -- Current implementation runs with full filesystem access -- No network isolation (can access localhost services, cloud metadata) -- Pattern-based security is easily bypassed -- Execution via native subprocess.spawn() with zero restrictions - -SOLUTION IN PROGRESS: Issue #59 - Pyodide WebAssembly sandbox -- Same security model as Deno (WASM isolation) -- Virtual filesystem (no host access) -- Network restricted to MCP proxy only -- Industry-proven approach (Pydantic, JupyterLite) - -DO NOT enable this tool until Pyodide implementation is complete. -See: https://github.com/aberemia24/code-executor-MCP/issues/50 - -This tool is DISABLED for your protection.`, - inputSchema: { - code: z.string().min(1).describe('Python code (DISABLED)'), - allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist (DISABLED)'), - timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout (DISABLED)'), - }, - outputSchema: ExecutionResultSchema.shape, - annotations: { - readOnlyHint: false, - destructiveHint: false, - idempotentHint: false, - openWorldHint: false, - }, - }; - - const pythonSecurityStubHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { - return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - output: '', - error: '🔴 CRITICAL: Python executor disabled due to security vulnerability.\n\n' + - 'ISSUE: No sandbox protection exists in current implementation (issue #50).\n' + - '- Full filesystem access (can read /etc/passwd, SSH keys, etc.)\n' + - '- Full network access (SSRF to localhost services, cloud metadata endpoints)\n' + - '- Pattern-based blocking is easily bypassed\n\n' + - 'SOLUTION: Pyodide WebAssembly sandbox implementation in progress (issue #59).\n' + - '- Same security model as Deno executor\n' + - '- Virtual filesystem isolation\n' + - '- Network restricted to authenticated MCP proxy\n\n' + - 'This tool will remain disabled until the security fix is complete.\n' + - 'For updates: https://github.com/aberemia24/code-executor-MCP/issues/50', - executionTimeMs: 0, - }, null, 2), - }], - isError: true, - }; - }; - - this.server.registerTool( - 'executePython', - pythonSecurityStubConfig, - pythonSecurityStubHandler - ); - - return; // Exit early - don't register real Python handler - } - - // PYTHON_SANDBOX_READY === true - register real Pyodide handler - const pythonToolConfig: Parameters[1] = { - title: 'Execute Python with MCP Access (Pyodide Sandbox)', - description: `Execute Python code in Pyodide WebAssembly sandbox with access to MCP tools. - -Executed code has access to call_mcp_tool(toolName, params) function for calling other MCP servers. - -Security (Pyodide Sandbox): -- WebAssembly isolation (same security model as Deno) -- Virtual filesystem (no host file access) -- Network restricted to authenticated MCP proxy only -- Only tools in allowedTools array can be called -- Execution timeout prevents infinite loops -- All executions are audit logged - -Args: - - code (string): Python code to execute - - allowedTools (string[]): MCP tools whitelist (default: []) - Format: ['mcp____', ...] - Example: ['mcp__zen__codereview', 'mcp__filesystem__read_file'] - - timeoutMs (number): Execution timeout in milliseconds (default: 30000) - - permissions (object): Subprocess permissions (limited to temp directory and localhost) - - skipDangerousPatternCheck (boolean): Accepted for backward compatibility but IGNORED (issue #56) - Per-call skipping is intentionally disabled so a caller cannot bypass the check. - Validation can only be disabled SERVER-SIDE via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS - env var (=true) or the security.skipDangerousPatternCheck config option (operator decision). - NOTE: Dangerous pattern validation is defense-in-depth only, NOT a security boundary - Real security comes from sandbox permissions, resource limits, and process isolation - -Returns: - { - "success": boolean, - "output": string, // stdout from print() - "error": string, // Error message if failed - "executionTimeMs": number, - "toolCallsMade": string[], // MCP tools called - "toolCallSummary": ToolCallSummaryEntry[] // Aggregated tool call metrics - } - -Example: - { - "code": "result = call_mcp_tool('mcp__zen__codereview', {...}); print(result)", - "allowedTools": ["mcp__zen__codereview"], - "timeoutMs": 60000 - }`, - inputSchema: { - code: z.string().min(1).describe('Python code to execute'), - allowedTools: z.array(z.string()).default([]).describe('MCP tools whitelist'), - timeoutMs: z.number().int().min(1000).default(30000).describe('Timeout in milliseconds'), - permissions: z.object({ - read: z.array(z.string()).optional(), - write: z.array(z.string()).optional(), - net: z.array(z.string()).optional(), - }).default({}).describe('Subprocess permissions'), - skipDangerousPatternCheck: z.boolean().optional().describe('Accepted but IGNORED for security (issue #56): per-call skipping is disabled. Validation can only be disabled server-side via the CODE_EXECUTOR_SKIP_DANGEROUS_PATTERNS env var or security.skipDangerousPatternCheck config option.'), - enableSampling: z.boolean().optional().default(false).describe('Enable LLM sampling (llm.ask/llm.think helpers)'), - maxSamplingRounds: z.number().int().min(1).max(100).optional().default(10).describe('Max sampling rounds'), - maxSamplingTokens: z.number().int().min(100).max(100000).optional().default(10000).describe('Max sampling tokens'), - samplingSystemPrompt: z.string().optional().describe('Custom system prompt for sampling'), - allowedSamplingModels: z.array(z.string()).optional().describe('Allowed Claude models for sampling'), - }, - outputSchema: ExecutionResultSchema.shape, - annotations: { - readOnlyHint: false, - destructiveHint: false, - idempotentHint: false, - openWorldHint: true, - }, - }; - - const pythonToolHandler: Parameters[2] = async (args: any, extra: RequestHandlerExtra) => { - try { - // Check rate limit - const rateLimitError = await this.checkRateLimit(); - if (rateLimitError) { - return rateLimitError; - } - - // Validate input with Zod schema - const parseResult = ExecutePythonInputSchema.safeParse(args); - if (!parseResult.success) { - return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - output: '', - error: `Input validation failed: ${parseResult.error.message}`, - executionTimeMs: 0, - }, null, 2), - }], - isError: true, - }; - } - const input = parseResult.data; - - // Validate security - this.securityValidator.validateAllowlist(input.allowedTools); - await this.securityValidator.validatePermissions(input.permissions); - - // Hybrid skip logic: - // 1. Config/Env variable ONLY (Issue #56 - Security Fix) - // User input is ignored to prevent security bypass - const skipPatternCheck = shouldSkipDangerousPatternCheck(); - const codeValidation = this.securityValidator.validateCode(input.code, skipPatternCheck); - - if (!codeValidation.valid) { - return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - output: '', - error: codeValidation.errors.join('\n'), - executionTimeMs: 0, - }, null, 2), - }], - isError: true, - }; - } - - // Ensure the downstream MCP pool has finished initializing (background - // startup) before executing. Bounded by per-server connect timeouts. - await this.poolReady; - - // Execute code with connection pooling - // Use Pyodide (secure) when PYTHON_SANDBOX_READY, otherwise native (insecure) - // Pyodide loaded lazily so its 13MB WASM stays out of compiled binaries that don't enable it. - let executePythonInSandbox: ExecutePythonPyodideFn; - if (PYTHON_SANDBOX_READY) { - const pyodideMod = await import('./executors/pyodide-executor.js'); - executePythonInSandbox = pyodideMod.executePythonInSandbox; - } else { - executePythonInSandbox = executePythonNative; - } - - const result = await this.connectionPool.execute(async () => { - return await executePythonInSandbox( - { - code: input.code, - allowedTools: input.allowedTools, - timeoutMs: input.timeoutMs, - permissions: input.permissions, - skipDangerousPatternCheck: skipPatternCheck, - enableSampling: input.enableSampling, - maxSamplingRounds: input.maxSamplingRounds, - maxSamplingTokens: input.maxSamplingTokens, - samplingSystemPrompt: input.samplingSystemPrompt, - allowedSamplingModels: input.allowedSamplingModels, - }, - this.mcpClientPool, - this.server.server // Pass underlying Server instance with request() method for MCP sampling - ); - }); - - // Audit log - await this.securityValidator.auditLog( - { - executor: 'python', - allowedTools: input.allowedTools, - toolsCalled: result.toolCallsMade ?? [], - executionTimeMs: result.executionTimeMs, - success: result.success, - error: result.error, - clientId: 'default', // MCP servers run locally - memoryUsage: process.memoryUsage().heapUsed, - }, - input.code - ); - - return { - content: [{ - type: 'text' as const, - text: formatExecutionResultForCli(result), - }], - structuredContent: result as MCPExecutionResult, - isError: !result.success, - }; - } catch (error) { - return this.handleToolError(error, ErrorType.EXECUTION); - } - }; - - this.server.registerTool( - 'executePython', - pythonToolConfig, - pythonToolHandler - ); - } - - // Tool 3: Health Check - this.server.registerTool( - 'health', - { - title: 'Server Health Check', - description: `Get server health status including audit log, MCP connections, connection pool, and uptime. - -Returns: - { - "healthy": boolean, - "auditLog": { "enabled": boolean }, - "mcpClients": { "connected": number }, - "connectionPool": { "active": number, "waiting": number, "max": number }, - "uptime": number - }`, - inputSchema: {}, - outputSchema: HealthCheckOutputSchema.shape, - annotations: { - readOnlyHint: true, - destructiveHint: false, - idempotentHint: true, - openWorldHint: false, - }, - }, - async (args: any, extra: RequestHandlerExtra) => { - try { - const tools = this.mcpClientPool.listAllTools(); - const poolStats = this.connectionPool.getStats(); - - const health = { - healthy: true, - auditLog: { - enabled: this.securityValidator.isAuditLogEnabled(), - }, - mcpClients: { - connected: tools.length, - }, - connectionPool: poolStats, - uptime: process.uptime(), - timestamp: new Date().toISOString(), - }; - - return { - content: [{ - type: 'text' as const, - text: JSON.stringify(health, null, 2), - }], - structuredContent: health, - }; - } catch (error) { - return this.handleToolError(error, ErrorType.EXECUTION); - } - } - ); } /** @@ -688,36 +58,12 @@ Returns: * Errors are propagated to caller for proper error handling. */ async start(): Promise { - // Initialize configuration - console.error('Loading configuration...'); - await initConfig(); - - // Check Deno availability - console.error('Checking Deno availability...'); - this.denoAvailable = await checkDenoAvailable(); + // Pre-tools shared setup: load config, detect Deno, init rate limiter. + await this.core.initialize(); - if (this.denoAvailable) { - const version = getDenoVersion(); - console.error(`✓ Deno ${version ?? 'found'} - TypeScript execution enabled`); - } else { - console.error(getDenoInstallMessage()); - console.error(''); // Empty line for readability - } - - // Register tools (now that config is initialized and Deno checked) - this.registerTools(); - - // Initialize rate limiter if enabled - if (isRateLimitEnabled()) { - const rateLimitConfig = getRateLimitConfig(); - if (rateLimitConfig) { - this.rateLimiter = new RateLimiter({ - maxRequests: rateLimitConfig.maxRequests, - windowMs: rateLimitConfig.windowMs, - }); - console.error(`Rate limiting enabled: ${rateLimitConfig.maxRequests} requests per ${rateLimitConfig.windowMs / 1000}s`); - } - } + // Register tools (now that config is initialized and Deno checked). One host + // per stdio process, so a fixed 'stdio' client id is used for audit/rate-limit. + registerTools(this.core, this.server, 'stdio'); // Start stdio transport FIRST so the upstream MCP handshake (initialize + // tools/list) is answered immediately. The downstream client pool is then @@ -762,41 +108,9 @@ Returns: console.error('Code Executor MCP Server started successfully (downstream MCP pool initializing in background)'); - // Initialize MCP client pool in the background. Tool handlers await - // `poolReady` before executing (see registerTools). Failures are logged but - // never crash the server — code-executor keeps serving whatever connected. - console.error('Initializing MCP client pool...'); - this.poolReady = this.mcpClientPool - .initialize() - .then(() => { - const tools = this.mcpClientPool.listAllTools(); - console.error(`Connected to ${tools.length} MCP tools across multiple servers`); - }) - .catch((error) => { - const message = error instanceof Error ? error.message : String(error); - console.error( - `MCP client pool initialization failed — continuing without downstream tools: ${message}` - ); - }); - - // Initialize health check server (optional, enabled via env var) - const enableHealthCheck = process.env.ENABLE_HEALTH_CHECK !== 'false'; - if (enableHealthCheck) { - console.error('Starting health check server...'); - this.healthCheckServer = new HealthCheckServer({ - mcpClientPool: this.mcpClientPool, - connectionPool: this.connectionPool, - version: VERSION, - }); - - try { - await this.healthCheckServer.start(); - } catch (error) { - console.error('Warning: Failed to start health check server:', error); - // Don't fail the entire server if health check fails to start - this.healthCheckServer = null; - } - } + // Post-transport background services: downstream MCP client pool (kicked off + // in the background, not awaited) and the optional health-check server. + await this.core.startBackgroundServices(); } /** @@ -804,33 +118,28 @@ Returns: * Backstop for the process 'exit' handler (see bottom of file). */ killChildrenSync(): void { - this.mcpClientPool.killChildrenSync(); + this.core.killChildrenSync(); } /** - * Shutdown server - */ - /** - * Graceful shutdown with request draining - * - * P1: Wait for in-flight executions to complete before shutdown. - * Fixes race condition where active TypeScript/Python executions are killed mid-operation. + * Shutdown server, then exit the process. * - * Shutdown sequence: - * 1. Drain connection pool (wait for active executions with 30s timeout) - * 2. Stop health check server - * 3. Clean up rate limiter - * 4. Disconnect MCP clients (with 2s SIGTERM grace period) - * - * @param timeoutMs - Maximum time for entire shutdown (default: 35s = 30s drain + 5s cleanup) + * Delegates the graceful, transport-agnostic drain to SharedCore and owns the + * stdio-specific concerns: stopping the parent-liveness poll and terminating + * the process once the drain completes. */ - async shutdown(timeoutMs: number = 35000): Promise { - // P1: Prevent concurrent shutdown attempts (manual + signal handler races) - if (this.shutdownInProgress) { + async shutdown(): Promise { + // Preserve the original single-guard shutdown semantics: concurrent + // triggers (signal-handler races, or a signal racing the stdin/parent + // watchers) must NOT each drive process.exit. The first trigger drains + // gracefully then exits; duplicates are ignored. Without this guard the + // SharedCore in-progress guard would early-return on a duplicate and this + // wrapper would then call process.exit(0) mid-drain. + if (this.shuttingDown) { console.error('Shutdown already in progress - ignoring duplicate call'); return; } - this.shutdownInProgress = true; + this.shuttingDown = true; // Stop the parent-liveness poll — shutdown is underway (its internal guard // also fires onParentExit at most once, so this is hygiene, not correctness). @@ -839,54 +148,7 @@ Returns: this.stopParentWatch = null; } - const shutdownStart = Date.now(); - - // Wrap entire shutdown in timeout protection - const shutdownPromise = (async () => { - // Phase 1: Drain connection pool (wait for active executions) - console.error('Phase 1: Draining connection pool...'); - try { - await this.connectionPool.drain(30000); // 30s timeout for executions - } catch (error) { - console.error('Error draining connection pool:', error); - } - - // Phase 2: Stop health check server - console.error('Phase 2: Stopping health check server...'); - if (this.healthCheckServer) { - try { - await this.healthCheckServer.stop(); - } catch (error) { - console.error('Error stopping health check server:', error); - } - } - - // Phase 3: Clean up rate limiter - console.error('Phase 3: Cleaning up rate limiter...'); - if (this.rateLimiter) { - this.rateLimiter.destroy(); - } - - // Phase 4: Disconnect MCP clients (with 2s SIGTERM grace period) - console.error('Phase 4: Disconnecting MCP clients...'); - await this.mcpClientPool.disconnect(); - - const elapsed = Date.now() - shutdownStart; - console.error(`✓ Graceful shutdown completed in ${elapsed}ms`); - })(); - - // Race against timeout - const timeoutPromise = new Promise((resolve) => { - setTimeout(() => { - const elapsed = Date.now() - shutdownStart; - console.error( - `⚠️ Shutdown timeout after ${timeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit` - ); - resolve(); - }, timeoutMs); - }); - - await Promise.race([shutdownPromise, timeoutPromise]); + await this.core.shutdown(); process.exit(0); } @@ -898,39 +160,6 @@ export { executeTypescriptInSandbox as executeTypescript } from './executors/san // who need the runtime should `import('code-executor-mcp/dist/executors/pyodide-executor.js')` // directly. Avoiding a static re-export keeps pyodide out of `bun --compile` graphs. -// Start server -const server = new CodeExecutorServer(); - -// P1: Graceful shutdown signal handlers (flag now in CodeExecutorServer class) -const handleShutdownSignal = async (signal: string) => { - console.error(`Received ${signal}, initiating graceful shutdown...`); - - try { - await server.shutdown(); // Internal flag protects against concurrent calls - } catch (error) { - console.error('Error during shutdown:', error); - process.exit(1); - } -}; - -process.on('SIGINT', () => void handleShutdownSignal('SIGINT')); -process.on('SIGTERM', () => void handleShutdownSignal('SIGTERM')); -// SIGHUP: controlling terminal / session leader went away (a common parent-death -// signal). Treat it as a graceful shutdown rather than the default (terminate). -process.on('SIGHUP', () => void handleShutdownSignal('SIGHUP')); - -// Synchronous last-resort cleanup. If the process exits without the async -// graceful path completing (e.g. host sends SIGKILL after a timeout, or an -// unexpected exit), this guarantees spawned downstream MCP children are killed -// rather than left as orphans. Must be synchronous — no async work runs here. -process.on('exit', () => { - try { - server.killChildrenSync(); - } catch { - // Nothing actionable during exit. - } -}); - // Argument parsing: Handle CLI commands const args = process.argv.slice(2); const command = args[0]; @@ -962,40 +191,83 @@ if (command === 'setup') { process.exit(1); }); } else { - // Normal server startup flow (stdio MCP server). + // Server startup flow. // // Reroute console.log/info/debug to stderr BEFORE any server code runs. On // stdio, stdout is the JSON-RPC channel; a stray console.log corrupts it and - // strict hosts (e.g. Claude Desktop) reject the stream. See stdio-guard.ts. - // Scoped to server mode only — the CLI subcommands above keep stdout. + // strict hosts (e.g. Claude Desktop) reject the stream. Harmless in HTTP mode + // (where stdout is not a protocol channel). See stdio-guard.ts. redirectConsoleLogToStderr(); - (async () => { - try { - const location = await detectMCPConfigLocation(); + if (process.env.CODE_EXECUTOR_ROLE === 'http') { + // Single shared HTTP MCP server (typically launchd-managed): every host + // connects to one loopback endpoint instead of spawning its own child. + // Role is selected by env, NOT argv — bun --compile shifts argv. + import('./http/http-server.js') + .then((m) => m.runHttpServer()) + .catch((error) => { + console.error('Fatal error (HTTP server):', error); + process.exit(1); + }); + } else { + // Default: one stdio MCP server per host. + const server = new CodeExecutorServer(); + + // P1: Graceful shutdown signal handlers (in-progress flag lives in the class). + const handleShutdownSignal = async (signal: string): Promise => { + console.error(`Received ${signal}, initiating graceful shutdown...`); + try { + await server.shutdown(); // Internal flag protects against concurrent calls + } catch (error) { + console.error('Error during shutdown:', error); + process.exit(1); + } + }; + process.on('SIGINT', () => void handleShutdownSignal('SIGINT')); + process.on('SIGTERM', () => void handleShutdownSignal('SIGTERM')); + // SIGHUP: controlling terminal / session leader went away (a common + // parent-death signal). Treat it as a graceful shutdown, not the default terminate. + process.on('SIGHUP', () => void handleShutdownSignal('SIGHUP')); + + // Synchronous last-resort cleanup. If the process exits without the async + // graceful path completing (e.g. host sends SIGKILL after a timeout, or an + // unexpected exit), this guarantees spawned downstream MCP children are killed + // rather than left as orphans. Must be synchronous — no async work runs here. + process.on('exit', () => { + try { + server.killChildrenSync(); + } catch { + // Nothing actionable during exit. + } + }); - if (!location.exists) { - // No configuration found - show instructions and exit - const toolName = getToolDisplayName(location.tool); + (async () => { + try { + const location = await detectMCPConfigLocation(); + + if (!location.exists) { + // No configuration found - show instructions and exit + const toolName = getToolDisplayName(location.tool); + + console.error(''); + console.error('❌ No MCP configuration found'); + console.error(''); + console.error('📝 To configure code-executor-mcp, run:'); + console.error(' code-executor-mcp setup'); + console.error(''); + console.error(`Configuration will be created at: ${location.path}`); + console.error(`For tool: ${toolName}`); + console.error(''); - console.error(''); - console.error('❌ No MCP configuration found'); - console.error(''); - console.error('📝 To configure code-executor-mcp, run:'); - console.error(' code-executor-mcp setup'); - console.error(''); - console.error(`Configuration will be created at: ${location.path}`); - console.error(`For tool: ${toolName}`); - console.error(''); + process.exit(1); + } + // Configuration exists - start server + await server.start(); + } catch (error) { + console.error('Fatal error:', error); process.exit(1); } - - // Configuration exists - start server - await server.start(); - } catch (error) { - console.error('Fatal error:', error); - process.exit(1); - } - })(); + })(); + } } diff --git a/tests/integration/http-server.test.ts b/tests/integration/http-server.test.ts new file mode 100644 index 0000000..d33c7f5 --- /dev/null +++ b/tests/integration/http-server.test.ts @@ -0,0 +1,134 @@ +/** + * Integration test for the single-shared-instance HTTP MCP server, run against + * the REAL compiled binary (the deployed artifact), started with + * CODE_EXECUTOR_ROLE=http. Verifies readiness, bearer-token auth, and that an + * initialize handshake opens a session — the security-critical surface of the + * HTTP transport. + * + * Requires a freshly built binary: `npm run build:binary`. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { mkdtempSync, writeFileSync, existsSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = resolve(fileURLToPath(import.meta.url), '..'); +const BIN = resolve(here, '../../bin/code-executor-mcp'); + +// A fixed, uncommon loopback port for the test server (kept off the 39273 default +// so a real running instance is never disturbed). +const PORT = 41573; +const TOKEN = 'test-token-abc123'; +const BASE = `http://127.0.0.1:${PORT}`; +const MCP_HEADERS = { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', +}; +const INITIALIZE_BODY = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'http-integration-test', version: '1.0.0' }, + }, +}); + +let child: ChildProcess | undefined; +let tmpDir: string; + +async function waitFor(check: () => Promise, timeoutMs: number): Promise { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + if (await check()) return true; + await new Promise((r) => setTimeout(r, 150)); + } + return false; +} + +describe.skipIf(!existsSync(BIN))('HTTP MCP server (real binary)', () => { + beforeAll(async () => { + tmpDir = mkdtempSync(join(tmpdir(), 'ce-http-')); + const configPath = join(tmpDir, 'mcp.json'); + writeFileSync(configPath, JSON.stringify({ mcpServers: {} }), 'utf-8'); // no downstream → fast start + + child = spawn(BIN, [], { + env: { + ...process.env, + CODE_EXECUTOR_ROLE: 'http', + CODE_EXECUTOR_HTTP_PORT: String(PORT), + CODE_EXECUTOR_HTTP_TOKEN: TOKEN, + MCP_CONFIG_PATH: configPath, + ENABLE_HEALTH_CHECK: 'false', // avoid the separate :3000 K8s health server + }, + stdio: ['ignore', 'ignore', 'inherit'], + }); + + const ready = await waitFor(async () => { + try { + const res = await fetch(`${BASE}/health`); + return res.ok; + } catch { + return false; + } + }, 20_000); + expect(ready, 'HTTP server did not become ready').toBe(true); + }, 30_000); + + afterAll(() => { + if (child?.pid) { + try { + child.kill('SIGKILL'); + } catch { + /* already gone */ + } + } + if (tmpDir) rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('serves an unauthenticated readiness probe at /health', async () => { + const res = await fetch(`${BASE}/health`); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.healthy).toBe(true); + }); + + it('rejects an /mcp request with no bearer token (401)', async () => { + const res = await fetch(`${BASE}/mcp`, { method: 'POST', headers: MCP_HEADERS, body: INITIALIZE_BODY }); + expect(res.status).toBe(401); + }); + + it('rejects an /mcp request with a wrong bearer token (401)', async () => { + const res = await fetch(`${BASE}/mcp`, { + method: 'POST', + headers: { ...MCP_HEADERS, Authorization: 'Bearer wrong-token' }, + body: INITIALIZE_BODY, + }); + expect(res.status).toBe(401); + }); + + it('opens a session on an authenticated initialize (200 + Mcp-Session-Id)', async () => { + const res = await fetch(`${BASE}/mcp`, { + method: 'POST', + headers: { ...MCP_HEADERS, Authorization: `Bearer ${TOKEN}` }, + body: INITIALIZE_BODY, + }); + expect(res.status).toBe(200); + expect(res.headers.get('mcp-session-id')).toBeTruthy(); + // Drain the response so the connection closes cleanly. + await res.text(); + }); + + it('rejects a non-initialize POST with no session id (400)', async () => { + const res = await fetch(`${BASE}/mcp`, { + method: 'POST', + headers: { ...MCP_HEADERS, Authorization: `Bearer ${TOKEN}` }, + body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }), + }); + expect(res.status).toBe(400); + }); +});