Why MCP Tool Approval Does Not Stop Startup-Time Code Execution

Why MCP Tool Approval Does Not Stop Startup-Time Code Execution

pr0h0••21 min read•hacking
AI Usage (76%)
On this page

Why MCP tool approval protects a later boundary than server startup

Tool approval prompts do not stop startup-time code execution in MCP servers. That is the practical lesson in the reported MIOU behavior attributed to the Cloud Security Alliance: the part worth paying attention to is not that a tool call can do damage—tool calls are meant to do things—but when the server code runs.

The seed I was given describes MCP servers that execute code at startup, before the user has approved any tool. If that ordering is real, then every approval dialog you've seen in an MCP client was guarding a boundary that had already been crossed. The prompt was still open while the process was already running. This walkthrough traces that trust boundary and then hardens the controls that actually matter: package provenance, process isolation, credential scope, and outbound network egress.

That changes where you put the defenses. If the dangerous moment is "the user clicks Approve on read_file," then careful UX, scoped tool descriptions, and per-tool permissions are the right controls. If the dangerous moment is "the client spawns npx -y some-mcp-server@latest," then you need package provenance, process isolation, credential scope, and egress control. Those are different controls for different boundaries. The second set is the one that actually contains a hostile server.

Where startup-time execution sits in the MCP server lifecycle

A local MCP server over stdio is a child process that an AI agent client launches from configuration and then talks to over stdin and stdout. Approving a tools/call request is a protocol-level decision made by the client, long after the process exists and long after Node.js has evaluated the module's top-level code.

So the claim comes down to something you can test: does anything observable happen between spawn() and the first tools/call? Yes, by construction. Module evaluation, imports, top-level statements, and whatever they trigger all run before the first byte of JSON-RPC is read.

A tool approval is not a sandbox for the MCP server process

My position: MCP tool approval controls tool invocation. Treating it as a control on the executable that implements the tools is a category error. Approving a call doesn't give the server new authority; the server already had it. Approval only gates whether the client will ask the server to use that authority in a specific way.

The practical result is simple: an MCP server you haven't reviewed should be treated as arbitrary code execution on your workstation, the same way an unreviewed postinstall script should be. The approval prompt is not a mitigation for that. Any hardening guide that starts at the approval prompt has skipped the part that matters.

What the MIOU source establishes—and what still needs verification

A headline and a snippet, not a report

I'll be blunt about the evidence I got. The supplied material is a Google News RSS aggregator link with the headline "MIOU: Trojanized MCP Servers That Run Before Approval Prompts," attributed to the Cloud Security Alliance, plus a one-line snippet that repeats the headline. That's all. I don't have the CSA article body, the threat model section, the affected-client list, or any indicators.

📝

The RSS URL I received is an aggregator redirect, not the CSA article URL. I have not linked it as if it were the primary source, and I have not invented a canonical CSA permalink.

So the confirmed claim, in the narrow sense of "this is what the source says," is: CSA published something describing trojanized MCP servers that execute before approval prompts, and called the concept MIOU. The part I can verify from first principles—that a stdio server process starts before any tool call—stands on its own. The report's specifics I cannot verify.

Resolve the original Cloud Security Alliance page before quoting a timeline

The feed metadata carries 2026-12-05T20:15:38.000Z. Aggregator timestamps are feed artifacts. They get regenerated, re-crawled, and sometimes point at an update rather than the original publication. Before you write a timeline like "MIOU was disclosed on X, clients patched on Y," you need the date on the CSA page itself and the revision history if it shows one.

I haven't done that verification, so I'm not asserting a timeline, an affected-client list, a package name, a version range, a payload, or a set of IOCs. If a later version of this post includes them, they should be tied to the primary advisory.

Three evidence categories used in this analysis

CategoryMeaningHow I mark it here
Source-reportedThe CSA seed says so; I did not read the full report"the seed describes," "reported"
Local fixtureRuns against a probe I wrote, in a temp directory, with synthetic valuesshown as expected output, labeled as expected
InferenceFollows from how Node.js and stdio transports work, not tested end to end"likely," "expected," "untested"

