10,000+ Stateless MCP Servers: Govern AI Agent Permissions

A hand lifting one printed code listing from a stack of identical listings

11 min read · 2,705 words

This article was written with AI. It was drafted from the sources it cites and checked against the full text of those sources before publishing. How we make articles

According to Forkast, more than 10,000 active public MCP servers now run across the ecosystem using the Model Context Protocol under a specification whose final release moved it to a fully stateless architecture (forkast.news). On this article’s reading, that statelessness is where AI agent permissions break: when session context does not survive between tool calls, nothing ties a bearer token reused across every loop to the task at hand, which is why this article compares it to a skeleton key.

A stateless protocol has no way to tell intended use from reuse when both present the same secret. Static API keys are not controls in a stateless loop.

Building a Python runtime governor for AI agent permissions supplies that session layer: a middleware that sits between the agent and the server: each tool call routed through it is checked against a scoped delegation, and a violation terminates the session. The code uses only the Python standard library, with no managed service behind it. Steps 1 to 5 build the gate inside one process. Step 6 then splits it into three: a tool server, a governor that holds the signing key, and an agent that holds nothing, so going around the gate fails at the server.

What You’ll Build

Seven short files make up the tutorial: the six listed below, and baseline_agent.py, which shows the failure the gate prevents.

  • mcp_server.py: A mock stateless MCP registry with two tools.
  • runtime_governor.py: A middleware that checks every tool call against a scoped token, rebuilding the session layer MCP dropped.
  • agent_loop.py: A simulation that attempts an escape and gets blocked cold.
  • tool_server.py: The tools behind an HTTP server that accepts only calls signed with a key.
  • governor_proxy.py: The governor as its own process, holding the key and signing what it approves.
  • remote_agent.py: An agent with no key, which tries the governed path and then tries to go around it.

Prerequisites

Python 3.12.2 powered this tutorial’s test run. The setup needs no pip installs, cloud accounts, or API keys.

Step 1: Model a Stateless MCP Registry

Step 1 simulates a stateless MCP server, mcp_server.py, in pure Python so the code runs offline. The mock leaves out the real protocol’s transport and keeps the part that matters here: the server holds no session state between calls.

Create mcp_server.py:

import json
from typing import Any, Callable

class MCPServer:
    def __init__(self):
        self.tools: dict[str, Callable] = {}

    def register(self, name: str, func: Callable):
        self.tools[name] = func

    def call(self, name: str, params: dict) -> Any:
        if name not in self.tools:
            raise ValueError(f"Unknown tool: {name}")
        return self.tools[name](**params)

# --- Mock tools ---
def read_file(path: str) -> str:
    return f"[OK] read {path}"

def delete_database(confirm: bool = False) -> str:
    if confirm:
        return "[DANGER] database wiped"
    return "[WARN] confirmation required"

server = MCPServer()
server.register("read_file", read_file)
server.register("delete_database", delete_database)

Notice the absence of auth inside the server; that design choice is intentional. The specification defines stateless transport by design — it carries no session context between tool calls (forkast.news). In this tutorial, closing that gap is the governor’s job.

Step 2: Run the Baseline Static-Token Failure

Before building the fix, run the static-token baseline and watch it fail. Create baseline_agent.py:

from mcp_server import server

STATIC_KEY = "sk-static-demo"

class StaticAgent:
    def act(self, tool_name: str, params: dict):
        # In production, this bearer token is reused across every loop
        print(f"[AUTH] Bearer {STATIC_KEY}")
        return server.call(tool_name, params)

agent = StaticAgent()
print(agent.act("read_file", {"path": "/etc/passwd"}))
print(agent.act("delete_database", {"confirm": True}))

Run the script:

python baseline_agent.py

Both calls succeed: the baseline script never checks the key, which tools it is for, or how long ago it was issued.

As Tim Freestone wrote in TechRepublic, five independent security research teams, publishing in the same week, “arrived at the same conclusion: AI agents are operating in enterprise environments with permissions designed for humans and security architectures built for a pre-agent world” (techrepublic.com).

Step 3: Build the Runtime Governor

As Sahil Mukhija and Vatsal Gupta argue for the Cloud Security Alliance, autonomous agents require governance models that move beyond human-style identity (Beyond Human Identity). On this article’s reading, AI agent permissions require validation at the execution boundary, which is what this governor does.

Create runtime_governor.py:

import hashlib
import time
from dataclasses import dataclass, field
from typing import Any

@dataclass
class DelegatedToken:
    scope: list[str]
    issued_at: float
    call_count: int = 0
    revoked: bool = False

