// file: libs/plugins/src/codecall/__tests__/execute.tool.spec.ts import CodeCallConfig from '../providers/code-call.config'; import { RunJournal } from '../runs/run-journal'; import { CodeCallRunStoreToken } from '../runs/run-record.types'; import { RunTelemetryToken } from '../runs/run-spans'; import EnclaveService, { type EnclaveExecutionResult } from '../services/enclave.service'; import ExecuteTool from '../tools/execute.tool'; // Mock the SDK - ToolContext with dependency injection jest.mock('@frontmcp/sdk', () => ({ // The caller's surface CodeCall passes on; these specs run tools outside a tool call. getCallSurface: () => undefined, Tool: (_config: unknown) => (target: T) => target, Provider: (_config: unknown) => (target: T) => target, ProviderScope: { GLOBAL: 'global', REQUEST: 'request' }, // BaseConfig mock for CodeCallConfig to extend BaseConfig: class MockBaseConfig { protected options: Record; constructor(options: Record = {}) { this.options = options; } get(key: string): unknown { return this.options[key]; } }, ToolContext: class MockToolContext { private dependencies = new Map(); scope = { tools: { getTools: jest.fn(() => []), }, runFlow: jest.fn(() => Promise.resolve(null)), }; authInfo = undefined; logger = undefined; constructor(_args?: unknown) { // Mock constructor accepts optional args } get(token: unknown): T { if (!this.dependencies.has(token)) { throw new Error(`Dependency not found: ${(token as { name?: string })?.name || token}`); } return this.dependencies.get(token) as T; } tryGet(token: unknown): T | undefined { return this.dependencies.get(token) as T | undefined; } // Test helper to set dependencies _setDependency(token: unknown, instance: unknown): void { this.dependencies.set(token, instance); } }, })); // Mock extractResultFromCallToolResult jest.mock('../utils', () => ({ ...jest.requireActual('../utils'), extractResultFromCallToolResult: jest.fn((result) => { if (result.isError) { const text = result.content?.[0]?.text; throw new Error(text || 'Tool execution failed'); } const content = result.content?.[0]; if (content?.type === 'text') { try { return JSON.parse(content.text); } catch { return content.text; } } return result.content; }), })); // Helper to create mock EnclaveService function createMockEnclaveService(executeResult?: Partial) { return { execute: jest.fn().mockResolvedValue({ success: true, result: { data: 'test' }, logs: [], timedOut: false, stats: { duration: 10, toolCallCount: 0, iterationCount: 0 }, ...executeResult, }), }; } // Helper to create mock CodeCallConfig function createMockConfig(overrides: Record = {}) { // Build nested structure from flat dot-notation overrides const resolvedVmOverrides: Record = {}; for (const [key, value] of Object.entries(overrides)) { if (key.startsWith('resolvedVm.')) { const nestedKey = key.slice('resolvedVm.'.length); resolvedVmOverrides[nestedKey] = value; } } const defaults = { resolvedVm: { timeoutMs: 5000, allowConsole: false, ...((overrides['resolvedVm'] as Record) || {}), ...resolvedVmOverrides, }, trace: { level: 'failure', maxLines: 20, values: false }, ...overrides, }; return { get: jest.fn((key: string) => { const flatDefaults: Record = { 'resolvedVm.timeoutMs': defaults.resolvedVm.timeoutMs, 'resolvedVm.allowConsole': defaults.resolvedVm.allowConsole, ...overrides, }; return flatDefaults[key]; }), getAll: jest.fn(() => defaults), }; } // Helper to create a configured ExecuteTool instance function createExecuteTool( options: { enclaveResult?: Partial; configOverrides?: Record; runFlowResult?: unknown; tools?: Array<{ name: string; fullName?: string; metadata?: unknown; rawInputSchema?: unknown; outputSchema?: unknown; getInputJsonSchema?: () => unknown; getOutputJsonSchema?: () => unknown; }>; } = {}, ) { const tool = new (ExecuteTool as any)(); const mockEnclave = createMockEnclaveService(options.enclaveResult); const mockConfig = createMockConfig(options.configOverrides); tool._setDependency(EnclaveService, mockEnclave); tool._setDependency(CodeCallConfig, mockConfig); if (options.runFlowResult !== undefined) { tool.scope.runFlow = jest.fn().mockResolvedValue(options.runFlowResult); } if (options.tools) { tool.scope.tools.getTools = jest.fn(() => options.tools); } return { tool, mockEnclave, mockConfig }; } describe('ExecuteTool', () => { describe('Constructor Validation', () => { it('should instantiate ExecuteTool correctly', () => { const tool = new (ExecuteTool as any)(); expect(tool).toBeDefined(); }); }); describe('Result Status Mapping', () => { it('should return ok status on successful execution', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: true, result: { message: 'Hello' }, logs: [], timedOut: false, }, }); const result = await tool.execute({ script: 'return { message: "Hello" };' }); expect(result.status).toBe('ok'); expect(result.result).toEqual({ message: 'Hello' }); }); it('should return ok status with logs when present', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: true, result: 42, logs: ['Log entry 1', 'Log entry 2'], timedOut: false, }, }); const result = await tool.execute({ script: 'return 42;' }); expect(result.status).toBe('ok'); expect(result.result).toBe(42); expect(result.logs).toEqual(['Log entry 1', 'Log entry 2']); }); it('should omit logs when empty array', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: true, result: 'test', logs: [], timedOut: false, }, }); const result = await tool.execute({ script: 'return "test";' }); expect(result.status).toBe('ok'); expect(result.logs).toBeUndefined(); }); it('should return timeout status when script times out', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: true, logs: [], }, configOverrides: { 'resolvedVm.timeoutMs': 3000, }, }); const result = await tool.execute({ script: 'while(true) {}' }); expect(result.status).toBe('timeout'); expect(result.error).toBeDefined(); expect(result.error.message).toContain('timed out'); expect(result.error.message).toContain('3000'); }); it('should return illegal_access status for validation errors', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { code: 'VALIDATION_ERROR', message: 'Access to eval is not allowed', name: 'ValidationError', }, }, }); const result = await tool.execute({ script: 'eval("bad")' }); expect(result.status).toBe('illegal_access'); expect(result.error.kind).toBe('IllegalBuiltinAccess'); expect(result.error.message).toContain('eval'); }); it('should return illegal_access status for ValidationError name', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'ValidationError', message: 'Blocked access to process', }, }, }); const result = await tool.execute({ script: 'process.exit()' }); expect(result.status).toBe('illegal_access'); expect(result.error.kind).toBe('IllegalBuiltinAccess'); }); it('should return tool_error status when tool fails', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'ToolError', toolName: 'users:create', toolInput: { name: 'Test' }, message: 'Database connection failed', code: 'DB_ERROR', details: { host: 'db.example.com' }, }, }, }); const result = await tool.execute({ script: 'await callTool("users:create", {name: "Test"})' }); expect(result.status).toBe('tool_error'); expect(result.error.source).toBe('tool'); expect(result.error.toolName).toBe('users:create'); // Not the tool's arguments either: the sandbox resolves sidecar references in them before the // tool handler sees them, so they may hold data the script itself never had. expect(result.error).not.toHaveProperty('toolInput'); expect(result.error.message).toContain('Database connection failed'); expect(result.error.code).toBe('DB_ERROR'); // The enclave's error data is not sanitized, so it never reaches the client. expect(result.error).not.toHaveProperty('details'); expect(JSON.stringify(result)).not.toContain('db.example.com'); }); it('should return runtime_error status for script exceptions', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'ReferenceError', message: 'undefinedVariable is not defined', stack: 'ReferenceError: undefinedVariable is not defined\n at script:1:1', }, }, }); const result = await tool.execute({ script: 'return undefinedVariable;' }); expect(result.status).toBe('runtime_error'); expect(result.error.source).toBe('script'); expect(result.error.name).toBe('ReferenceError'); expect(result.error.message).toContain('undefinedVariable'); }); it('should return syntax_error status for invalid syntax', async () => { const { tool, mockEnclave } = createExecuteTool(); // Simulate enclave throwing a SyntaxError mockEnclave.execute.mockRejectedValue( Object.assign(new SyntaxError('Unexpected token'), { loc: { line: 1, column: 5 }, }), ); const result = await tool.execute({ script: 'const x =' }); expect(result.status).toBe('syntax_error'); expect(result.error.message).toContain('Unexpected token'); expect(result.error.location).toEqual({ line: 1, column: 5 }); }); it('should return syntax_error for errors containing "syntax" in message', async () => { const { tool, mockEnclave } = createExecuteTool(); mockEnclave.execute.mockRejectedValue(new Error('Invalid syntax near line 5')); const result = await tool.execute({ script: 'bad code' }); expect(result.status).toBe('syntax_error'); expect(result.error.message).toContain('syntax'); }); it('should return runtime_error for unexpected exceptions', async () => { const { tool, mockEnclave } = createExecuteTool(); mockEnclave.execute.mockRejectedValue(new Error('Something unexpected happened')); const result = await tool.execute({ script: 'return 1;' }); expect(result.status).toBe('runtime_error'); expect(result.error.source).toBe('script'); expect(result.error.message).toContain('Something unexpected'); }); it('should return runtime_error without a stack or server paths', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'Error', message: "Cannot find module '/srv/app/node_modules/pkg/index.js'\n at load (/srv/app/dist/main.js:10:5)", stack: 'Error: boom\n at run (/srv/app/node_modules/@enclave-vm/core/index.js:1:2)', }, }, }); const result = await tool.execute({ script: 'return 1;' }); expect(result.status).toBe('runtime_error'); expect(result.error).not.toHaveProperty('stack'); expect(result.error.message).toBe("Cannot find module '[path]'"); }); it('should strip stacks and server paths from errors the enclave throws', async () => { const { tool, mockEnclave } = createExecuteTool(); mockEnclave.execute.mockRejectedValue(new Error('failed reading C:\\srv\\app\\secret.json')); const result = await tool.execute({ script: 'return 1;' }); expect(result.status).toBe('runtime_error'); expect(result.error).not.toHaveProperty('stack'); expect(result.error.message).toBe('failed reading [path]'); }); }); describe('allowedTools Whitelist', () => { it('should allow tool call when in allowedTools list', async () => { const { tool } = createExecuteTool({ runFlowResult: { content: [{ type: 'text', text: '{"id": "123"}' }], isError: false, }, enclaveResult: { success: true, result: { id: '123' }, logs: [], timedOut: false, }, }); // Execute the tool to capture the callTool environment const result = await tool.execute({ script: 'return await callTool("users:get", {id: "123"});', allowedTools: ['users:get', 'users:list'], }); expect(result.status).toBe('ok'); }); it('should block tool call when not in allowedTools list', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'AccessDeniedError', code: 'ACCESS_DENIED', message: 'Tool billing:charge is not in the allowedTools list', }, }, }); const result = await tool.execute({ script: 'return await callTool("billing:charge", {amount: 100});', allowedTools: ['users:get'], }); // The enclave will return this as a runtime error since the tool call fails expect(result.status).toBe('runtime_error'); }); it('should allow all tools when allowedTools is undefined', async () => { const { tool } = createExecuteTool({ runFlowResult: { content: [{ type: 'text', text: '{"result": "ok"}' }], isError: false, }, enclaveResult: { success: true, result: { result: 'ok' }, logs: [], timedOut: false, }, }); const result = await tool.execute({ script: 'return await callTool("any:tool", {});', // allowedTools not specified }); expect(result.status).toBe('ok'); }); it('should block self-reference to codecall tools', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'SelfReferenceError', code: 'SELF_REFERENCE', message: 'Cannot call codecall:execute from within CodeCall', }, }, }); const result = await tool.execute({ script: 'return await callTool("codecall:execute", {script: "return 1;"});', }); expect(result.status).toBe('runtime_error'); }); }); describe('callTool Environment Function', () => { it('should return result directly when throwOnError=true (default)', async () => { const { tool, mockEnclave } = createExecuteTool({ runFlowResult: { content: [{ type: 'text', text: '{"name": "Alice"}' }], isError: false, }, }); // Capture the environment passed to enclave let capturedEnv: unknown; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: { name: 'Alice' }, logs: [], timedOut: false, }; }); await tool.execute({ script: 'return await callTool("users:get", {id: "1"});' }); // Verify the environment has callTool expect(capturedEnv).toBeDefined(); const typedEnv = capturedEnv as { callTool: (...args: unknown[]) => unknown }; expect(typeof typedEnv.callTool).toBe('function'); }); it('should create proper MCP request format for flow', async () => { const { tool, mockEnclave } = createExecuteTool({ runFlowResult: { content: [{ type: 'text', text: '{"id": "user-123"}' }], isError: false, }, // The tool has to be registered for the call to reach the flow at all: since // GHSA-6w3j-82v5-6qrr, a name that resolves to no tool is denied rather than // passed through. A real scope always lists its tools, so registering it here // makes the fixture match reality. tools: [{ name: 'users:create', fullName: 'users:create', metadata: {} }], }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; // Call the captured callTool to verify flow is called correctly await capturedEnv.callTool('users:create', { name: 'Test User' }); return { success: true, result: { id: 'user-123' }, logs: [], timedOut: false, }; }); await tool.execute({ script: 'return await callTool("users:create", {name: "Test User"});' }); expect(tool.scope.runFlow).toHaveBeenCalledWith('tools:call-tool', { request: { method: 'tools/call', params: { name: 'users:create', arguments: { name: 'Test User' }, }, }, ctx: { authInfo: undefined, }, }); }); it('should handle flow returning null (tool not found)', async () => { const { tool, mockEnclave } = createExecuteTool({ runFlowResult: null, // Tool not found }); let thrownError: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { try { await (env as any).callTool('nonexistent:tool', {}); } catch (err) { thrownError = err; } return { success: false, timedOut: false, logs: [], error: { message: thrownError?.message || 'Flow returned no result', }, }; }); const result = await tool.execute({ script: 'await callTool("nonexistent:tool", {});' }); expect(result.status).toBe('runtime_error'); }); }); describe('getTool Environment Function', () => { it("does not describe a tool its authorities withhold from the script's caller", async () => { const mockTools = [ { name: 'admin:purge', fullName: 'admin:purge', metadata: { description: 'Purge everything', authorities: { allow: false } }, getInputJsonSchema: () => ({ type: 'object' }), }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); Object.assign(tool.scope, { authoritiesEngine: { evaluate: async (authorities: { allow: boolean }) => ({ granted: authorities.allow }) }, authoritiesContextBuilder: { build: (authInfo: unknown) => authInfo }, }); mockEnclave.execute.mockImplementation(async (_script: string, env: any) => ({ success: true, result: env.getTool('admin:purge') ?? null, logs: [], timedOut: false, })); const result = await tool.execute({ script: 'return getTool("admin:purge");' }); expect(result.status).toBe('ok'); expect(result.result).toBeNull(); }); it('should find tool by name', async () => { const inputJsonSchema = { type: 'object', properties: { limit: { type: 'number' } } }; const outputJsonSchema = { type: 'object', properties: { users: { type: 'array' } } }; const mockTools = [ { name: 'users:list', fullName: 'users:list', metadata: { description: 'List all users' }, getInputJsonSchema: () => inputJsonSchema, getOutputJsonSchema: () => outputJsonSchema, }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('users:list'), logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("users:list");' }); expect(result.status).toBe('ok'); expect(result.result).toEqual({ name: 'users:list', description: 'List all users', inputSchema: inputJsonSchema, outputSchema: outputJsonSchema, }); expect(result.result.inputSchema).not.toBe(inputJsonSchema); expect(result.result.outputSchema).not.toBe(outputJsonSchema); }); it('should expose null schemas when the tool declares none', async () => { const mockTools = [ { name: 'ping', fullName: 'ping', metadata: { description: 'Ping' }, getInputJsonSchema: () => null, getOutputJsonSchema: () => null, }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('ping'), logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("ping");' }); expect(result.status).toBe('ok'); expect(result.result).toEqual({ name: 'ping', description: 'Ping', inputSchema: null, outputSchema: null, }); }); it('should find tool by fullName when name differs', async () => { const mockTools = [ { name: 'list', fullName: 'users:list', metadata: { description: 'List users' }, getInputJsonSchema: () => ({}), getOutputJsonSchema: () => ({}), }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('users:list'), logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("users:list");' }); expect(result.status).toBe('ok'); expect(result.result.name).toBe('list'); }); it.each(['codecall:invoke', 'codecall:execute', 'CodeCall:Search'])( 'should not describe the CodeCall tool %p', async (name: string) => { const mockTools = [ { name, fullName: name, metadata: { description: 'CodeCall meta-tool' }, getInputJsonSchema: () => ({ type: 'object' }), getOutputJsonSchema: () => ({ type: 'object' }), }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool(name), logs: [], timedOut: false }; }); const result = await tool.execute({ script: `return getTool("${name}");` }); expect(result.status).toBe('ok'); expect(result.result).toBeUndefined(); }, ); it('should not describe tools outside the declared allowedTools whitelist', async () => { const mockTools = [ { name: 'users:list', fullName: 'users:list', metadata: { description: 'List users' }, getInputJsonSchema: () => ({ type: 'object' }), getOutputJsonSchema: () => ({ type: 'object' }), }, { name: 'billing:charge', fullName: 'billing:charge', metadata: { description: 'Charge a card' }, getInputJsonSchema: () => ({ type: 'object' }), getOutputJsonSchema: () => ({ type: 'object' }), }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: { allowed: capturedEnv.getTool('users:list')?.name, denied: capturedEnv.getTool('billing:charge'), }, logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("billing:charge");', allowedTools: ['users:list'], }); expect(result.status).toBe('ok'); expect(result.result).toEqual({ allowed: 'users:list' }); }); it('should return undefined when tool not found', async () => { const { tool, mockEnclave } = createExecuteTool({ tools: [] }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('nonexistent:tool'), logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("nonexistent:tool");' }); expect(result.status).toBe('ok'); expect(result.result).toBeUndefined(); }); it('should expose only plain schema data for a registry entry holding live schemas', async () => { // A registry entry keeps its declared schemas as live objects with behaviour and // pinned internals. Only the JSON Schema projection may reach the sandbox. class LiveSchema { constructor() { Object.defineProperty(this, '_zod', { value: { constr: LiveSchema }, configurable: false, writable: false, enumerable: true, }); } parse(value: unknown): unknown { return value; } } const mockTools = [ { name: 'users:list', fullName: 'users:list', metadata: { description: 'List users' }, rawInputSchema: new LiveSchema(), outputSchema: new LiveSchema(), getInputJsonSchema: () => ({ type: 'object', properties: {} }), getOutputJsonSchema: () => ({ type: 'object', properties: { users: { type: 'array' } } }), }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('users:list'), logs: [], timedOut: false }; }); const result = await tool.execute({ script: 'return getTool("users:list");' }); expect(result.status).toBe('ok'); expect(result.result.inputSchema).toEqual({ type: 'object', properties: {} }); expect(result.result.inputSchema).not.toBeInstanceOf(LiveSchema); expect(result.result.outputSchema).not.toBeInstanceOf(LiveSchema); expect(result.result.inputSchema['_zod']).toBeUndefined(); expect(result.result.outputSchema['_zod']).toBeUndefined(); expect(result.result.inputSchema['parse']).toBeUndefined(); }); it('should report null schemas when a tool entry has no schema accessors', async () => { const mockTools = [{ name: 'legacy:tool', fullName: 'legacy:tool', metadata: { description: 'Legacy' } }]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('legacy:tool'), logs: [], timedOut: false }; }); const result = await tool.execute({ script: 'return getTool("legacy:tool");' }); expect(result.status).toBe('ok'); expect(result.result).toEqual({ name: 'legacy:tool', description: 'Legacy', inputSchema: null, outputSchema: null, }); }); it('should return undefined when the schema projection cannot be represented as plain data', async () => { const circular: Record = { type: 'object' }; circular['self'] = circular; const mockTools = [ { name: 'cyclic:tool', fullName: 'cyclic:tool', metadata: { description: 'Cyclic' }, getInputJsonSchema: () => circular, getOutputJsonSchema: () => null, }, ]; const { tool, mockEnclave } = createExecuteTool({ tools: mockTools }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('cyclic:tool'), logs: [], timedOut: false }; }); const result = await tool.execute({ script: 'return getTool("cyclic:tool");' }); expect(result.status).toBe('ok'); expect(result.result).toBeUndefined(); }); it('should return undefined when getTools throws', async () => { const { tool, mockEnclave } = createExecuteTool(); tool.scope.tools.getTools = jest.fn(() => { throw new Error('Registry unavailable'); }); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: capturedEnv.getTool('any:tool'), logs: [], timedOut: false, }; }); const result = await tool.execute({ script: 'return getTool("any:tool");' }); expect(result.status).toBe('ok'); expect(result.result).toBeUndefined(); }); }); describe('Console and Logging Environment', () => { it('should provide mcpLog function', async () => { const { tool, mockEnclave } = createExecuteTool(); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: null, logs: [], timedOut: false }; }); await tool.execute({ script: 'mcpLog("info", "Test message");' }); expect(typeof capturedEnv.mcpLog).toBe('function'); }); it("keeps a script's mcpLog message on one line of the server log", async () => { const { tool, mockEnclave } = createExecuteTool(); const logger = { info: jest.fn() }; tool.logger = logger; mockEnclave.execute.mockImplementation(async (_script: string, env: any) => { env.mcpLog('info', 'done\n[ERROR] forged entry\r\n', { step: 1 }); return { success: true, result: null, logs: [], timedOut: false }; }); await tool.execute({ script: 'mcpLog("info", "done");' }); const [message, metadata] = logger.info.mock.calls[0]; expect(message).not.toMatch(/[\r\n]/); expect(message).toContain('forged entry'); expect(metadata).toEqual({ step: 1 }); }); it('should provide mcpNotify function', async () => { const { tool, mockEnclave } = createExecuteTool(); let capturedEnv: any; mockEnclave.execute.mockImplementation(async (_script: string, env: unknown) => { capturedEnv = env; return { success: true, result: null, logs: [], timedOut: false }; }); await tool.execute({ script: 'mcpNotify("event", {});' }); expect(typeof capturedEnv.mcpNotify).toBe('function'); }); }); describe('Error Handling Edge Cases', () => { it('should handle non-Error objects thrown', async () => { const { tool, mockEnclave } = createExecuteTool(); mockEnclave.execute.mockRejectedValue('string error'); const result = await tool.execute({ script: 'throw "error";' }); expect(result.status).toBe('runtime_error'); expect(result.error.message).toBe('string error'); }); // Note: null/undefined throws are not tested because execute.tool.ts has a bug // where it tries to access .loc on null/undefined values (line 255). // This should be fixed in the implementation. it('should handle syntax error without location', async () => { const { tool, mockEnclave } = createExecuteTool(); mockEnclave.execute.mockRejectedValue(new SyntaxError('Parse error')); const result = await tool.execute({ script: 'bad syntax' }); expect(result.status).toBe('syntax_error'); expect(result.error.location).toBeUndefined(); }); }); describe('Input Validation Edge Cases', () => { it('should handle empty script', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: true, result: undefined, logs: [], timedOut: false, }, }); const result = await tool.execute({ script: '' }); expect(result.status).toBe('ok'); }); it('should handle script with only whitespace', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: true, result: undefined, logs: [], timedOut: false, }, }); const result = await tool.execute({ script: ' \n\t ' }); expect(result.status).toBe('ok'); }); it('should handle empty allowedTools array (blocks all)', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'AccessDeniedError', code: 'ACCESS_DENIED', message: 'No tools are allowed', }, }, }); const result = await tool.execute({ script: 'await callTool("any:tool", {});', allowedTools: [], }); expect(result.status).toBe('runtime_error'); }); }); describe('A replay that diverged', () => { it('ends with the divergence, whatever the review decided at a call after it', async () => { const { tool } = createExecuteTool({ enclaveResult: { success: false, timedOut: false, logs: [], error: { name: 'RunDivergedError', code: 'RUN_DIVERGED', message: 'The run diverged from its journal: call 1 to "users.get" had other arguments', }, review: { decisions: [ { phase: 'call', toolName: 'users.delete', callIndex: 1, decision: 'needs_approval', durationMs: 1 }, ], }, }, }); const result = await tool.execute({ script: 'return 1;' }); expect(result).toMatchObject({ status: 'runtime_error', error: { name: 'RunDivergedError', message: expect.stringContaining('diverged from its journal') }, }); }); }); describe('Run records', () => { function withRunStore(keep: jest.Mock, enclaveResult?: Partial) { const created = createExecuteTool({ enclaveResult }); const runs = { keepsResultsOf: () => false, keep }; const warn = jest.fn(); created.tool._setDependency(CodeCallRunStoreToken, runs); created.tool.logger = { warn }; return { ...created, warn }; } it('keeps a record of the run and returns its run id', async () => { const keep = jest.fn().mockResolvedValue('run-1'); const { tool, mockEnclave } = withRunStore(keep, { success: true, result: { total: 3 } }); const result = await tool.execute({ script: 'return { total: 3 };' }); expect(result).toEqual({ status: 'ok', result: { total: 3 }, logs: undefined, runId: 'run-1' }); expect(mockEnclave.execute).toHaveBeenCalledWith( 'return { total: 3 };', expect.any(Object), expect.any(RunJournal), undefined, ); expect(keep).toHaveBeenCalledWith( tool, { runId: expect.stringMatching(/^[0-9a-f-]{36}$/), scriptHash: expect.stringMatching(/^[0-9a-f]{64}$/), status: 'ok', startedAt: expect.any(String), endedAt: expect.any(String), reviewDecision: null, resultBytes: '{"total":3}'.length, journal: [], }, undefined, ); }); it('returns no run id when the store keeps nothing for the caller', async () => { const { tool } = withRunStore(jest.fn().mockResolvedValue(undefined), { success: false, error: { name: 'Error', message: 'x' }, }); const result = await tool.execute({ script: 'return 1;' }); expect(result.status).toBe('runtime_error'); expect(result).not.toHaveProperty('runId'); }); it('logs a store that fails and still returns the result', async () => { const { tool, warn } = withRunStore(jest.fn().mockRejectedValue(new Error('store down'))); const result = await tool.execute({ script: 'return 1;' }); expect(result).toMatchObject({ status: 'ok' }); expect(result).not.toHaveProperty('runId'); expect(warn).toHaveBeenCalledWith('codecall: could not keep the run record', { error: 'store down' }); }); it('logs a store that fails with a value that is not an error', async () => { const { tool, warn } = withRunStore(jest.fn().mockRejectedValue('offline')); await tool.execute({ script: 'return 1;' }); expect(warn).toHaveBeenCalledWith('codecall: could not keep the run record', { error: 'offline' }); }); }); describe('Run spans', () => { function withTelemetry(execute?: jest.Mock) { const created = createExecuteTool(); const callSpan = { setAttributes: jest.fn(), end: jest.fn(), endWithError: jest.fn() }; const runSpan = { ...callSpan, startChildSpan: jest.fn(() => callSpan) }; created.tool._setDependency(RunTelemetryToken, { startSpan: jest.fn(() => runSpan) }); if (execute) created.mockEnclave.execute = execute; return { ...created, runSpan, callSpan }; } it('ends the run span with an error when the run throws before the enclave runs', async () => { const { tool, runSpan } = withTelemetry(); (tool as unknown as { dependencies: Map }).dependencies.delete(EnclaveService); await expect(tool.execute({ script: 'return 1;' })).rejects.toThrow('Dependency not found'); expect(runSpan.endWithError).toHaveBeenCalledWith('the run threw before it returned a result'); expect(runSpan.end).not.toHaveBeenCalled(); }); it('ends a call span still open when the enclave throws, and the run span with the run status', async () => { const { tool, runSpan, callSpan } = withTelemetry( jest.fn(async (_script: string, _environment: unknown, journal: RunJournal) => { journal.begin('users.get', { id: 1 }); throw new Error('tool handler crashed'); }), ); const result = await tool.execute({ script: "return await callTool('users.get', { id: 1 });" }); expect(result.status).toBe('runtime_error'); expect(callSpan.setAttributes).toHaveBeenCalledWith( expect.objectContaining({ 'codecall.call.outcome': 'unfinished' }), ); expect(callSpan.end).toHaveBeenCalledTimes(1); expect(runSpan.endWithError).toHaveBeenCalledWith('runtime_error'); }); }); });