Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): reject batched exec commands with one clear error (#101669)

posthog[bot]00c0c2bc6860
diff --git a/services/mcp/schema/exec-command-reference.md b/services/mcp/schema/exec-command-reference.md
index 8e5e6ab589e6..ac789a12c8e4 100644
--- a/services/mcp/schema/exec-command-reference.md
+++ b/services/mcp/schema/exec-command-reference.md
@@ -13,6 +13,8 @@ schema <tool_name> [field_path] — drill into a specific field schema (supports
call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)
```
+**One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel.
+
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
The `learn` command is only registered on hosts that use the guided help catalog (currently Claude web and desktop). On hosts that support MCP apps, CLI mode also registers a separate `render-ui` tool for rendering interactive visualizations.
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index e045c6338d3e..c1b919aff7cd 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -145,6 +145,7 @@ export class ToolInputValidationError extends Error {
export type ExecCommandErrorReason =
| 'unknown_command'
+ | 'batched_command'
| 'unknown_tool'
| 'deprecated_tool'
| 'gated_tool'
diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.md
index 5079c5882e56..6ee77b61861c 100644
--- a/services/mcp/src/templates/sections/cli-syntax.md
+++ b/services/mcp/src/templates/sections/cli-syntax.md
@@ -8,4 +8,6 @@ schema <tool_name> [field_path] — drill into a specific field schema (supports
call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)
```
+**One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel.
+
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 7659e2e3c0c7..a4babe5f2ed2 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -298,6 +298,85 @@ function parseCommand(input: string): { verb: string; rest: string } {
return { verb: trimmed.slice(0, idx), rest: trimmed.slice(idx + 1).trim() }
}
+/** A later line opening with one of these is what separates a batched request
+ * from a legitimately multi-line argument. */
+const EXEC_VERBS = new Set(['learn', 'tools', 'search', 'info', 'schema', 'call'])
+
+/** Bounds on the rejection message, so a long batch or a large JSON body does
+ * not come back as a wall of text. */
+const MAX_LISTED_BATCH_COMMANDS = 5
+const MAX_LISTED_BATCH_COMMAND_LENGTH = 200
+
+function firstToken(line: string): string {
+ const trimmed = line.trim()
+ const idx = trimmed.search(/\s/)
+ return idx === -1 ? trimmed : trimmed.slice(0, idx)
+}
+
+/** Only `call` carries a body that may span lines, so it ends once that body is
+ * complete JSON. That keeps a pretty-printed payload from reading as a batch. */
+function isCompleteCommand(command: string): boolean {
+ const { verb, rest } = parseCommand(command)
+ if (verb !== 'call') {
+ return true
+ }
+ const { rest: jsonBody } = parseCommand(parseCallFlags(rest).rest)
+ if (!jsonBody) {
+ return true
+ }
+ try {
+ JSON.parse(jsonBody)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** Returns undefined for a single command, so only a genuine batch is rejected. */
+function splitBatchedCommands(command: string): string[] | undefined {
+ const lines = command.split('\n')
+ if (lines.length < 2 || !EXEC_VERBS.has(firstToken(lines[0] ?? ''))) {
+ return undefined
+ }
+
+ const commands: string[] = []
+ let current = lines[0] ?? ''
+ for (const line of lines.slice(1)) {
+ if (EXEC_VERBS.has(firstToken(line)) && isCompleteCommand(current)) {
+ commands.push(current.trim())
+ current = line
+ continue
+ }
+ current = `${current}\n${line}`
+ }
+ if (commands.length === 0) {
+ return undefined
+ }
+ commands.push(current.trim())
+ return commands
+}
+
+function batchedCommandMessage(commands: string[]): string {
+ const listed = commands.slice(0, MAX_LISTED_BATCH_COMMANDS)
+ const more = commands.length - listed.length
+ const lines = listed.map((entry) => {
+ const flattened = entry.replace(/\s+/g, ' ')
+ const shown =
+ flattened.length > MAX_LISTED_BATCH_COMMAND_LENGTH
+ ? `${flattened.slice(0, MAX_LISTED_BATCH_COMMAND_LENGTH)}...`
+ : flattened
+ return `- ${shown}`
+ })
+ if (more > 0) {
+ lines.push(`- ...and ${more} more`)
+ }
+ return [
+ `exec runs one command per request, and this request held ${commands.length}.`,
+ 'Send each one as its own exec call. You can issue them in parallel. Commands found:',
+ ...lines,
+ ].join('\n')
+}
+
function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; noSkills: boolean; rest: string } {
let rest = input.trim()
let forceJson = false
@@ -1383,6 +1462,13 @@ export function createExecTool(
// records what was attempted — those are the failures worth counting.
options.trackCommand?.({ exec_verb: verb })
+ // Without this the trailing commands ride along as part of the first one's
+ // argument and come back as an unknown tool name, which explains nothing.
+ const batched = splitBatchedCommands(params.command)
+ if (batched) {
+ throw new ExecCommandError(batchedCommandMessage(batched), 'batched_command')
+ }
+
let gatewayTools: Tool<ZodObjectAny>[] | undefined
/** PostHog's tools plus any third-party tools the caller has connected.
* Resolved at most once per command, and only for commands that need a
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt
index 5a26f6ab7fdb..4fc14ab8fc01 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt
@@ -9,6 +9,8 @@ schema <tool_name> [field_path] — drill into a specific field schema (supports
call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)
```
+**One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel.
+
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
**SKILLS FIRST: HARD REQUIREMENT**
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt
index b0366cfbf6c7..382ac4fbd737 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt
@@ -9,6 +9,8 @@ schema <tool_name> [field_path] — drill into a specific field schema (supports
call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)
```
+**One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel.
+
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
**LEARN FIRST: HARD REQUIREMENT**
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 83cf46e6bd1b..9c0d5859a0ee 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -8,6 +8,8 @@ schema <tool_name> [field_path] — drill into a specific field schema (supports
call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)
```
+**One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel.
+
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
#### Metric discovery (semantic layer)
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 813af877d638..fc83ab5be836 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -1217,6 +1217,30 @@ describe('exec tool', () => {
})
})
+ describe('batched commands', () => {
+ it.each([
+ ['info mock-tool\ninfo other-tool', 2],
+ ['search flags\ncall mock-tool {}\ninfo mock-tool', 3],
+ ])('rejects %j and names each command', async (command, expected) => {
+ const exec = createExec()
+ await expect(exec.handler(mockContext, { command })).rejects.toThrow(
+ `exec runs one command per request, and this request held ${expected}.`
+ )
+ })
+
+ it.each([
+ ['a JSON body split over lines', 'call mock-tool {\n "query": "SELECT 1"\n}'],
+ ['a JSON body with a key named after a verb', 'call mock-tool {\n "search": "flags"\n}'],
+ ])('runs a single call with %s', async (_label, command) => {
+ const tool = makeMockTool({
+ schema: z.object({ query: z.string().optional(), search: z.string().optional() }),
+ handler: async () => ({ ok: true }),
+ })
+ const exec = createExec([tool])
+ await expect(exec.handler(mockContext, { command })).resolves.toBeDefined()
+ })
+ })
+
describe('info command', () => {
it('returns YAML for the top shape with the input schema embedded as JSON', async () => {
const tool = makeMockTool({ schema: z.object({ name: z.string().describe('Person name') }) })