Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): reject shell commands that cannot be spawned

Alfredo Lopez5494c97523e2
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index ae1cfe4e2..affae0926 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.501",
+ "version": "0.1.502",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.501",
+ "version": "0.1.502",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 5f434642c..41ab8c29c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.501",
+ "version": "0.1.502",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/orchestration/__tests__/toolUseLoop.shellNul.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.shellNul.test.ts
new file mode 100644
index 000000000..9f1af9053
--- /dev/null
+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.shellNul.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { spawn } from 'child_process'
+import { mkdtemp, rm } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
+import { UnifiedApprovalGateController } from '../../extensions/mcpApprovalGateController'
+import type { ReasoningPort, Tool, ToolRegistry } from '../../interfaces'
+import { BasicSafety } from '../../safety/safety'
+import { ShellTool } from '../../tools/shell'
+import type { AgentEvent, RespondResult } from '../../types'
+import { SimpleEventEmitter } from '../eventEmitter'
+import { buildLoopConfig } from '../loopConfig'
+import { runToolUseLoop } from '../toolUseLoop'
+
+// Real processes would run; the spy only observes whether one was started.
+vi.mock('child_process', async importOriginal => {
+ const actual = await importOriginal<typeof import('child_process')>()
+ return { ...actual, spawn: vi.fn(actual.spawn) }
+})
+
+let workspacePath: string
+
+beforeEach(async () => {
+ workspacePath = await mkdtemp(join(tmpdir(), 'clerum-shell-nul-loop-'))
+ vi.mocked(spawn).mockClear()
+})
+
+afterEach(async () => {
+ await rm(workspacePath, { recursive: true, force: true })
+})
+
+function scriptedReasoning(results: RespondResult[]): ReasoningPort {
+ let index = 0
+ const next = async (): Promise<RespondResult> =>
+ results[index++] ?? { type: 'error', error: new Error('No more results') }
+ return { respondWithTools: vi.fn(next), continueWithToolResults: vi.fn(next) }
+}
+
+function registryWith(tool: Tool): ToolRegistry {
+ return {
+ get: (name: string) => (name === tool.name() ? tool : null),
+ listDefinitions: () => [
+ { name: tool.name(), description: tool.description(), parameters: tool.parametersSchema() },
+ ],
+ register: vi.fn(),
+ }
+}
+
+async function runShellCall(command: string) {
+ const registry = registryWith(new ShellTool(workspacePath, 5_000, ['PATH']))
+ const reasoning = scriptedReasoning([
+ { type: 'tool_calls', calls: [{ id: 'tc_nul', name: 'shell_exec', arguments: { command } }] },
+ { type: 'text', content: 'done' },
+ ])
+ const events = new SimpleEventEmitter()
+ const blocked: AgentEvent[] = []
+ events.on('safety:input_blocked', event => blocked.push(event))
+ const config = buildLoopConfig({
+ reasoning,
+ toolRegistry: registry,
+ safety: new BasicSafety(),
+ events,
+ conversation: makeFakeConversation(),
+ loopController: new UnifiedApprovalGateController(registry),
+ })
+ const result = await runToolUseLoop(config, [{ role: 'user', content: 'run it' }])
+ return { result, blocked, reasoning }
+}
+
+describe('shell_exec NUL commands through the tool loop (#1020)', () => {
+ it('X5: BasicSafety rejects a NUL command before approval and no process is spawned', async () => {
+ const { result, blocked, reasoning } = await runShellCall('printf a\0b')
+
+ expect(result.type).not.toBe('need_approval')
+ expect(blocked).toHaveLength(1)
+ expect(blocked[0]!.data).toMatchObject({
+ toolName: 'shell_exec',
+ errors: ['shell_exec.command must not contain NUL characters'],
+ })
+ // Witness: the loop reached the model again with the validation error as the tool result.
+ expect(reasoning.continueWithToolResults).toHaveBeenCalledOnce()
+ expect(JSON.stringify(vi.mocked(reasoning.continueWithToolResults).mock.calls[0])).toContain(
+ 'Parameter validation failed: shell_exec.command must not contain NUL characters'
+ )
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ it('X5 witness: the same command without NUL reaches approval', async () => {
+ const { result, blocked } = await runShellCall('printf ab')
+
+ expect(blocked).toEqual([])
+ expect(result.type).toBe('need_approval')
+ if (result.type === 'need_approval') {
+ expect(result.approval.tool_name).toBe('shell_exec')
+ expect(result.approval.tool_call_id).toBe('tc_nul')
+ }
+ expect(spawn).not.toHaveBeenCalled()
+ })
+})
diff --git a/mcp-host/src/core/safety/__tests__/safety.test.ts b/mcp-host/src/core/safety/__tests__/safety.test.ts
index fecfd954b..e654bbfd8 100644
--- a/mcp-host/src/core/safety/__tests__/safety.test.ts
+++ b/mcp-host/src/core/safety/__tests__/safety.test.ts
@@ -44,6 +44,19 @@ describe('BasicSafety', () => {
expect(result.errors.join(' ')).toMatch(/service account token/i)
})
+ it('U7: rejects a shell_exec command containing a NUL character (#1020)', () => {
+ const result = safety.validateToolParams('shell_exec', { command: 'printf a\0b' })
+ expect(result).toEqual({
+ is_valid: false,
+ errors: ['shell_exec.command must not contain NUL characters'],
+ })
+ // Witness: the same command without the NUL byte is valid.
+ expect(safety.validateToolParams('shell_exec', { command: 'printf ab' })).toEqual({
+ is_valid: true,
+ errors: [],
+ })
+ })
+
it('allows benign external http_request targets', () => {
const result = safety.validateToolParams('http_request', {
url: 'https://httpbin.org/get',
diff --git a/mcp-host/src/core/safety/safety.ts b/mcp-host/src/core/safety/safety.ts
index 8870dee24..31ecd9991 100644
--- a/mcp-host/src/core/safety/safety.ts
+++ b/mcp-host/src/core/safety/safety.ts
@@ -210,6 +210,13 @@ export class BasicSafety implements Safety {
errors: ['shell_exec.command must be a non-empty string'],
}
}
+ // spawn() throws synchronously on a NUL byte in an argument (#1020).
+ if (command.includes('\0')) {
+ return {
+ is_valid: false,
+ errors: ['shell_exec.command must not contain NUL characters'],
+ }
+ }
const errors = BasicSafety.SHELL_BLOCKED_PATTERNS.filter(rule =>
rule.pattern.test(command)
diff --git a/mcp-host/src/core/tools/__tests__/shell.test.ts b/mcp-host/src/core/tools/__tests__/shell.test.ts
index 3ad34a1ad..e912efaa9 100644
--- a/mcp-host/src/core/tools/__tests__/shell.test.ts
+++ b/mcp-host/src/core/tools/__tests__/shell.test.ts
@@ -659,3 +659,33 @@ describe('ShellTool without the GFS download store (#1019)', () => {
})
})
})
+
+describe('ShellTool start failures (#1020)', () => {
+ beforeEach(() => {
+ vi.mocked(spawn).mockClear()
+ })
+
+ it('U3: resolves a synchronous spawn throw from a NUL env value as a start failure', async () => {
+ const tool = new ShellTool(workspacePath, 5_000, ['PATH'], () => ({ BROKEN: 'a\0b' }))
+ const result = await tool.execute({ command: 'printf never-runs' })
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/^Command failed to start: /)
+ expect(result.content).not.toContain('never-runs')
+ expect(result.duration_ms).toBeGreaterThanOrEqual(0)
+ // Witness: spawn was reached and threw; no process exists to report on.
+ expect(spawn).toHaveBeenCalledOnce()
+ expect(vi.mocked(spawn).mock.results[0]!.type).toBe('throw')
+ })
+
+ it('U4: reports an asynchronous spawn failure (missing cwd) as a start failure', async () => {
+ const missing = join(workspacePath, 'removed-before-spawn')
+ const tool = new ShellTool(missing, 5_000, ['PATH'])
+ const result = await tool.execute({ command: 'printf never-runs' })
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/^Command failed to start: .*ENOENT/)
+ expect(result.content).not.toContain('never-runs')
+ // Witness: spawn returned a child; the failure arrived on its error event.
+ expect(spawn).toHaveBeenCalledOnce()
+ expect(vi.mocked(spawn).mock.results[0]!.type).toBe('return')
+ })
+})
diff --git a/mcp-host/src/core/tools/shell.ts b/mcp-host/src/core/tools/shell.ts
index e0774d220..c4a45e69a 100644
--- a/mcp-host/src/core/tools/shell.ts
+++ b/mcp-host/src/core/tools/shell.ts
@@ -1,4 +1,4 @@
-import { spawn } from 'child_process'
+import { type ChildProcess, spawn } from 'child_process'
import { setTimeout as sleep } from 'node:timers/promises'
import { recordGfsShellOutputLimit } from '../../internalTools/gfsDownloadMetrics'
import { ALL_PROVIDERS, LlmProvider, PROVIDERS } from '../../llm/registryCore'
@@ -215,12 +215,25 @@ export class ShellTool implements Tool {
return new Promise<ToolOutput>(resolve => {
// detached: true makes the child a process group leader so we can kill
// the whole group (shell + grandchildren like `sleep`) with -pid signal.
- const child = spawn('/bin/sh', ['-c', command], {
- cwd: this.workspacePath,
- env: safeEnv,
- stdio: ['ignore', 'pipe', 'pipe'],
- detached: true,
- })
+ let child: ChildProcess
+ try {
+ child = spawn('/bin/sh', ['-c', command], {
+ cwd: this.workspacePath,
+ env: safeEnv,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: true,
+ })
+ } catch (error) {
+ // spawn() throws synchronously for invalid arguments, e.g. a NUL byte in
+ // a dynamic env value that BasicSafety never sees (#1020). No process
+ // exists, so this is a start failure reported as an error result.
+ resolve({
+ content: `Command failed to start: ${error instanceof Error ? error.message : String(error)}`,
+ duration_ms: Date.now() - startTime,
+ is_error: true,
+ })
+ return
+ }
const stdoutBuf: Buffer[] = []
const stderrBuf: Buffer[] = []