Skip to content
Next Security

Threat modeling AI agents and MCP toolchains

A method for threat modeling LLM agents and MCP servers: map tool authority, trace untrusted input to side effects, and enforce controls outside the model.

Published
Author
Next Security Research
Topics
  • AI security
  • MCP
  • Agents
  • Threat modeling
  • Prompt injection
Tested scope
Method article: no live system tested. Protocol references are to the Model Context Protocol specification revision 2025-06-18 and OWASP Top 10 for LLM Applications 2025.

Key takeaway

Model an agent by what its tools are allowed to do on whose behalf; any text the model reads can steer those tools, so enforce limits in the tools, not in the prompt.

TL;DR

An AI agent is a program that lets a language model choose which tools to call and with which arguments. The model cannot reliably tell instructions from data: anything it reads, including an email, a web page, a code comment, a retrieved document or a tool’s own description, can change what it decides to do next. That is prompt injection, and no published technique removes it completely.

So the threat model should start from authority rather than from the model. Ask what each tool can do, on whose behalf, with which credential, and what text can reach the model before it calls that tool. The dangerous case is specific: the agent reads content an attacker can influence, it can access data or actions the attacker cannot, and it has a channel to act or send data outward without a human check. When all three are present, assume an attacker can trigger the action. Remove any one of them and the attack path breaks.

The Model Context Protocol (MCP) makes it easy to add tools, which is useful and also widens this surface quickly. Each MCP server brings tool descriptions into the model’s context, returns content that the model treats as input, and often holds tokens for a downstream API.

Business context and attack surface

Teams adopt agents to save time on tasks that cross systems: triaging support tickets, summarizing and acting on email, opening pull requests, querying internal data, running cloud operations. The value comes from the agent holding real permissions. The risk comes from the same place.

The question a security review has to answer for a product or platform owner is concrete: if someone outside the organization can get text in front of this agent, what is the worst thing the agent can be made to do, and would anyone notice? A jailbreak screenshot does not answer it. A map of tools, credentials and data flows does.

A typical agent deployment has these parts:

  • The host application and agent loop. It assembles the context window, calls the model, parses tool calls and executes them.
  • The model provider. Receives everything in the context, including retrieved data and tool output.
  • MCP clients and servers. Local servers often run over stdio as a process on the user’s machine with the user’s privileges. Remote servers run over HTTP and authenticate with OAuth.
  • Downstream systems. The APIs, databases, mailboxes and repositories the tools act on.
  • Content sources. Retrieval indexes, web fetches, tickets, emails, files and memory stores that feed the context.
Agent trust boundaries and an indirect prompt injection pathA user talks to an agent host, which calls a model. The agent connects through MCP to a read tool that fetches external content and a send tool that acts outward. An attacker-controlled document enters through the read tool, reaches the model context, and drives a call to the send tool. Risk markers sit on the external content and the outbound action. A policy check between the agent and the send tool is the control point.Your boundary: host and policyUserAgent hostModel providerMCP: read docsMCP: send emailTool policy checkShared docOutsideassembles contextsees all contextreturns untrusted textacts with user tokenscope, args, approvalattacker textrecipientIllustrative model. Amber dashes: attacker-influenced path. Cyan: where the control has to sit.
Illustrative: attacker text enters through a read tool and reaches the send tool through the model. The only reliable stopping point is the policy check outside the model.

A five-step method

These steps run in order because each depends on the last.

1. Inventory tools and their real authority

For every tool exposed to the agent, record: what it does, which credential it uses (the end user’s delegated token, a shared service account, or the local user’s OS privileges), the scopes on that credential, and whether the action is reversible. A tool called search_tickets backed by a service account that can also delete tickets has the authority of the service account, whatever its name says.

2. Mark every source of untrusted text

List every path by which text reaches the context window: user input, retrieved documents, web pages, tool results, error messages, memory, and the tool descriptions themselves. Mark each one as controlled by you, by the user, or by a third party. Shared documents, inbound email, public issues and web content are third-party controlled.

