Dev.to Security 🔐 Cybersecurity 👁 0 📖 7 min read

Auditing MCP server tool calls with a deny-by-default stdio proxy

An MCP server is a small config entry that hands your agent real capabilities: read a file, list a directory, delete something. The protocol is simple enough that people wire it up in five minutes and never look at it ag

An MCP server is a small config entry that hands your agent real capabilities: read a file, list a directory, delete something. The protocol is simple enough that people wire it up in five minutes and never look at it again. The problem is that one unreviewed tool, one prompt-injected argument, or a server running as your own user is enough to turn that convenience into an incident.

What follows is the setup I use for stdio-based MCP servers. Budget 45–60 minutes for the first server and around 15 minutes for each one after that. When you are done, every JSON-RPC message lands in an append-only JSONL file, and any tool you did not explicitly allow is rejected before the real server ever sees it.

Four places where an MCP server can bite you

MCP has two transports. With stdio, the client spawns the server process and talks JSON-RPC over stdin/stdout. With HTTP, the server lives elsewhere. stdio is the interesting case here, because you can insert code you fully control between the two sides. For HTTP servers the same policy work belongs in a gateway or reverse proxy sitting in front of the server.

There are four things worth protecting, and each one gets a matching control:

  • Tool definitions — the server ships a delete_file or a run_shell that nobody reviewed. Control: an inventory plus a deny-by-default allow-list.
  • Tool arguments — model output shaped by a prompt injection turns into a real command. Control: the allow-list, plus logging of argument keys.
  • Process permissions — the server runs as you and can reach ~/.ssh. Control: a separate OS user or a container.
  • Blast radius — nothing is recorded, so you can never reconstruct what was called. Control: an append-only log of every message.

Before you start, confirm three things: you know the exact command that launches the server (e.g. python3 -m my_mcp_server), you can edit the client config that lists mcpServers (for Claude Desktop that file is claude_desktop_config.json — check the docs for the path on your OS), and you have a file the agent is allowed to read, such as ~/mcp-audit/sandbox/notes.txt. Decide who owns the log now rather than later: the agent's process must not be able to rewrite or delete it.

One easy-to-miss detail: GUI-launched clients usually have a shorter PATH than your shell. Run which python3 and paste the absolute path into the config.

Step 1: List every tool the server exposes

You cannot allow-list what you have never seen, and the tool nobody read is exactly the one that gets abused. Save the script below as ~/mcp/list_tools.py. It spawns the server, initializes a session, calls tools/list, and prints one line per tool.

import json, subprocess, sys

SERVER = sys.argv[1:]                    # e.g. python3 -m my_mcp_server
proc = subprocess.Popen(SERVER, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                        text=True, bufsize=1)

def send(msg):
    proc.stdin.write(json.dumps(msg) + "\n")
    proc.stdin.flush()

send({"jsonrpc": "2.0", "id": 1, "method": "initialize",
      "params": {"protocolVersion": "<the version your client sends>",
                 "capabilities": {},
                 "clientInfo": {"name": "inventory", "version": "0.0.0"}}})
print("serverInfo:", json.loads(proc.stdout.readline()).get("result", {}).get("serverInfo"))
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
for tool in json.loads(proc.stdout.readline())["result"]["tools"]:
    print(f'{tool["name"]:<20} | {(tool.get("description") or "")[:60]}')
proc.terminate()

Run it with the server command as the arguments:

python3 ~/mcp/list_tools.py python3 -m my_mcp_server

The protocolVersion value has to match what your client actually sends — take it from the client's documentation, not from an article. Expected output looks roughly like this:

serverInfo: {'name': 'my_mcp_server', 'version': '...'}
read_file            | Read a UTF-8 text file from the sandbox
list_dir             | List files in the sandbox directory
delete_file          | Delete a file by absolute path

Step 2: Classify each tool and write the policy down

Go through the list and fill in a table like this one for your own server:

Tool Touches Risk Decision
read_file sandbox files medium allow, log argument keys
list_dir sandbox files low allow
delete_file any path on disk high deny

Deny is the default. A tool earns an allow only when you can explain why it needs to exist and what it can reach. delete_file stays denied until you have a concrete reason to change that.

Step 3: Put a logging, denying proxy in the middle

Over stdio, stdout carries JSON-RPC and nothing else, so a proxy is a transparent interception point — there is no network config to touch. Save this as ~/mcp/mcp_audit_proxy.py. It writes one JSONL record per message and answers tools/call itself whenever the tool is not on the allow-list.