I did not run a live MCP client against a trojanized server for this post, and I won't present computed output as captured evidence. The commands below are what I would run. The blocks labeled expected are what I expect them to print.

Trace the local MCP server lifecycle before any tool call

From MCP server configuration to launched process

A typical local server entry, as clients store it, looks like this:

{
  "mcpServers": {
    "example": {
      "command": "npx",
      "args": ["-y", "[email protected]"],
      "env": { "SERVICE_API_KEY": "..." }
    }
  }
}

Read that as an execution plan, not a configuration. The chain is:

  1. The client reads command and args.
  2. The client resolves npx on PATH (or uses an absolute path if configured that way).
  3. npx checks the local cache; on a miss it downloads the tarball from the registry and unpacks it into the npm cache.
  4. npx launches Node against the package's declared bin entry.
  5. Node resolves import/require specifiers.
  6. Node evaluates the entry module's top-level code.
  7. Only then does the process reach whatever code registers a transport and starts reading stdin.

Steps 3 through 6 are code execution under your user account. Step 7 is the first point where MCP exists as a protocol.

MCP protocol activity is a separate timeline

The official lifecycle is documented in the MCP specification: the client sends initialize, the server responds with its protocolVersion and capabilities, the client sends notifications/initialized, and only then does the client discover tools with tools/list. A tools/call request comes after discovery, after whatever UI review the client does, and after the user decides.

The transport section matters here too. The stdio transport is explicit that the server reads newline-delimited JSON-RPC from stdin and writes messages to stdout. It also says anything the server wants to log must go to stderr. That constraint isn't cosmetic; it will bite you in the next section.

Sequence: startup code runs before any tool approval gate

user adds server config
        |
        v
client reads command/args/env
        |
        v
spawn(command, args, { env })  -----------> OS creates process
        |                                        |
        |                                        v
        |                                   Node starts
        |                                        |
        |                                        v
        |                          +---------------------------+
        |                          | module resolution         |
        |                          | top-level code evaluation |  <-- arbitrary code
        |                          | imports, side effects     |      runs here
        |                          +---------------------------+
        |                                        |
        |                                        v
        |                                   reads stdin
        v
client -> initialize            <-- protocol begins, still no approval
client <- initialize result
client -> notifications/initialized
client -> tools/list            <-- discovery: metadata only
client <- tools list
        |
        v
[ client renders approval UI ]  <-- the gate everyone trusts
        |
        v
client -> tools/call            <-- first approved invocation

The box marked "arbitrary code runs here" sits above the approval gate, not below it. That's the whole argument, and it doesn't depend on the CSA report being right about any particular client.

Local stdio MCP servers are not remote HTTP servers

One distinction worth keeping straight, because it changes the blast radius: a remote MCP server reached over Streamable HTTP does not run on your machine. Your client opens a connection and sends requests. The risk there is credential handling, server-side authorization, and what the remote service does with the data you send.

A local stdio server is the opposite: the code runs on your host, as your user, with your environment. The seed's framing—trojanized servers running before approval—only makes sense in the local case. The remote case has no local launch step to sneak into. When you triage a report like this, the first question is which transport it applies to.

Build a harmless Node.js startup probe

Lab scope and safety constraints

Everything below runs in a temporary directory with a throwaway Node.js LTS install, synthetic environment values, and no outbound connections. In concrete terms:

  • node --version → v22.12.0 (an LTS line; pin your own and record it)
  • working directory: mktemp -d, deleted afterward
  • one synthetic variable, HACKYJS_FAKE_TOKEN, with an obviously fake value
  • one fixture file created on purpose, one scratch directory
  • no real credentials, no registry calls, no network syscalls

startup-probe.mjs

// startup-probe.mjs — harmless; no network, synthetic values only


const log = (event) =>
  process.stderr.write(
    JSON.stringify({ ts: new Date().toISOString(), ...event }) + "\n"
  );

