# 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.

- Published: 2026-11-23
- Topics: AI security, AI agents, MCP
- Canonical page: https://thesecguy.com/notes/ai-agents-tool-calling-mcp-memory-security/
- Publisher: The Sec Guy (https://thesecguy.com)

**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](https://developers.openai.com/api/docs/guides/function-calling) 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.

<figure class="fig">
<p class="fig-k">One tool call, five steps</p>
<div class="flow">
<div class="node"><b>1. Offer tools</b><span>"Make a request to the model with tools it could call"</span><div class="chips"><i class="chip">your app</i></div></div>
<div class="node"><b>2. Model asks</b><span>"Receive a tool call from the model": a tool name and arguments</span><div class="chips"><i class="chip">model</i></div></div>
<div class="node"><b>3. App runs it</b><span>"Execute code on the application side with input from the tool call"</span><div class="chips"><i class="chip">your app</i><i class="chip">your credentials</i></div></div>
<div class="node"><b>4. Result goes back</b><span>"Make a second request to the model with the tool output"</span><div class="chips"><i class="chip">your app</i></div></div>
<div class="node"><b>5. Answer, or again</b><span>"Receive a final response from the model (or more tool calls)"</span><div class="chips"><i class="chip">model</i></div></div>
</div>
<figcaption>Step text quoted from OpenAI's function calling guide. The chips are our labels.</figcaption>
</figure>

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](https://openai.com/index/introducing-structured-outputs-in-the-api/) 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](https://raw.githubusercontent.com/ggml-org/llama.cpp/HEAD/grammars/README.md) 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.

<figure class="fig">
<p class="fig-k">Following a complex JSON schema: OpenAI's own test</p>
<div class="hbars">
<div class="hbar hot"><em>gpt-4o-2024-08-06 with Structured Outputs</em><div class="track"><i style="width:100%"></i></div><b>100%</b></div>
<div class="hbar"><em>gpt-4-0613, an older model</em><div class="track"><i style="width:39%"></i></div><b>under 40%</b></div>
</div>
<figcaption>Source: OpenAI, "Introducing Structured Outputs in the API", 6 August 2024. The second bar is drawn just under 40%; OpenAI gives no exact figure.</figcaption>
</figure>

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](https://arxiv.org/abs/2210.03629), 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.

<figure class="fig">
<p class="fig-k">The loop, and what the model reads on each pass</p>
<div class="flow">
<div class="node"><b>Plan</b><span>The model reads everything so far and writes its next thought</span><div class="chips"><i class="chip">reasoning</i></div></div>
<div class="node"><b>Act</b><span>It emits a tool call. The application runs it</span><div class="chips"><i class="chip">tool call</i></div></div>
<div class="node"><b>Observe</b><span>The result comes back as text and joins the conversation</span><div class="chips"><i class="chip">untrusted text</i></div></div>
<div class="node"><b>Repeat</b><span>Until the model answers instead of calling a tool</span><div class="chips"><i class="chip">no fixed number of steps</i></div></div>
</div>
<figcaption>Our illustration of the reason-and-act loop described in the ReAct paper (Yao et al., 2022).</figcaption>
</figure>

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](https://thesecguy.com/notes/prompt-injection-6-real-ai-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](https://modelcontextprotocol.io/specification/2026-07-28/architecture) (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."

<figure class="fig">
<p class="fig-k">Who talks to whom in MCP</p>
<div class="flow">
<div class="node"><b>Host</b><span>The app you use: a chat client or a coding tool. Talks to the model and keeps the conversation</span><div class="chips"><i class="chip">enforces consent</i></div></div>
<div class="node"><b>Client</b><span>One per server, inside the host</span><div class="chips"><i class="chip">tools/list</i><i class="chip">tools/call</i></div></div>
<div class="node"><b>Server</b><span>Wraps a product: files, a database, an API</span><div class="chips"><i class="chip">name</i><i class="chip">description</i><i class="chip">inputSchema</i></div></div>
<div class="node"><b>What the model sees</b><span>The tool descriptions the host passes along, as text in its context</span><div class="chips"><i class="chip">written by the server</i></div></div>
</div>
<figcaption>Our diagram of the roles in the MCP specification, version 2026-07-28.</figcaption>
</figure>

## 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](https://docs.langchain.com/oss/python/concepts/memory) 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](https://invariantlabs.ai/blog/mcp-security-notification). 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](https://thesecguy.com/notes/owasp-top-10-agentic-applications-2026/).

## 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](https://invariantlabs.ai/blog/mcp-github-vulnerability). 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](https://generalanalysis.com/blog/supabase-mcp-blog) 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."

<figure class="fig">
<p class="fig-k">Two demonstrations with the same recipe</p>
<div class="flow">
<div class="node"><b>A stranger writes</b><span>GitHub: an issue on a public repo. Supabase: a support ticket</span><div class="chips"><i class="chip">untrusted content</i></div></div>
<div class="node"><b>The agent reads it</b><span>Asked to do something routine: check issues, list tickets</span><div class="chips"><i class="chip">observe</i></div></div>
<div class="node"><b>It reaches private data</b><span>GitHub: private repos. Supabase: a tokens table</span><div class="chips"><i class="chip">broad credentials</i></div></div>
<div class="node"><b>It writes somewhere visible</b><span>GitHub: a public pull request. Supabase: the ticket thread</span><div class="chips"><i class="chip">way out</i></div></div>
</div>
<figcaption>Sources: Invariant Labs, May 2025; General Analysis, July 2025. Both were researcher demonstrations.</figcaption>
</figure>

Simon Willison [called the Supabase case](https://simonwillison.net/2025/Jul/6/supabase-mcp-lethal-trifecta) "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](https://thesecguy.com/notes/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](https://genai.owasp.org/llmrisk/llm062025-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](https://embracethered.com/blog/posts/2024/chatgpt-macos-app-persistent-data-exfiltration), 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](https://arxiv.org/abs/2503.03704), 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.

<figure class="fig">
<p class="fig-k">MINJA: poisoning an agent's memory with ordinary queries (lab result)</p>
<div class="hbars">
<div class="hbar hot"><em>Malicious records that made it into memory</em><div class="track"><i style="width:98.2%"></i></div><b>98.2%</b></div>
<div class="hbar"><em>Victim queries steered to the attacker's reasoning</em><div class="track"><i style="width:76.8%"></i></div><b>76.8%</b></div>
</div>
<figcaption>Source: Dong et al., "Memory Injection Attacks on LLM Agents via Query-Only Interaction", NeurIPS 2025. The authors report both as averages "across all settings" they tested.</figcaption>
</figure>

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](https://genai.owasp.org/llmrisk/llm052025-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.

1. **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.
2. **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.
3. **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.
4. **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.
5. **Validate arguments in code, as if a stranger typed them.** A valid `order_id` still 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."
6. **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](https://developers.openai.com/api/docs/guides/function-calling)
- OpenAI, "Introducing Structured Outputs in the API", 6 August 2024: [openai.com](https://openai.com/index/introducing-structured-outputs-in-the-api/)
- Yao et al., "ReAct: Synergizing Reasoning and Acting in Language Models", 2022 (ICLR camera-ready version): [arxiv.org/abs/2210.03629](https://arxiv.org/abs/2210.03629)
- Model Context Protocol specification, version 2026-07-28, "Architecture": [modelcontextprotocol.io](https://modelcontextprotocol.io/specification/2026-07-28/architecture), "Tools": [modelcontextprotocol.io](https://modelcontextprotocol.io/specification/2026-07-28/server/tools). MCP "Security Best Practices" (the page at the 2025-06-18 path): [modelcontextprotocol.io](https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices)
- llama.cpp, "GBNF Guide" (grammars README): [raw.githubusercontent.com](https://raw.githubusercontent.com/ggml-org/llama.cpp/HEAD/grammars/README.md)
- LangGraph documentation, "Memory overview": [docs.langchain.com](https://docs.langchain.com/oss/python/concepts/memory)
- Beurer-Kellner, Fischer (Invariant Labs), "MCP Security Notification: Tool Poisoning Attacks", 1 April 2025: [invariantlabs.ai](https://invariantlabs.ai/blog/mcp-security-notification)
- Milanta, Beurer-Kellner (Invariant Labs), "GitHub MCP Exploited: Accessing private repositories via MCP", 26 May 2025: [invariantlabs.ai](https://invariantlabs.ai/blog/mcp-github-vulnerability)
- General Analysis, "Supabase MCP can leak your entire SQL database", July 2025: [generalanalysis.com](https://generalanalysis.com/blog/supabase-mcp-blog)
- Simon Willison, "Supabase MCP can leak your entire SQL database", 6 July 2025: [simonwillison.net](https://simonwillison.net/2025/Jul/6/supabase-mcp-lethal-trifecta), and "The lethal trifecta for AI agents", 16 June 2025: [simonwillison.net](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/)
- Johann Rehberger, "Spyware Injection Into Your ChatGPT's Long-Term Memory (SpAIware)", 20 September 2024: [embracethered.com](https://embracethered.com/blog/posts/2024/chatgpt-macos-app-persistent-data-exfiltration). His full name is from The Hacker News, 25 September 2024: [thehackernews.com](https://thehackernews.com/2024/09/chatgpt-macos-flaw-couldve-enabled-long.html)
- Dong et al., "Memory Injection Attacks on LLM Agents via Query-Only Interaction" (MINJA), NeurIPS 2025: [arxiv.org/abs/2503.03704](https://arxiv.org/abs/2503.03704) and [neurips.cc](https://neurips.cc/virtual/2025/poster/118152)
- OWASP GenAI Security Project, "LLM06:2025 Excessive Agency": [genai.owasp.org](https://genai.owasp.org/llmrisk/llm062025-excessive-agency/), "LLM05:2025 Improper Output Handling": [genai.owasp.org](https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/), and the Top 10 for Agentic Applications launch post, 9 December 2025: [genai.owasp.org](https://genai.owasp.org/2025/12/09/owasp-top-10-for-agentic-applications-the-benchmark-for-agentic-security-in-the-age-of-autonomous-ai/)