3. Trace untrusted text to side effects

For each third-party source, ask which tools the agent could call in the same session after reading it. The pairing of an untrusted source with a tool that writes, sends, deploys, pays or changes permissions is a candidate attack path. Pay particular attention to quiet exfiltration channels: a tool that fetches a URL, a rendered markdown image whose URL carries data in its query string, or a link the user is likely to click.

4. Check where enforcement lives

For each candidate path, find where the limit is enforced. If the only control is an instruction in the system prompt (“never send email to external domains”), treat the path as open. Instructions influence the model; they do not bind it. Enforcement has to be in code that runs outside the model: the tool handler, the host’s policy layer, the downstream API’s authorization, or a human approval step.

5. Write test cases and controls per path

Each open path gets a mitigation with an owner and a safe test that shows whether the mitigation holds. The validation section below has examples.

MCP-specific threats

MCP adds some threats that are worth naming separately because they come from the protocol and its deployment patterns, not from the model.

Tool description poisoning. Tool names and descriptions are inserted into the model’s context. A malicious or compromised server can put instructions in a description, for example telling the model to read a local file and include it in a call to another tool. The user rarely sees descriptions in full.

Definition changes after approval. A user approves a server once. If the server later changes its tool definitions, many clients do not ask again. Pin what was reviewed.

Tool shadowing across servers. When several servers are connected, one server’s description can try to change how the model uses another server’s tools, or register a tool with a confusingly similar name.

Confused deputy and token passthrough. A remote MCP server that accepts a token from the client and forwards it to a downstream API, or that uses its own broad credential to act for any caller, lets a caller borrow authority they do not have. The MCP security best practices prohibit token passthrough and require servers to validate that tokens were issued for them. This is CWE-441: Unintended Proxy or Intermediary.

Local server privilege. A stdio server runs as the local user. If it can execute shell commands or read the filesystem, any instruction that reaches the model can try to use that. Third-party local servers are also a supply-chain dependency that runs with your developer’s credentials.

What an attacker needs, and what they cannot do

To exploit an indirect injection path, an attacker needs three things: a way to place text where the agent will read it (a shared document, an email to the user, a public issue, a web page the agent will fetch, or a tool description), a session in which the agent reads that text and then holds a tool with the effect they want, and the absence of an enforced check on that tool call.

They do not need access to your systems, credentials or the model. That is what makes the class serious.

What they cannot do is exceed the authority of the tools. If the send tool can only address recipients inside the organization, external exfiltration through it fails no matter what the model is told. If the deploy tool requires a human approval that shows the exact arguments, the attacker has to also deceive the human, which is a different and harder attack. If tools act with the end user’s own scoped token, the agent cannot reach data that user could not reach.

Root cause and mitigations

The root cause is that control decisions are delegated to a component that processes untrusted input as instructions. CWE-1427: Improper Neutralization of Input Used for LLM Prompting describes the input side; the impact side is usually missing or incorrect authorization in the tool layer.

Declare tool policy outside the model

A policy file read by the host, not by the model, keeps the rules out of reach of injected text:

# agent-policy.yaml (illustrative; enforce in the host before executing a tool call)
tools:
  docs.search:
    effect: read
    credential: user_delegated
  email.send:
    effect: external_write
    credential: user_delegated
    args:
      to:
        allow_domains: ["example.com"]
    require_approval: true          # show exact recipient, subject and body
    deny_if_session_read_untrusted: true
  repo.merge_pr:
    effect: privileged_write
    require_approval: true
    approvers: ["repo_maintainer"]
session:
  max_tool_calls: 25
  untrusted_sources: ["docs.search", "web.fetch", "email.read"]

The deny_if_session_read_untrusted rule is a simple form of taint tracking: once the session has ingested third-party content, high-impact tools require approval or are disabled for the rest of the session.

Authorize in the tool handler, as the user

Every tool handler should check the end user’s permission on the specific resource, with the user’s identity, even if the model asked politely:

// MCP tool handler (TypeScript, illustrative)
async function getInvoice(args: { invoiceId: string }, ctx: ToolContext) {
  const user = ctx.auth.subject;                 // from a token issued for this server
  const invoice = await db.invoice.findFirst({
    where: { id: args.invoiceId, tenantId: user.tenantId },
  });
  if (!invoice || !(await canRead(user, invoice))) {
    throw new ToolError('not_found');            // same answer for missing and forbidden
  }
  return redact(invoice, user.scopes);
}

Bind tokens to the server and keep scopes narrow

Remote MCP servers should validate the token audience (the MCP specification uses OAuth resource indicators, RFC 8707, for this), request the smallest scopes per tool, and obtain their own downstream tokens rather than forwarding the client’s.

Pin and review tool definitions

Hash the tool list (names, descriptions, input schemas) when a server is approved, and require re-approval when the hash changes:

# Record the reviewed manifest, fail CI or startup on drift (illustrative).
# "mcp-client" stands for whichever client or SDK call returns tools/list for a server.
mcp-client list-tools --server billing --json | jq -S . | sha256sum > billing.tools.sha256

Close quiet exfiltration channels

Do not render remote images or auto-fetch URLs from model output in the UI. If you must render them, proxy through an allowlist. Restrict outbound network access for local MCP servers that do not need it by running them in a container or sandbox with no network or an egress allowlist.

Treat model output as untrusted input everywhere

Output that flows into a shell, SQL query, HTML page or another tool gets the same validation and encoding as user input. This is the same rule as for any other untrusted string, and it is where classic injection bugs reappear in agent systems.

Validation steps

Run these in a test tenant with test data and canary values, never against real third-party systems:

  1. Indirect injection canary. Place a document in a source the agent reads that instructs it to send its contents to a canary address or fetch a canary URL. Confirm the policy layer blocks or holds the call for approval, and that the attempt is logged.
  2. Authorization with two users. As user A, ask the agent to read a resource that belongs to user B. Confirm the tool returns not-found and that the call used A’s identity.
  3. Definition drift. Change a tool description on a test server. Confirm the client refuses to use it until re-approved.
  4. Token audience. Present a token issued for a different resource to the MCP server. Confirm rejection.
  5. Approval fidelity. Confirm approval prompts show the actual arguments that will execute, not a model-written summary of them.
  6. Exfiltration through rendering. Have the model output a markdown image pointing at a canary URL with data in the query string. Confirm the UI does not fetch it.

Keep these as regression tests. Agent behavior changes when you change models, prompts or tool sets, and a control that held last month may not hold after an upgrade.

Framework mapping

Where these issues correspond to published frameworks:

  • OWASP Top 10 for LLM Applications 2025: LLM01 Prompt Injection (direct and indirect), LLM02 Sensitive Information Disclosure, LLM03 Supply Chain (third-party MCP servers), LLM05 Improper Output Handling, LLM06 Excessive Agency.
  • MITRE ATLAS: AML.T0051 LLM Prompt Injection, including the indirect sub-technique. ATLAS adds agent-related techniques regularly; check the current matrix for tool-invocation entries before citing them in a report.
  • CWE: CWE-1427, CWE-441, CWE-862: Missing Authorization.
  • The combination of untrusted content, private data and an outbound channel was described by Simon Willison as the lethal trifecta; it is a useful shorthand for step 3 of the method.

Limits and uncertainty

This is a method article. It does not report results against a specific product, model or MCP server, and the code is illustrative.

Prompt injection classifiers and guard models can reduce the rate of successful injections, but they are probabilistic and can be evaded. Use them as a detection layer, not as the control that makes a high-impact tool safe to expose.

The MCP specification is revised regularly, and client behavior on approvals, definition changes and authorization differs between implementations. Check the revision your clients and servers implement. The 2025-06-18 revision is the reference here.

Human approval only works if people read what they approve. Approval prompts that appear dozens of times a session get clicked through. Reserve them for high-impact actions and make the arguments readable.