// (1) Top-level startup marker: runs during module evaluation,
//     before a single byte of JSON-RPC is read from stdin.
log({ event: "startup", pid: process.pid, node: process.version });

// (2) Read exactly one named, synthetic environment variable.
const token = process.env.HACKYJS_FAKE_TOKEN;
log({
  event: "env-read",
  variable: "HACKYJS_FAKE_TOKEN",
  present: token !== undefined,
  length: token?.length ?? 0,
});

// (3) Read one fixture file we created on purpose.
try {
  const body = await readFile(new URL("./fixture/secret.txt", import.meta.url), "utf8");
  log({ event: "fixture-read", ok: true, bytes: body.length });
} catch (error) {
  log({ event: "fixture-read", ok: false, code: error.code });
}

// (4) Attempt one write into a scratch directory.
try {
  await writeFile(new URL("./fixture/scratch/probe.txt", import.meta.url), "probe\n");
  log({ event: "fixture-write", ok: true });
} catch (error) {
  log({ event: "fixture-write", ok: false, code: error.code });
}

// (5) Start no network activity and no MCP transport on purpose.
log({ event: "ready-for-protocol", note: "no tools/call received yet" });

Two deliberate choices. First, everything goes to stderr and nothing to stdout. Second, the probe reads exactly one environment variable by name instead of dumping process.env. A dump is a credential exfiltration primitive, and I'd rather the fixture be boring.

Why stderr is for diagnostics and stdout is for protocol

⚠️

On a stdio transport, stdout is the wire. A single stray console.log("started") in an MCP server produces a line that isn't valid JSON-RPC. Clients that parse strictly will fail the server at initialization. Clients that parse leniently may treat noise as data. Log to process.stderr in every MCP server you write.

This is a real source of bugs in hand-written servers, and it explains why a well-behaved trojanizing payload stays quiet on stdout: talking on the wire gives it away. If you're auditing an unfamiliar server, one of the cheapest checks is grep -n "console.log" across its entry points.

A launcher harness that keeps the approval gate closed

// launch-harness.mjs — models the launch step and a closed approval gate



const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const toolCallApproved = false; // the only approval this harness models

const child = spawn(process.execPath, ["startup-probe.mjs"], {
  cwd: import.meta.dirname,
  // Explicit allowlist. Nothing is inherited implicitly.
  env: {
    PATH: process.env.PATH,
    LANG: "C.UTF-8",
    HACKYJS_FAKE_TOKEN: "synthetic-not-a-real-credential",
  },
  stdio: ["pipe", "pipe", "pipe"],
});

const startupEvents = [];
createInterface({ input: child.stderr }).on("line", (line) => {
  console.log(`[probe] ${line}`);
  startupEvents.push(line);
});

// stdout stays reserved for protocol frames.
createInterface({ input: child.stdout }).on("line", (line) => {
  console.log(`[protocol] ${line}`);
});

await sleep(300);

console.log(`[harness] approval gate closed: ${toolCallApproved === false}`);
console.log(`[harness] tools/call sent: ${toolCallApproved}`);
console.log(`[harness] startup events observed: ${startupEvents.length}`);

child.stdin.end();
child.kill();

The harness is not a compliant MCP client. It never sends initialize. That's intentional: the point is to isolate the launch step and show what runs before a protocol conversation could even begin. The compliant variant is in the next section.

Run the probe and read the expected output

mkdir -p "$(mktemp -d)" 2>/dev/null     # keep your shell tidy; real work happens below
cd "$(mktemp -d)"
mkdir -p fixture/scratch
printf 'synthetic fixture\n' > fixture/secret.txt
## copy startup-probe.mjs and launch-harness.mjs into this directory
node --version
node launch-harness.mjs

Expected output (not captured from a run — this is what the code above should print):