class RuntimeGovernor:
    def __init__(self, server, anomaly_threshold: int = 3, ttl_seconds: float | None = None):
        self.server = server
        self.anomaly_threshold = anomaly_threshold
        self.ttl_seconds = ttl_seconds
        self.sessions: dict[str, DelegatedToken] = {}
        # Parameters that may never be set to a true value, in any form: an agent can send "true" as a string
        self.forbidden_params = {"confirm", "force"}

    def issue_token(self, session_id: str, scope: list[str]) -> DelegatedToken:
        token = DelegatedToken(scope=scope, issued_at=time.time())
        self.sessions[session_id] = token
        return token

    def validate(self, session_id: str, tool_name: str, params: dict) -> None:
        token = self.sessions.get(session_id)
        if not token or token.revoked:
            raise PermissionError("Invalid or revoked session.")

        # 1. Scope check
        if tool_name not in token.scope:
            self._terminate(session_id, f"Tool {tool_name} outside scope {token.scope}")
            raise PermissionError(f"Tool {tool_name} not in scope.")

        # 2. Forbidden parameter lock
        for k, v in params.items():
            if k in self.forbidden_params and v:
                self._terminate(session_id, f"Forbidden parameter value: {k}")
                raise PermissionError(f"Forbidden parameter: {k}")

        # 3. Rate / volume anomaly
        token.call_count += 1
        if token.call_count > self.anomaly_threshold:
            self._terminate(session_id, "Anomaly threshold exceeded.")
            raise PermissionError("Anomaly threshold exceeded.")

        # 4. TTL expiration
        if self.ttl_seconds is not None and time.time() - token.issued_at > self.ttl_seconds:
            self._terminate(session_id, "Token expired.")
            raise PermissionError("Token expired.")

    def execute(self, session_id: str, tool_name: str, params: dict) -> Any:
        self.validate(session_id, tool_name, params)
        return self.server.call(tool_name, params)

    def _terminate(self, session_id: str, reason: str):
        token = self.sessions.get(session_id)
        if token:
            token.revoked = True
        print(f"[TERMINATED] {session_id}: {reason}")

After confirming the session exists and is not revoked, the governor runs four numbered checks in sequence before any tool executes. The governor stores its session state in a process-local dictionary, so in this tutorial’s design the governor’s state lives inside its own process, with no shared state on the wire and no external service to call.

Step 4: Inject Scoped Delegation and Anomaly Checks

How many tool calls are too many? Set the threshold to the number of calls the task is expected to make, then tune it on observed patterns. This demo sets anomaly_threshold=3.

Agent loops no longer touch the server directly; communication flows through the governor instead.

Create agent_loop.py:

from mcp_server import server
from runtime_governor import RuntimeGovernor

governor = RuntimeGovernor(server, anomaly_threshold=3)

# Onboard the agent with a tightly scoped token
session = "agent-001"
governor.issue_token(session, scope=["read_file"])

# Task 1: legitimate read
try:
    out = governor.execute(session, "read_file", {"path": "data.txt"})
    print(out)
except PermissionError as e:
    print(f"[BLOCKED] {e}")

# Task 2: another legitimate read
try:
    out = governor.execute(session, "read_file", {"path": "config.yaml"})
    print(out)
except PermissionError as e:
    print(f"[BLOCKED] {e}")

# Task 3: escape attempt using cached session
# The agent found a cached credential and tries a destructive tool outside scope
try:
    out = governor.execute(session, "delete_database", {"confirm": True})
    print(out)
except PermissionError as e:
    print(f"[BLOCKED] {e}")

# Task 4: even if the agent retries the original tool, the session is dead
try:
    out = governor.execute(session, "read_file", {"path": "backup.sql"})
    print(out)
except PermissionError as e:
    print(f"[BLOCKED] {e}")

Scoped permissions bind the token to read_file only, and the scope check runs before any tool executes. If a destructive tool somehow appeared in the allowed scope, this call’s confirm: True would trip the forbidden-parameter lock next and still terminate the session; a call without a forbidden parameter would pass that check.

Step 5: Simulate the Escape and Confirm the Kill Switch

Run the full loop:

python agent_loop.py
# 2026-10-07 AEST, local machine, Python 3.12.2. The seven files exactly as published (agent_loop.py with the Verify block appended), run in the article's order.
[… 9 lines omitted …]
[TERMINATED] agent-001: Tool delete_database outside scope ['read_file']
[BLOCKED] Tool delete_database not in scope.
[BLOCKED] Invalid or revoked session.
[TERMINATED] selftest: Tool delete_database outside scope ['read_file']
PASS: Escape blocked.
exit=0
=== Step 6: tool_server.py and governor_proxy.py started with GOVERNOR_KEY set; remote_agent.py run with it unset
[OK] read data.txt
[BLOCKED 403] Signature does not match this call.
[BLOCKED 403] Tool delete_database not in scope.
[BLOCKED 403] Invalid or revoked session.
exit=0
Output of our own test run of the code above.

Review the output:

[OK] read data.txt
[OK] read config.yaml
[TERMINATED] agent-001: Tool delete_database outside scope ['read_file']
[BLOCKED] Tool delete_database not in scope.
[BLOCKED] Invalid or revoked session.

Call three never reached the server, and because the governor revoked the session, the fourth call was blocked too, even though read_file is in scope.

Verify Your Gate

Add a self-test block to agent_loop.py so the CI pipeline proves the gate works on every deploy:

if __name__ == "__main__":
    # A fresh session: the loop above revoked agent-001, as it should.
    governor.issue_token("selftest", scope=["read_file"])
    assert "read data.txt" in governor.execute("selftest", "read_file", {"path": "data.txt"})
    try:
        governor.execute("selftest", "delete_database", {"confirm": True})
        raise AssertionError("Governor failed to block escape")
    except PermissionError:
        print("PASS: Escape blocked.")

Execute the verification:

python agent_loop.py

With the self-test block added, the run should end with PASS: Escape blocked.; an AssertionError in its place means the gate is not intercepting calls.

Step 6: Put the Key Where the Agent Cannot Reach It

Everything so far holds only while the agent calls through the governor, and all of it runs in one process. baseline_agent.py showed the other path: it called server.call directly and nothing stopped it. Closing that path takes three processes. The tool server accepts only signed calls, verifying them with the same key the governor signs with. The governor holds the policy. The agent holds no key.

Create tool_server.py:

import hashlib
import hmac
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from mcp_server import server

KEY = os.environ["GOVERNOR_KEY"].encode()      # set for this process and the governor's, never the agent's
SEEN: set[str] = set()


def signature(session_id: str, tool_name: str, params: dict, nonce: str) -> str:
    message = json.dumps([session_id, tool_name, params, nonce], sort_keys=True).encode()
    return hmac.new(KEY, message, hashlib.sha256).hexdigest()


class ToolHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        call = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        expected = signature(call["session"], call["tool"], call["params"], call.get("nonce", ""))
        if not hmac.compare_digest(expected, call.get("signature", "")):
            return self._reply(403, "Signature does not match this call.")
        if call["nonce"] in SEEN:
            return self._reply(403, "This signed call was already used.")
        SEEN.add(call["nonce"])
        self._reply(200, server.call(call["tool"], call["params"]))

    def _reply(self, status: int, body: str):
        self.send_response(status)
        self.end_headers()
        self.wfile.write(body.encode())

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 8701), ToolHandler).serve_forever()

Create governor_proxy.py. It reuses the Step 3 governor unchanged and hands it a forwarder in place of the in-process server:

import json
import secrets
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

from runtime_governor import RuntimeGovernor
from tool_server import signature

TOOL_SERVER = "http://127.0.0.1:8701"


class SignedForwarder:
    """What the governor calls once a tool call has passed its checks."""

    def __init__(self):
        self.session_id = ""

    def call(self, tool_name: str, params: dict) -> str:
        nonce = secrets.token_hex(16)
        body = {"session": self.session_id, "tool": tool_name, "params": params, "nonce": nonce,
                "signature": signature(self.session_id, tool_name, params, nonce)}
        request = urllib.request.Request(TOOL_SERVER, json.dumps(body).encode())
        return urllib.request.urlopen(request).read().decode()


forwarder = SignedForwarder()
governor = RuntimeGovernor(forwarder, anomaly_threshold=3)
governor.issue_token("agent-003", scope=["read_file"])


class GovernorHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        call = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        forwarder.session_id = call["session"]
        try:
            status, body = 200, governor.execute(call["session"], call["tool"], call["params"])
        except PermissionError as e:
            status, body = 403, str(e)
        self.send_response(status)
        self.end_headers()
        self.wfile.write(body.encode())

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 8702), GovernorHandler).serve_forever()

Create remote_agent.py:

import json
import urllib.error
import urllib.request

GOVERNOR = "http://127.0.0.1:8702"
TOOL_SERVER = "http://127.0.0.1:8701"