#!/usr/bin/env python3
"""stdio MCP proxy: log every JSON-RPC message, deny tools outside the allow-list."""
import datetime, json, os, pathlib, subprocess, sys, threading

AUDIT_DIR = pathlib.Path(os.environ.get("MCP_AUDIT_DIR", pathlib.Path.home() / "mcp-audit"))
AUDIT_LOG = AUDIT_DIR / "tool-calls.jsonl"
ALLOW = {"read_file", "list_dir"}               # names copied from tools/list
SERVER = ["python3", "-m", "my_mcp_server"]     # absolute paths are safer
LOCK = threading.Lock()
AUDIT_DIR.mkdir(parents=True, exist_ok=True)

def log(**rec):
    rec["ts"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
    with LOCK, AUDIT_LOG.open("a", encoding="utf-8") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")

def send(msg):
    sys.stdout.write(json.dumps(msg) + "\n")
    sys.stdout.flush()

proc = subprocess.Popen(SERVER, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                        text=True, bufsize=1)

def client_to_server():
    for line in sys.stdin:
        try:
            msg = json.loads(line)
        except json.JSONDecodeError:
            log(direction="client->server", parse_error=True, raw=line[:200])
            proc.stdin.write(line); proc.stdin.flush(); continue
        params = msg.get("params") or {}
        name = params.get("name")
        if msg.get("method") == "tools/call" and name not in ALLOW:
            log(direction="client->server", decision="deny", tool=name,
                arg_keys=sorted((params.get("arguments") or {}).keys()))
            send({"jsonrpc": "2.0", "id": msg.get("id"),
                  "error": {"code": -32001,
                            "message": f"policy_denied: tool '{name}' is not allow-listed"}})
            continue
        log(direction="client->server", decision="allow",
            method=msg.get("method"), tool=name)
        proc.stdin.write(line); proc.stdin.flush()

def server_to_client():
    for line in proc.stdout:
        log(direction="server->client", raw=line[:400].rstrip())
        sys.stdout.write(line); sys.stdout.flush()

threading.Thread(target=server_to_client, daemon=True).start()
client_to_server()
proc.wait()

A few decisions in there are deliberate:

  • The deny branch returns an error object with the same id, so the client renders a normal failed tool call instead of hanging while it waits for a response.
  • Server responses are truncated at 400 characters and unparseable client lines at 200. Logs get shared; they should stay readable.
  • Arguments are recorded as key names, not values. File contents and tokens do not belong in a file you will hand to someone else.

Step 4: Point the client at the proxy

Swap the server entry in your client config for the proxy:

{
  "mcpServers": {
    "files": {
      "command": "/usr/local/bin/python3",
      "args": ["/Users/<you>/mcp/mcp_audit_proxy.py"],
      "env": { "MCP_AUDIT_DIR": "/Users/<you>/mcp-audit" }
    }
  }
}

Rename files to whatever you call that server. The proxy picks up its log directory from MCP_AUDIT_DIR, and the client's env block is the simplest place to set it.

Step 5: Attack your own setup

Restart the client, trigger one allowed call, then run tail -n 5 ~/mcp-audit/tool-calls.jsonl. You want to see a record with "decision": "allow" and "method": "tools/call" — that record is the proof the proxy is in the path rather than parked next to it.

Then ask the agent for something on the deny list, delete_file in my example. The client should come back with a plain policy_denied error, and the log should gain a deny entry naming the tool and the argument keys that were attempted. If the call goes through, the client is still talking to the server directly and the config edit did not take.

Keep the audit trail out of the agent's reach

An audit log that the audited process can edit is decoration. Run the proxy under a different user from the server, or ship the JSONL to a log collector you control. That is also the right moment to deal with the process-level problem: give the MCP server its own OS user or run it in a container, so a read_file tool cannot wander into ~/.ssh.

Takeaway

Securing a stdio MCP server is not one big change, it is three small ones: enumerate the tools, allow-list them by name with deny as the default, and put a proxy in the middle that writes a JSONL record for every message. Budget 45–60 minutes for the first server and about 15 per additional one. The log is what turns "I think the agent only read the sandbox" into something you can actually verify.

This article was originally published on AI Release — https://ai-release.org . More notes like this land in the channel: https://t.me/ai_release1.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.