$ node --version
v22.12.0
$ node launch-harness.mjs
[probe] {"ts":"2025-...","event":"startup","pid":51412,"node":"v22.12.0"}
[probe] {"ts":"2025-...","event":"env-read","variable":"HACKYJS_FAKE_TOKEN","present":true,"length":32}
[probe] {"ts":"2025-...","event":"fixture-read","ok":true,"bytes":18}
[probe] {"ts":"2025-...","event":"fixture-write","ok":true}
[probe] {"ts":"2025-...","event":"ready-for-protocol","note":"no tools/call received yet"}
[harness] approval gate closed: true
[harness] tools/call sent: false
[harness] startup events observed: 5

Five startup events, zero approved tool calls. Change the harness to run with env: { PATH: process.env.PATH } and the env-read line flips to "present":false. That's a small but useful demonstration that an allowlist reduces what a launched process can reach.

What the startup probe does not prove

It does not prove that any named MCP client executes third-party code before showing its approval UI. It proves that in a process the harness spawned, top-level code ran and touched the filesystem and environment before the harness modeled an approval decision. That's a demonstration of the mechanism, not a bypass.

To claim the client-level behavior, you need the integration test in the next section, on a specific client version, with its approval settings recorded.

Verify the ordering in an authorized MCP client

Adapt the startup probe with the official MCP SDK

The sketch below turns the probe into a protocol-compatible local fixture using the official TypeScript SDK. I didn't run it for this post, and it's version-sensitive, so pin the SDK and record the resolved version.

// ordering-fixture.mjs — sketch, untested in this post




const log = (event) =>
  process.stderr.write(JSON.stringify({ ts: new Date().toISOString(), ...event }) + "\n");

log({ event: "startup", pid: process.pid, node: process.version });

const server = new McpServer({ name: "ordering-fixture", version: "0.0.1" });

server.tool("echo", { text: z.string() }, async ({ text }) => {
  log({ event: "tools-call", name: "echo" });
  return { content: [{ type: "text", text }] };
});

log({ event: "tools-registered" });
await server.connect(new StdioServerTransport());
log({ event: "transport-connected" });

Register it in the client under test with an absolute interpreter path and an absolute script path. That removes npx and PATH resolution from the experiment. Then run it in an authorized environment you control.

Collect timestamped startup and approval events

Record these five things, in order, with timestamps from the same clock where possible:

  1. startup on stderr
  2. initialize request/response on the wire
  3. tools/list request/response
  4. the client's approval UI appearing (and whether you accepted)
  5. tools-call on stderr

Also record what the client calls the decision. Many clients have two distinct consent steps: a trust prompt when a server is added or first launched, and a per-call approval. Conflating them is how people conclude "it asked me first" when only the launch prompt had appeared.

Three client runs to compare

RunLaunch consentTool call decisionWhat to record
Adenied / server disabledn/awhether startup appeared at all
Balloweddeniedstartup timestamp versus approval-UI timestamp
Callowedapprovedtools-call timestamp versus startup timestamp

Run A tells you whether the client defers launch. Some clients do lazy launch on first use, which changes the timing but not the ordering. Run B is the decisive one: if startup appears and no tools/call is ever sent, the process ran without a per-call approval. Run C just confirms the tool actually works, so you know B's null result wasn't a broken configuration.

I've marked this section as not performed. If you run it, publish the client name and version, the SDK version, the runtime version, and the approval settings. Otherwise the result isn't reproducible.

Determine what startup code can actually reach

Startup code exposure table

SurfaceReached by default for a stdio serverNotes
Inherited environmentYes, unless the client filters itAPI keys, cloud credentials, SSH_AUTH_SOCK, proxy vars
Workspace filesYesWhatever your user can read under the configured cwd
Writable directoriesYesIncluding ~/.npm, shell rc files, project source
Mounted socketsYesDocker socket, SSH agent socket are the high-value ones
Network routesYesAny egress your host allows, including cloud metadata endpoints

Synthetic access versus conditional impact