def post(url: str, body: dict) -> str:
    try:
        return urllib.request.urlopen(urllib.request.Request(url, json.dumps(body).encode())).read().decode()
    except urllib.error.HTTPError as e:
        return f"[BLOCKED {e.code}] {e.read().decode()}"


# 1. The governed path: the agent asks the governor, which signs and forwards.
print(post(GOVERNOR, {"session": "agent-003", "tool": "read_file", "params": {"path": "data.txt"}}))

# 2. Bypass: the agent skips the governor and calls the tool server itself. It has no key.
print(post(TOOL_SERVER, {"session": "agent-003", "tool": "delete_database", "params": {"confirm": True},
                         "nonce": "0" * 32, "signature": "f" * 64}))

# 3. Out of scope through the governor: refused, and the session is revoked.
print(post(GOVERNOR, {"session": "agent-003", "tool": "delete_database", "params": {"confirm": True}}))

# 4. The revoked session cannot read any more either.
print(post(GOVERNOR, {"session": "agent-003", "tool": "read_file", "params": {"path": "config.yaml"}}))

Start the two services with the key in their environment, then run the agent without it:

export GOVERNOR_KEY=$(python -c "import secrets; print(secrets.token_hex(32))")
python tool_server.py &
python governor_proxy.py &
sleep 1
env -u GOVERNOR_KEY python remote_agent.py

Step 6’s run printed:

[OK] read data.txt
[BLOCKED 403] Signature does not match this call.
[BLOCKED 403] Tool delete_database not in scope.
[BLOCKED 403] Invalid or revoked session.

Line one is the governed path: the governor checked the call, signed it with a one-time nonce, and the server ran it. The second is the agent calling the tool server directly; it has no key, so its signature is wrong and the server refuses. The third and fourth are the Step 5 behavior, now across a process boundary: an out-of-scope call revokes the session, and the revoked session is refused even for a tool it was allowed. The agent never sees a signature, so it has nothing to replay.

Step 6 gives up one thing the earlier steps kept: the server now holds a secret and the set of used nonces, which is state. Before production use, put a timestamp in the signed message, accept it only inside a short window so the set stays small, and keep the key in a secrets manager.

Production Hardening

Before deploying it, make these changes.

Keep validation on the call path. If the agent loop is concurrent, await the governor’s check before each tool call rather than running it alongside; a check that finishes after the call has already executed cannot block it.

Give each agent its own session. A session ID and scoped token per running agent keeps one agent’s revocation and call count out of another’s.

Log to structured stdout. The governor prints terminations to stdout. In production, redirect those logs to a SIEM platform. Itamar Apelblat, writing for Forbes Technology Council, argues that AI agents do not hack their way in because they are already inside (Forbes).

The Steelman: Should MCP Stay Stateless?

Forkast reports that the final spec’s removal of protocol-level sessions enables horizontal scaling (forkast.news). That is the strongest objection to a runtime governor: statelessness is a feature, and Step 6 puts state back.

Analysis: the objection is right about the cost and wrong about where it lands. The protocol stays stateless; the state sits in two services an operator runs, the governor’s sessions and the server’s used nonces, and a deployment with several server replicas has to share that nonce set or issue nonces per replica. What the cost buys is the difference Step 2 and Step 6 show side by side. The reused bearer token fails open, because nothing consults it. The governor fails closed, and with the key out of the agent’s process, so does the server. That split is the enterprise gap that five independent security research teams, rounded up by TechRepublic, described, made runnable: permissions designed for humans persist as a bearer token no one consults, while a check at the execution boundary terminates the session on the first violating call. The build is also the Cloud Security Alliance’s runtime governance argument in working code — scope bound to a session, validated on every call instead of issued once and reused. Every authorization layer needs someone to define scope; here it is an operator in configuration, checked on every call.

Verdict: When to Deploy, When to Skip

Recommendations from this article appear in the verdicts below.

Condition Verdict
Agent calls several tools per task or chains LLM outputs into tool inputs Deploy the governor immediately
Single-tool, read-only agent with no credential cache Skip; overkill
Using managed MCP SaaS that blocks middleware hooks Wait; negotiate runtime access or switch vendors
Small team Build this minimal version; it needs only the standard library
Large team Build this first, then budget for dedicated agent IAM

Next Steps

Copy the seven files into your project. Replace the mock MCPServer with the actual MCP client. Map every production tool to a scope list. Run the verification.

Your codebase now has the permission control that the stateless registry lacked. Wire the self-test into CI so every deploy reruns it.

References

Scroll to Top