If You’re Not Using These Three Guards in Your AI Agent, It Has Already Sent Your Secrets to the…
From the publisher’s feed, collected in the ZeroLabs newsroom.
If You’re Not Using These Three Guards in Your AI Agent, It Has Already Sent Your Secrets to the ProviderYou paste sensitive things into AI chats more than you think. Your agent does it automatically, dozens of times a session, silently, without a notification. Here’s the same protection Cursor and many other AI use, explained from the ground up.You’ve done it. Maybe last week. Maybe this morning.You opened ChatGPT to debug something, pasted a file you were working on, hit send and then froze. Was there an API key in that file? A database password buried in a config string? A token you use for a client’s system? You re-read the message. You close the tab. You tell yourself it’s probably fine.And maybe it is. But probably isn’t a policy.Now imagine you’re not pasting manually. You’re building an AI agent something that can autonomously read your files, browse your directories, make changes and you’ve given it access to your codebase to help review it. The agent starts reading. It finds a .env file. Inside: OPENAI_API_KEY=sk-proj-....Here is what happens next, if you have set up no guards:That key gets passed, verbatim, to the language model. It lands in the trace logs. It is in your provider’s records. Whether it travels further into a fine-tuning dataset, into a logging service, into somewhere you have no visibility you will not know.Three turns later, the same agent calls a cleanup tool and deletes a directory you never asked it to touch. It logs the action quietly delete_directory(path="./tmp_backups") and moves on. You find out when you go looking for a file that no longer exists.Two separate failures. No bugs. No hallucinations in the dramatic sense. Just an agent that had no boundary between what it could do and what it should do.This is the problem middleware solves. By the end of this post, you will understand the exact protection Cursor and GitHub Copilot use and how to build both of those same mechanisms into your own agent.First: What is middleware, and why does it exist?If you have never used the word “middleware” before, here is the mental model that makes everything else click.Think of your AI agent as a production line. Data flows in — from you, from files it reads, from search results gets handed to the model, which produces decisions, which become actions. A middleware is a checkpoint at a specific point on that line. It intercepts the data, runs some check or transformation, and either lets the data through unchanged, modifies it, or stops it entirely.The critical detail is where the checkpoint sits. Too late, and sensitive data has already crossed a boundary it shouldn’t. Too early, and you’re checking the wrong thing.GitHub Copilot’s secret scanning is a checkpoint on the output side: before a code suggestion surfaces in your editor, a pattern-matcher runs against it. If the suggestion contains something shaped like an API key starting with sk-, ghp_, AKIA it is suppressed. You never see it. The check fires before the data crosses the boundary into your editor.Cursor’s “Review Changes” is a checkpoint before any file is written: the agent’s execution pauses completely, a diff is shown to you, and the agent cannot proceed until you explicitly approve it. If you reject, the write never happens. The agent figures out an alternative approach.Both are middleware. One guards what comes out of the model. One guards what actions the model can take. LangChain lets you implement both and add resource limits on top.The guard that catches secrets before they reach the model:PIIMiddlewareHere is something that surprises most people the first time they think about it carefully.Your AI agent does not directly access your filesystem. It only sees what gets placed in its context window, what you type to it, and what your tools return. That sounds like a narrow surface. But it means the actual places sensitive data can enter are very specific, and also very different from where most people look.Sensitive data enters the agent’s context in exactly two ways:You type or paste it directly (you copy a config snippet into the chat to ask a question)A tool reads it from disk and returns it (the agent scans a directory and reads a .env file as part of the scan)Both paths go through the middleware layer before the model ever sees them. That is where PIIMiddleware fires at that exact chokepoint.PIIMiddleware intercepts both what you type and what tools return before either reaches the model.There is a flag called apply_to_tool_results that almost every tutorial demonstrates without explaining. It defaults to False. If you add PIIMiddleware with only apply_to_input=True, you have covered the "you paste something sensitive" case but left the "your agent reads a file and returns it" case completely open. An agent with file-reading access will happily retrieve a full .env file as a tool result, and that result goes straight to the model.The minimal, correct setup:from langchain.agents.middleware import PIIMiddlewarePIIMiddleware( "email", strategy="redact", # replaces match with [REDACTED_EMAIL] apply_to_input=True, # scans what you type apply_to_tool_results=True, # scans what tools return - never skip this)For API keys, the ones that actually cause incidents no off-the-shelf detector knows your specific key format. You define it with a regex pattern. Here is one that covers the most common formats:import reAPI_KEY_PATTERN = r"(?:sk-|ghp_|AKIA)[a-zA-Z0-9]{20,48}"# sk- → OpenAI and Anthropic keys# ghp_ → GitHub personal access tokens# AKIA → AWS access key IDsPIIMiddleware( "api_key", detector=API_KEY_PATTERN, strategy="redact", apply_to_input=True, apply_to_tool_results=True,)Four strategies, four different use cases:Strategy What happens When to use it redact Replaces the match with [REDACTED_FIELDNAME] Logs, traces, non-reversible pipelines mask Replaces characters with *, keeping length When you need to show something exists without revealing it. block Raises an exception and stops the entire run Zero-tolerance. high-security contexts hash Replaces with a deterministic hash When you need to track the entity without storing the valueThe instinct most people have here is wrongblock sounds like the safest option. In practice, it is usually the wrong one for tool results. If your agent reads 30 files during a codebase scan and one happens to contain an email address in a comment, block kills your entire session. redact removes the sensitive value and lets the agent continue which is almost always what you actually want. Reserve block for cases where the presence of sensitive data means the agent has accessed something it absolutely should not have reached at all.Quick gut-check If someone asked you right now: “If PIIMiddleware has apply_to_input=True but apply_to_tool_results is left at its default, what specific situation does that leave unprotected?" could you answer it in one sentence?The approval gate that stops silent deletions:HumanInTheLoopMiddlewareBack to the second failure from the opening: the agent that deleted a directory nobody asked it to touch.HumanInTheLoopMiddleware is the Cursor "Review Changes" pattern built as a code primitive. Before any destructive or modifying tool executes, the agent pauses. State is saved. You see exactly what the agent is about to do, with all the details, and you have to explicitly approve it before anything actually happens.The part almost every tutorial skips is this: the pause is easy. The resume is the hard part.Pausing execution straightforward. But returning to the exact state the agent was in when it paused, hours or days later, potentially after the process has been restarted, that requires the full conversation state, the pending action, and the agent’s position in its reasoning to be saved somewhere persistent. Without that persistence layer (called a checkpointer), the interrupt fires, state disappears, and the next call starts from scratch. The agent has no memory of what it was about to do. Your approval gate becomes a session-ender.The agent cannot execute a destructive action until you explicitly approve it. State is saved when the pause fires you can leave it for hours and come back.The pause fires after the model has decided what it wants to do, but before any tool actually executes. This is the only window that works: the decision is visible, and nothing irreversible has happened yet.from langchain.agents.middleware import HumanInTheLoopMiddlewarefrom langgraph.checkpoint.sqlite import SqliteSaver# The checkpointer is not optional. Without it, resume is impossible.with SqliteSaver.from_conn_string("./review_agent.db") as checkpointer: agent = create_agent( model="anthropic:claude-sonnet-4-20250514", tools=[read_file, list_directory, write_file, search_codebase], middleware=[ HumanInTheLoopMiddleware( interrupt_on={ "write_file": True, # always pause before writing "read_file": False, # reading is safe - no pause needed "list_directory": False, "search_codebase": False, } ), ], checkpointer=checkpointer, # saved to SQLite, persists across restarts )The resume flow in code:# First call — agent hits the interrupt at write_file and pausesresult = agent.invoke( {"messages": [{"role": "user", "content": "Review and fix the config files"}]}, config={"configurable": {"thread_id": "session-001"}} # thread_id ties the saved state to this specific session)# result.interrupted == True# result.pending_tool_call == {"name": "write_file", "args": {"path": "src/config.py", ...}}# You show this to the user and wait for approval# User approves - resume the same threadfinal_result = agent.invoke( Command(resume=True), config={"configurable": {"thread_id": "session-001"}} # same thread_id - loads state from the checkpointer and picks up where it stopped)The one gotcha that will cost you an afternoon interrupt_on={"write_file": True} matches the exact string of the tool name. If your tool is actually defined as file_write or update_file, the interrupt never fires it silently passes through. To find the correct name, check what appears in the trace logs when the tool is called. That string is the one you need to match.Two rate limits, two different failure modes you need bothThis concept is simpler to explain, and easier to misconfigure.Your agent calls the model. The model decides what to do and sometimes calls tools. One model call can trigger multiple tool calls running in parallel. These are not the same resource, and they do not count each other.ModelCallLimitMiddleware counts model calls. ToolCallLimitMiddleware counts tool executions.An agent making 10 model calls with 3 parallel tool calls per step has made 30 tool executions. A cap on model calls alone would not catch that. The reverse is also real: an agent stuck re-reasoning in a loop keeps calling the model with no new tool calls. A tool call counter sees zero and never fires.from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddlewareModelCallLimitMiddleware( max_calls=30, on_limit="raise", # raises MaxCallsExceeded - catch this in your application)ToolCallLimitMiddleware( max_calls=60, on_limit="raise",)Use both. They guard different failure modes and neither is a substitute for the other.On on_limit="raise" vs on_limit="return": if you are building an interactive session where a partial result is useful ("here's what I reviewed so far"), use "return". If partial output causes downstream failures in your pipeline, use "raise".I set ModelCallLimitMiddleware(max_calls=10) thinking it was a safe ceiling for a quick test. The agent was calling the model 8 times in the first turn alone — multi-step plan. The limit cut it off mid-task, returned a half-finished result, and I spent 20 minutes wondering why the output was truncated before I checked the logs. The fix was not removing the limit. It was setting it to a number that matched what the task actually needed.The ordering rule that almost no tutorial mentions and that silently breaks your safety layerMiddleware runs in the order you list it. This is not a small implementation detail. The order is the safety guarantee.Here is the specific failure: if any middleware that transforms or summarises message content runs before PIIMiddleware, then PIIMiddleware is scanning already-transformed content, not the raw original. If the transformation happened to compress, paraphrase, or restructure the text in a way that your pattern no longer matches, the redaction misses it. The sensitive data already crossed the boundary. It is in the model's context. The redaction ran after the damage was done.For the safety stack in this post:middleware=[ # PIIMiddleware always first — it must see raw, untransformed data PIIMiddleware("api_key", detector=API_KEY_PATTERN, strategy="redact", apply_to_input=True, apply_to_tool_results=True), PIIMiddleware("email", strategy="redact", apply_to_input=True, apply_to_tool_results=True),# Limits next - exact position within the group is flexible ModelCallLimitMiddleware(max_calls=30, on_limit="raise"), ToolCallLimitMiddleware(max_calls=60, on_limit="raise"), # Human-in-the-loop last in the safety group # (it fires in the after_model hook regardless of list position, # but last is a readable convention) HumanInTheLoopMiddleware(interrupt_on={"write_file": True}),]Think of the middleware list less like a plugin registry and more like a pipeline. What the fourth item receives as input is not the original message — it is the original message after items 1, 2, and 3 have already processed it. Move PIIMiddleware below anything that touches message content, and the safety guarantee quietly disappears.If someone asked you: “What fails if PIIMiddleware is placed after a middleware that summarises conversation history?" could you answer without re-reading?Putting it together: A code review agent with the same safety properties as CursorHere is the full configuration — the same middleware you have seen explained in pieces, assembled into an agent that mirrors the safety behaviour of the commercial tools most people already use.Four tools: read_file, list_directory, write_file, search_codebase. Three safety layers: secrets never reach the model, file writes require your approval, resource usage has a hard ceiling.from langchain.agents import create_agentfrom langchain.agents.middleware import ( PIIMiddleware, HumanInTheLoopMiddleware, ModelCallLimitMiddleware, ToolCallLimitMiddleware,)from langgraph.checkpoint.sqlite import SqliteSaver# Custom pattern for secrets common in codebasesAPI_KEY_PATTERN = r"(?:sk-|ghp_|AKIA)[a-zA-Z0-9]{20,48}"# sk- → OpenAI / Anthropic keys# ghp_ → GitHub personal access tokens# AKIA → AWS access key IDswith SqliteSaver.from_conn_string("./review_agent.db") as checkpointer: agent = create_agent( model="anthropic:claude-sonnet-4-20250514", tools=[read_file, list_directory, write_file, search_codebase], middleware=[ # 1. Catch secrets before they reach the model - on both surfaces PIIMiddleware( "api_key", detector=API_KEY_PATTERN, strategy="redact", apply_to_input=True, apply_to_tool_results=True, # this is the one that catches .env reads ), PIIMiddleware( "email", strategy="redact", apply_to_input=True, apply_to_tool_results=True, ), # 2. Hard resource limits - stops infinite loops and runaway sessions ModelCallLimitMiddleware(max_calls=30, on_limit="raise"), ToolCallLimitMiddleware(max_calls=60, on_limit="raise"), # 3. Approval gate - nothing gets written without your explicit sign-off HumanInTheLoopMiddleware( interrupt_on={ "write_file": True, "read_file": False, "list_directory": False, "search_codebase": False, } ), ], checkpointer=checkpointer, # required for interrupt/resume to work )What the experience looks like when the agent wants to write a file:Agent: I'd like to update src/config.py to fix the circular import. Here is what I plan to write:--- src/config.py --- from typing import Optional from pydantic import BaseModel class Settings(BaseModel): debug: bool = False database_url: str = "sqlite:///app.db" ... Approve this change? (yes/no)User: yesAgent: Written. Moving to tests/test_config.py next.The agent cannot touch anything silently. Every write surfaces for review before it happens. Secrets in any file the agent reads are replaced with [REDACTED_API_KEY] before reaching the model — which also means they never appear in the approval prompt you read. What you are reviewing is already clean.Two easy extensions:If your codebase contains user data phone numbers in test fixtures, for example add a PIIMiddleware("phone", strategy="redact") entry before the email entry. Each PII detector runs independently against the same input, so order within the PII group does not matter.If you want graceful degradation instead of a hard stop at the limits, change on_limit="raise" to on_limit="return" on both limit middlewares. The agent stops at the limit and returns whatever partial result it has assembled, rather than throwing an error.The safety layer is now in place. Your agent cannot leak secrets to the model. It cannot modify files without your approval. It cannot spiral past a resource ceiling you control.What it still cannot do is sustain long sessions. A full codebase review hundreds of files, dozens of tool calls will hit the context window limit before it finishes. The agent will start losing track of what it already reviewed. Its suggestions will drift because the earlier context has been forgotten.That is the problem Blog 2 addresses: not what the agent touches, but how long it can coherently reason across a session before it starts to lose the plot.If You’re Not Using These Three Guards in Your AI Agent, It Has Already Sent Your Secrets to the… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.