The probe demonstrated synthetic access to one variable and one fixture file. Everything else in that table is conditional:

  • Credential theft requires a credential in the inherited environment or a readable file, plus egress to an endpoint the attacker controls.
  • File modification requires write permission on the target path. A read-only checkout or a container with a read-only root filesystem blocks it.
  • Data transmission requires network reachability. --network none or a default-deny egress policy blocks it.

None of this is exotic. These are the ordinary permissions of a developer process. That's exactly why "the process is not sandboxed" is the correct default assumption.

The real boundary crossing is process authority

MCP tool metadata doesn't grant a server anything. The tool schema is a contract about arguments, not a permission grant. What gives a launched server the ability to read ~/.aws/credentials is spawn() with your uid.

That's why I'd fix this at the launch layer instead of trying to make the approval prompt smarter. No amount of per-tool annotation changes the fact that the process is already running with your authority by the time the annotation is displayed.

Establish package provenance before execution

Inspect the MCP server executable and resolved artifact

Before a server goes into a config you keep, resolve what it actually is:

## What will be executed, and from where?
npm view [email protected] dist.tarball dist.integrity _npmUser maintainers repository

## Which lifecycle scripts does the package declare?
npm view [email protected] scripts

## Which files are actually in the artifact?
npm pack [email protected] --dry-run

## Verify registry signatures and provenance attestations (npm 9+)
npm audit signatures

dist.integrity is the subresource-integrity hash of the tarball. Comparing it against a lockfile entry tells you the artifact is the one you reviewed, not that it's benign. npm audit signatures verifies that the published artifact matches what the registry signed and, where the publisher used provenance, links it to a source repository and build. npm documents both in generating provenance statements.

Install scripts, launch behavior, and runtime imports

These are three different execution windows and people routinely collapse them:

WindowWhen it runsDisabled by
Install lifecycle script (preinstall, install, postinstall)During npm install--ignore-scripts
Package-manager launchWhen npx pkg downloads and runs the binNothing defaults to off
Runtime top-level codeEvery start, including from cacheNothing

--ignore-scripts addresses only the first row. It does nothing about the third, which is where the reported MIOU behavior lives. This is the most common mistake I see in MCP server hardening advice: "we run npm ci --ignore-scripts, so we're covered." You're covered against one class of install-time payload. The server still evaluates its own top-level code every time it launches.

Version pinning, lockfiles, signatures, and provenance

These supply-chain controls each reduce a different risk:

  • Version pinning stops silent upgrades to a malicious latest release. It doesn't stop a compromised pinned version.
  • Lockfile integrity stops artifact substitution between resolution and install. It doesn't tell you the artifact was safe when it was published.
  • Registry signatures prove the artifact came from the registry as published. They don't prove the publisher was trustworthy.
  • Provenance attestations tie the artifact to a build from a specific repo and workflow. They shrink the "did someone's laptop push a payload" gap, but not "did the maintainer merge a bad PR."

What helps most is reading the artifact you're about to launch. An MCP server's entry point is usually a few hundred lines. npm pack it, unpack it, and grep the entry for child_process, net., http, fetch, eval, and process.env. It's cheap and catches the noisy cases.

Enforce isolation, credential scope, and egress before launch

Run the MCP server in a constrained local container

If you must run an unreviewed server, run it where its permissions are small. Pinning by digest is the right move; a readable tag is used below for legibility.

docker run --rm -i \
  --name mcp-probe \
  --user 10001:10001 \
  --read-only \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --network none \
  --tmpfs /tmp:rw,noexec,nosuid,size=8m \
  -e HACKYJS_FAKE_TOKEN=synthetic-not-a-real-credential \
  -v "$PWD/fixture:/work/fixture:ro" \
  -w /work \
  node:22.12.0-bookworm-slim \
  node startup-probe.mjs

--read-only, --cap-drop ALL, --security-opt no-new-privileges, and --network none do most of the work. The single bind mount is read-only and points at a fixture directory, not your home directory. Docker's docs on run configuration and container security cover the flags. The important part is applying all of them: --cap-drop ALL without --read-only still leaves the filesystem writable, and --read-only without --network none still leaves exfiltration open.

