Concepts · Level 2 · Note 8
How AI agents work: tool calling, MCP and memory, and where each one breaks
Tool calling, structured output, the agent loop, MCP and agent memory in plain words, then how each is attacked in documented research, and what to check.
Short answer
An AI agent is a model in a loop. It writes a structured request, your application runs the tool, and the result goes back in as text. MCP is a standard way to plug tools in, and memory is text saved for later runs. Each part is an attack path. Researchers have shown hidden instructions in MCP tool descriptions, a GitHub issue that made an agent leak private repos, and a planted ChatGPT memory that kept sending chats out until OpenAI patched it. Valid JSON only proves the shape is right. Put the checks in code: least privilege, approval for risky calls, pinned tools, reviewed memory.
A language model on its own can only produce text. An agent is that same model wired to tools, run in a loop, and sometimes given a notebook to keep between sessions. Five ideas explain how that works, and each one comes with its own way to go wrong.
Tool calling, in plain words
Imagine a very well-read consultant locked in a room with no phone and no computer. The only way in or out is a slot under the door. When they need something, they slide out a note: “Look up order 4412.” An assistant outside reads the note, does the lookup and slides the answer back.
The consultant never touches the order system. They only write notes. Whether a note gets carried out is up to the assistant.
In an agent, the model is the consultant and your application is the assistant.
Tool calling, technically
OpenAI’s function calling guide lays out the flow in five steps. Each tool is declared with a name, a description of “when and how to use the function”, and a JSON schema, a formal list of the fields it accepts, for its arguments. The guide is plain about who does the work: “When the model calls a function, you must execute it and return the result.” That is true of the tools you define, which are the subject of this note. The same guide notes that OpenAI also offers built-in tools, such as web search, that run on its platform.
Animated: one tool call, there and back
- Your app sends the user's question to the model, along with a list of tools the model may ask for.
- The model can't run anything. It writes a request: a tool name and the arguments.
- Your app reads the request and runs the tool. That code uses your keys and your network.
- The result goes back to the model as text, in a second request.
- The model reads the result and writes the answer, or asks for another tool.
- The catch is step 3. Your code acts on the say-so of a note. Whether a note gets carried out is up to your app, so that is where the checks belong.
One tool call, five steps
Step 3 is the one that matters for security. The code that runs there uses your keys and your network, on the say-so of a note.
Structured output, in plain words
Ask someone to write you a letter and you get whatever they feel like writing. Hand them a form with boxes and you get a name in the name box and a date in the date box. Software needs the form, because a program can’t act on a rambling letter.
A form only controls where things go. Someone can still write a false name in the name box.
Structured output and constrained decoding, technically
Early “JSON mode” aimed for valid JSON and made no promise about the fields inside it. OpenAI’s announcement of Structured Outputs on 6 August 2024 says JSON mode “improves model reliability for generating valid JSON outputs” but “does not guarantee that the model’s response will conform to a particular schema.”
The stronger method is constrained decoding. A model writes one token (a word or a piece of one) at a time, picking each from its whole vocabulary. With a schema supplied, the system removes every candidate that would break the schema before the pick. In OpenAI’s words: “we constrain our models to only tokens that would be valid according to the supplied schema”. To do that they “convert the supplied JSON Schema into a context-free grammar”. Open-source runtimes do it too. The llama.cpp grammar guide describes its format as a way “to constrain model outputs”, for example “to force the model to generate valid JSON”. You’ll see this called constrained sampling or grammar-constrained decoding.
Animated: how constrained decoding forces the shape
The schema says: the "to" field must be text
Candidates for the next token
- The model is filling in a tool call. The schema says the "to" field must be text.
- A model writes one token at a time. Normally it picks from its whole vocabulary, so any of these could come next.
- With constrained decoding, every candidate that would break the schema is removed before the pick.
- Only valid tokens are left, so the model opens a text value.
- Repeat that for every token and the output always fits the form.
- The catch: the form controls the shape, and an attacker's address is text too. A hijacked model fills the form perfectly. Check the values in code.
Following a complex JSON schema: OpenAI's own test
On OpenAI’s evaluation, the constrained model “scores a perfect 100%” and the older gpt-4-0613 “scores less than 40%”. The two bars are different models, so the gap is not all down to the constraint: OpenAI says training alone took the newer model to 93% on the same benchmark, and constrained decoding closed the rest.
That score is about shape, and it comes with conditions. On OpenAI’s API the guarantee applies when the schema is set with strict: true. The post says the output can still break the schema if generation is cut off, for example at the token limit, and that the model can refuse. It also warns that “the model may still make mistakes within the values of the JSON object”.
The agent loop, in plain words
A plumber doesn’t fix a leak in one move. They look, try something, look again, and repeat until the floor is dry. Nobody hands them the steps in advance.
An agent works the same way: decide the next step, take it, read what came back.
The agent loop, technically
The pattern has a name from a 2022 paper, ReAct, by Shunyu Yao and six co-authors. They had a model “generate both reasoning traces and task-specific actions in an interleaved manner”, where actions “allow it to interface with external sources, such as knowledge bases or environments”.
In practice the loop is steps 2 to 5 in the figure above, repeated for as long as step 5 returns another tool call. Every tool result is appended to the conversation and the model reads the whole thing again to pick the next action.
The loop, and what the model reads on each pass
Notice the third box. A web page, a ticket or an email fetched by a tool lands in the same stream as the user’s request. The API marks it as a tool result, but that mark is one more thing the model reads. Nothing forces the model to treat the text as data and not as instructions. Our note on six real agent hijacks is a catalog of what follows from that.
MCP, in plain words
Before USB, every printer and camera needed its own cable. Model Context Protocol, MCP, is the common plug for AI tools. A company wraps its product in an MCP server once, and any agent that speaks MCP can use it.
Each tool arrives with a label saying what it does, written by whoever made the server, and the model reads the labels to choose.
MCP, technically
The MCP specification (version 2026-07-28) describes a host application that creates clients, “each client having a 1:1 relationship with a particular server”. Servers “expose tools that can be invoked by language models”. A client asks a server for its tools with tools/list and asks the server to run one with tools/call. A tool definition carries a name, a description and an inputSchema.
Two details matter later. Tools are “model-controlled”, meaning the model can “discover and invoke tools automatically”. And the tool list “MAY change over time”, with a notifications/tools/list_changed message that a server can send to clients that subscribed to it. The spec asks for a person in the path: “there SHOULD always be a human in the loop with the ability to deny tool invocations.”
Animated: a hidden instruction in a tool description
- MCP is a common plug for AI tools. Your app, the host, connects to a server that wraps a product.
- The host asks the server for its tools. Each one comes back with a name, a description and a form for its arguments.
- The description is written by whoever made the server. It lands in the model's context as text, and the model reads it to choose a tool.
- In a demonstration by Invariant Labs, a tool that claimed to add two numbers carried extra instructions in its description.
- In their experiment with a coding agent, the agent followed them. It read sensitive local files and passed them along.
- A second trick is the rug pull: a server changes a description after the client approved it. So pin tool descriptions, and block the server when one changes.
Agent memory, in plain words
There are two kinds. One is a whiteboard: everything said in this meeting, wiped when the meeting ends. The other is a notebook the agent keeps and rereads before each new meeting.
The notebook is why an assistant can know your name next week. It’s also somewhere a lie can sit for months.
Agent memory, technically
Short-term memory is the conversation itself, held in the context window. The LangGraph documentation defines it as what “lets your application remember previous interactions within a single thread or conversation”, and notes the limit: “A full history may not fit inside an LLM’s context window”.
Long-term memory is a store outside the model. In the same documentation it “allows systems to retain information across different conversations or sessions.” Something decides what to save, often the model itself through a memory tool, and saved items are loaded into later prompts. To the model, a stored memory is more text in the context, and it arrives looking like something the agent already believes.
Attack 1: lie on the label, or change it later
On 1 April 2025, Luca Beurer-Kellner and Marc Fischer of Invariant Labs described what they named Tool Poisoning Attacks. In such an attack, “malicious instructions are embedded within MCP tool descriptions that are invisible to users but visible to AI models.” Their demo was a tool named add that claimed to add two numbers. Its description also told the model to read local files and pass them along as an extra argument. In their experiment with the Cursor coding agent, the agent read the user’s ~/.cursor/mcp.json “and other sensitive files like SSH keys”.
They described two variations. In a rug pull, “a malicious server can change the tool description after the client has already approved it.” In shadowing, one server’s description changes how the agent uses another server’s tool. Their example was a bogus tool whose description added behavior to a trusted send_email tool, so mail went to the attacker. These were the researchers’ own experiments. For a case OWASP has since cataloged, see Deadbugz in our Agentic Top 10 explainer.
Attack 2: something the agent reads becomes a tool call
The label can be honest and the agent can still be steered, because tool results are text too.
Invariant Labs showed it with the official GitHub MCP server in May 2025. An attacker files an issue on a victim’s public repository. The victim later asks their agent to look at open issues. The agent reads the planted one, pulls data from the victim’s private repositories and leaks it “in an autonomously-created PR in the public repository”. The authors named this a “toxic agent flow” and were clear that “this is not a flaw in the GitHub MCP server code itself”.
The same shape showed up in a July 2025 demonstration by General Analysis against a Supabase setup filled with dummy data. A customer writes a support ticket containing instructions. A developer’s Cursor agent, connected with the service_role key that “bypasses all row-level security (RLS) protections”, reads the ticket, then reads “the full contents of the integration_tokens table” and writes them into the support thread. The authors say they have “not rerun the demonstration against the current server.”
Two demonstrations with the same recipe
Simon Willison called the Supabase case “yet another example of a lethal trifecta attack”. His three ingredients are private data, untrusted content and a way to send data out, and our LLM security guide covers them.
Security people will recognize an older name: the confused deputy. The agent holds real authority and gets talked into using it for someone else. OWASP files the cause under Excessive Agency and lists three roots: “excessive functionality”, “excessive permissions” and “excessive autonomy”. MCP’s Security Best Practices page has its own “Confused Deputy Problem” section, which covers a narrower case of proxy servers and OAuth consent.
Attack 3: write in the notebook
If an injection can reach the memory tool, it stops being a one-time event.
Johann Rehberger showed this against the ChatGPT macOS app in a post he titled SpAIware, published on 20 September 2024. A prompt injection on a web page stored instructions in ChatGPT’s long-term memory. From then on, he wrote, “all new conversation going forward will contain the attackers instructions”, and his proof of concept sent the conversations out to the attacker. OpenAI closed the exfiltration path in version 1.2024.247. His post adds that at the time of writing “A website or untrusted document can still invoke the memory tool to store arbitrary memories.”
A research team from Michigan State University, the University of Georgia and Singapore Management University went after agents that share one memory across users. Their attack, MINJA, needs no access beyond normal use: the attacker “behaves like a regular user and cannot directly manipulate any part of the agent” beyond what any user can reach. By sending crafted queries, they got the agent to save bad records itself. Those records later misled other users’ requests.
Animated: how a planted memory keeps coming back
- An agent has two kinds of memory. The conversation is a whiteboard, wiped when the session ends. Long-term memory is a notebook kept outside the model.
- In this session the agent reads a web page. The page carries a hidden instruction.
- The instruction gets the agent to save a note with its memory tool. The planted note now sits beside the real ones.
- The session ends and the whiteboard is wiped. In a new session, saved memories are loaded into the prompt.
- The planted note comes back with them. To the model it looks like something it already believes.
- The catch: one injection now acts in every later session. A researcher showed this against a ChatGPT app, and the vendor closed the path that sent data out. Control what can write to memory, and review what is stored.
MINJA: poisoning an agent's memory with ordinary queries (lab result)
The averages were 98.2% for getting records in and 76.8% for the attack working. The second number counts how often a victim’s query drew out the planted reasoning steps. It’s a lab result on three test agents, including a medical-records one, and it assumes “a shared memory bank is adopted”. OWASP’s agentic list has an entry for this class, ASI06, Memory & Context Poisoning.
Valid JSON is not safe JSON
With strict mode on, constrained decoding makes a finished tool call match its schema. It’s tempting to read that as validation. By our own reasoning it isn’t. The schema says to must be a string, and an attacker’s address is a string, so a hijacked model fills the form perfectly.
OpenAI says as much: “Structured Outputs doesn’t prevent all kinds of model mistakes.” OWASP’s guidance on Improper Output Handling gives the stance to take: “Treat the model as any other user, adopting a zero-trust approach”.
What to check, with an example
Take a made-up shop, used here only as an illustration. Its support agent has a ticket-reading tool, an order database reached through an MCP server, an email-sending tool, and long-term memory for customer preferences.
- List every tool and whose credentials it runs with. OWASP’s advice: “Limit the extensions that LLM agents are allowed to call to only the minimum necessary.” In the shop, the database server came with a delete tool nobody uses. Remove it, and connect with a read-only role scoped to the orders table.
- Find the runs where a stranger’s text, private data and a way out meet. Anyone can write ticket text, the order table is private, and email goes anywhere. That is the full recipe from the GitHub and Supabase demos, so the shop restricts the email tool to the address already on the ticket.
- Put approval in front of side effects, and show the arguments. The MCP spec asks clients to “Show tool inputs to the user before calling the server, to avoid malicious or accidental data exfiltration”. A refund or an outbound email waits for a click, and the person clicking sees the recipient and the body.
- Pin tool descriptions and diff them. Invariant’s recommendation: “Clients should pin the version of the MCP server and its tools to prevent unauthorized changes.” The shop stores a hash (a short fingerprint) of each description at review time. A changed hash blocks the server until someone reads the new text.
- Validate arguments in code, as if a stranger typed them. A valid
order_idstill has to belong to the customer on the ticket. OWASP: “Implement authorization in downstream systems rather than relying on an LLM to decide if an action is allowed or not.” - Control who can write to memory. Scope memories per customer, log where each one came from, and never let text from a ticket or web page save one without review. Rehberger’s advice to users applies to operators too: “regularly review the memories the system stores”.
Sources (all checked 23 November 2026)
- OpenAI, “Function calling” guide: developers.openai.com
- OpenAI, “Introducing Structured Outputs in the API”, 6 August 2024: openai.com
- Yao et al., “ReAct: Synergizing Reasoning and Acting in Language Models”, 2022 (ICLR camera-ready version): arxiv.org/abs/2210.03629
- Model Context Protocol specification, version 2026-07-28, “Architecture”: modelcontextprotocol.io, “Tools”: modelcontextprotocol.io. MCP “Security Best Practices” (the page at the 2025-06-18 path): modelcontextprotocol.io
- llama.cpp, “GBNF Guide” (grammars README): raw.githubusercontent.com
- LangGraph documentation, “Memory overview”: docs.langchain.com
- Beurer-Kellner, Fischer (Invariant Labs), “MCP Security Notification: Tool Poisoning Attacks”, 1 April 2025: invariantlabs.ai
- Milanta, Beurer-Kellner (Invariant Labs), “GitHub MCP Exploited: Accessing private repositories via MCP”, 26 May 2025: invariantlabs.ai
- General Analysis, “Supabase MCP can leak your entire SQL database”, July 2025: generalanalysis.com
- Simon Willison, “Supabase MCP can leak your entire SQL database”, 6 July 2025: simonwillison.net, and “The lethal trifecta for AI agents”, 16 June 2025: simonwillison.net
- Johann Rehberger, “Spyware Injection Into Your ChatGPT’s Long-Term Memory (SpAIware)”, 20 September 2024: embracethered.com. His full name is from The Hacker News, 25 September 2024: thehackernews.com
- Dong et al., “Memory Injection Attacks on LLM Agents via Query-Only Interaction” (MINJA), NeurIPS 2025: arxiv.org/abs/2503.03704 and neurips.cc
- OWASP GenAI Security Project, “LLM06:2025 Excessive Agency”: genai.owasp.org, “LLM05:2025 Improper Output Handling”: genai.owasp.org, and the Top 10 for Agentic Applications launch post, 9 December 2025: genai.owasp.org