Allowlisted environment, scoped credentials, and minimal mounts

For real servers rather than fixtures:

  • Pass variables by name (-e VAR reading from your shell) instead of --env-file, so the container doesn't inherit a wholesale environment.
  • Prefer short-lived, service-scoped tokens over long-lived personal keys. A GitHub token scoped to one repo with a one-hour expiry bounds the damage a compromised server can do.
  • Mount a project subdirectory, never $HOME. -v "$HOME:/home/dev" turns one compromised process into a compromised workstation.

Defensive isolation checks and expected outcomes

Run these against the containerized probe and confirm each outcome:

## 1. Fixture readable, host secrets absent, no container socket
docker run --rm --network none --read-only --user 10001:10001 \
  -v "$PWD/fixture:/work/fixture:ro" -w /work \
  node:22.12.0-bookworm-slim \
  node -e 'const fs=require("node:fs");for (const p of ["/work/fixture/secret.txt","/root/.ssh","/var/run/docker.sock"]) { try { fs.accessSync(p); console.log("present", p) } catch (e) { console.log(e.code, p) } }'

## 2. Write to the root filesystem must fail
docker run --rm --network none --read-only --cap-drop ALL --user 10001:10001 \
  -v "$PWD/fixture:/work/fixture:ro" -w /work \
  node:22.12.0-bookworm-slim \
  node -e 'try { require("node:fs").writeFileSync("/work/fixture/escape.txt","x"); console.log("WROTE") } catch (e) { console.log(e.code) }'

## 3. Outbound connection must fail
docker run --rm --network none --read-only --cap-drop ALL --user 10001:10001 \
  node:22.12.0-bookworm-slim \
  node -e 'fetch("https://example.com").then(()=>console.log("REACHED")).catch(e=>console.log("blocked:", e.cause?.code ?? e.message))'

Expected outcomes:

## 1
present /work/fixture/secret.txt
ENOENT /root/.ssh
ENOENT /var/run/docker.sock

## 2
EROFS

## 3
blocked: ENETUNREACH

Note the first line of check 1: the fixture is readable. That's the point. Isolation doesn't make a process unable to read; it makes the process unable to read anything you did not mount. Check 3 may print ENETUNREACH or, if the resolver is attempted first, an EAI_AGAIN-style failure. Either way, no connection.

Limits of container isolation for MCP servers

Container isolation isn't absolute. Kernel bugs, misconfigured runtimes, and privileged sidecars break it. Read-only mounts still disclose whatever is mounted. If you mount a source tree because the tool needs it, the tool can read your .env in that tree. A networked tool also needs destination-level restrictions. --network none isn't usable for a server that has to reach an API, so you need an egress policy that defaults to deny, plus a block on cloud metadata endpoints (169.254.169.254 and friends), which are the classic SSRF pivot.

Make startup permissions part of the approval decision

Order controls by what stops startup execution

If you take one thing from this, take the ordering of controls:

  1. Reject untrusted execution. If you can't identify and review the artifact, don't put it in a config. This eliminates the entire class.
  2. Minimize the authority of the process. Containers, allowlisted environments, scoped tokens, no host sockets, default-deny egress.
  3. Keep per-call approval. It's a genuinely useful control against a compromised or misbehaving server doing something you didn't intend on a specific call. It just isn't the control that stops the launch.

Doing 3 without 1 and 2 is the failure mode the MIOU seed describes.

Acceptance evidence for each allowed MCP server

For each server you allow, keep a short record:

  • reviewed executable identity: resolved tarball, dist.integrity, publisher, version, digest of the runtime image
  • recorded launch permissions: user, mounts, environment variables by name, network policy
  • negative isolation tests: the ENOENT, EROFS, and ENETUNREACH results above, rerun after any config change
  • an audit trail that distinguishes process startup from tool invocation, so an incident review can answer "was the process running before the user approved anything"

If your audit log only records tool calls, you can't answer that question. Add a launch event.

Further Reading

Share this post

More posts

Loading comments…