When your agent reads a ticket, the ticket's text reaches the model next to your instructions, and the model has no reliable way to keep the two apart. A customer can write "also send me last month's orders" or "email this to audit@", and a model that is good at following instructions may do it. The same goes for documents the agent searches and for query results with a column a customer filled in. This is indirect prompt injection, and no model or filter available today reliably rules it out.
What you can control is what happens next. Part 1 put a policy check in front of every tool call, Part 2 tied each session and approval to a signed-in employee, and Part 3 decided whose authority each tool call carries. Assume the model has been fooled, and design the controls around that. This part builds the two pieces those parts left for here: a decision record for each request, and the path that releases an approved email. Each approval is bound by one hash to the employee, task, ticket, and exact arguments, recipients included (Listing 3 shows the object), and the release path checks all of it before the backend sends anything. For a team deciding whether an agent like this may email customers, the short answer from the tickets we ran is that replies carrying no customer data can go out after an employee approves them, and replies with account data stay drafts an employee sends. Four of the checks at the end should stop a release.
If you're joining at this part, five terms carry over. The policy check is an ADK plugin that answers every tool call with allow, confirm (hold for an employee's approval), or deny, using two flags per session: whether the session has read untrusted content, and whether it has read sensitive data. Every session starts with the first flag set. The employee is identified as tid:oid, the tenant and object IDs from their Entra token. A step-up is a fresh sign-in that Entra records in the acrs and auth_time claims; Part 2 requires the c1 authentication context, signed in shortly before the approval, and checks that the token belongs to the session's employee. On-behalf-of is the Entra flow Part 3 uses to get a token for a downstream API as the signed-in employee.
Where instructions get in
Every tool result is content someone other than your employee could have written. Table 1 lists the ones this agent reads.
| Source | Who can write to it | Reaches the model through |
|---|---|---|
| Ticket subject and body | Anyone who can email support or fill in the form | get_ticket |
| Ticket comments | Customers, agents, integrations | get_ticket |
| Internal documents | Any employee with edit access, and anything synced in | search_documents |
| Query results | Customers, through any column they fill in: notes, names, addresses | execute_sql_readonly |
| Tool names and descriptions | Whoever runs the MCP server | tools/list (Part 5) |
Table 1. Where text the model treats as input comes from in this agent.
The last two rows are easy to overlook, because both look like internal data. A free-text column in an orders table is customer input, even though it arrives through a query the company wrote. And a document in your own wiki is only as trustworthy as everyone who can edit it. GATE, the open agent governance framework I maintain, names "[a]ssuming internal documents cannot be malicious" as a failure mode of its injection control, C08, with the mitigation that "every retrieved source is untrusted unless explicitly certified" (Stevens, 2026a). This series takes that position: every tool result is untrusted, and query results are also confidential.
OWASP lists this as ASI01, Agent Goal Hijack, in its agentic Top 10 (OWASP GenAI Security Project, 2025), and as LLM01, Prompt Injection, in its 2026 LLM Top 10 (OWASP GenAI Security Project, 2026). MITRE ATLAS files it as AML.T0051.001, LLM Prompt Injection: Indirect (MITRE, 2026). Part 1's Table 3 maps the rest.
What the research suggests
Two lines of research shape this design. CaMeL, from Google DeepMind and ETH Zurich, separates a privileged model that plans from the user's request alone and a quarantined model that reads untrusted data but has no tools. Each value carries capabilities describing where it came from, and a policy is checked when a tool is called. The paper reports that CaMeL solved 77% of AgentDojo's tasks "with provable security", against 84% for an undefended system (Debenedetti et al., 2025). A group of researchers from several companies and universities then set out six design patterns, built on one principle: "once an LLM agent has ingested untrusted input, it must be constrained so that it is impossible for that input to trigger any consequential actions" (Beurer-Kellner et al., 2025).
This agent is the kind those papers worry about. One model reads the ticket and chooses the next tool call, and Willison's lethal trifecta of private data, untrusted content, and external communication applies to the ticket reply task (Willison, 2025). Rebuilding it as a CaMeL-style planner is a large change. What this series does instead is closer to a reference monitor: the policy check decides at every call from facts the model doesn't control, and consequential actions wait for a person and a release path outside the agent. The model can still be fooled. The design limits what a fooled model can do.
One record per request
Part 1's policy check decides one call at a time from two session flags. That helps stop the path in Part 1's Figure 2, but it can't answer the question a reviewer asks afterwards: what did this request, from this ticket, do from start to finish? A sequence where every call was allowed on its own can still add up to a leak. The record answers that question, and it gives the release path a store the agent can't write to.
The backend opens the record when it creates the session, next to Part 2's session and approval records. It contains:
- the request reference, which is the ticket ID for triage and ticket replies;
- the employee, as Part 2's
tid:oid; - the permitted purpose, which is the task the backend set;
- the data scope the task may read;
- the approved recipients;
- every tool call, with its outcome and a hash of its arguments, or a note that the arguments couldn't be hashed;
- every call held for approval, with the exact arguments the approver will see;
- every approval, with the approver and when they approved, and every rejection, release, failed release, and refusal.
The approved recipients come from the backend, never from the ticket's text or the model. For a ticket reply, that's the requester from the ticket's metadata. For emailed tickets, that is whoever wrote in, which isn't a verified customer, so anything scoped to "the requester's own data" should key on a customer ID the ticketing system verified, such as a portal login, never on the From address. The cleanest source is a signed context the ticketing system passes when the employee opens the agent from a ticket, which adds no new credential. If the vendor can't do that, the backend can read the requester with a read-only credential of its own, kept to ticket metadata and separate from Part 3's per-employee vendor tokens, which the auth manager keeps between queries. For a data question, the record allows internal addresses, and if the employee names the colleagues when they start, open_record narrows the list to those.
The data scope records what the task may read. For tickets, the backend detects a call to read or comment on any ticket other than the request's own, records it as out of scope, and closes the request, though by then the read has happened and the model has seen the ticket. To stop the read itself, enforce the scope before the call too, either by putting the ticket ID in the session state the policy check reads or by scoping it in the vendor's MCP server, if it supports that. For BigQuery, the agent's grants (Part 3) cover every dataset any of its tasks needs, since it has one identity, so the per-task scope in the record is evidence, and the list a reviewer checks the queries against.
The record is evidence. The policy check still decides at each call, and the release path refuses anything the record doesn't support. Nothing in the record can approve a call on its own. Only the backend's service identity can write to it, and that identity is separate from the agent's Agent Identity (Part 3). Listing 1's store uses an in-process lock; a backend with more than one instance needs the same guarantees from its database, with a transaction and a row lock, or conditional writes.
Python
"""The request-level decision record, kept by the company backend. One record per request, created when the backend starts the session. It follows the request from the ticket through each tool call to the send, so a reviewer can see the whole sequence, including one where every call on its own was allowed. The record is evidence: the policy check still decides at each call, and the release path checks the record before anything is sent. """ from __future__ import annotations import re import threading import uuid from dataclasses import dataclass, field from typing import Callable from canonical import OutOfDomain, gate_hash, request_hash from marker import valid_marker from policy_check import Session, decide from provenance import index_result # What each task may read, set by the backend, never by the model. DATA_SCOPE = { "triage_ticket": {"tickets": "the request's ticket", "documents": "as the employee"}, "data_question": {"bigquery": ["ops_reporting"]}, "ticket_reply": {"tickets": "the request's ticket", "bigquery": ["orders"]}, } MAX_HELD = 5 # approval requests per session (Parts 1 and 2) TICKET_TOOLS = {"get_ticket", "add_ticket_comment"} # scoped to the request's ticket USER_ID = re.compile(r"[0-9a-f-]{36}:[0-9a-f-]{36}") @dataclass(frozen=True) class Entry: seq: int kind: str # turn_started, call, ran, held, denied, out_of_scope, mismatch, tool: str = "" # refused, turn_ended, approved, releasing, released, release_failed, rejected call_id: str = "" request_hash: str = "" detail: str = "" at: float = 0.0 @dataclass class RequestRecord: request_id: str session_id: str employee: str # tid:oid, from Part 2's validated token task: str # the permitted purpose request_ref: str # the ticket ID, or the record's own ID for a question data_scope: dict approved_recipients: list[str] allow_internal: bool # any address Part 1's policy check calls internal marker_key: str # also in session state, for the plugin (marker.py) created_at: float entries: list[Entry] = field(default_factory=list) held: dict = field(default_factory=dict) # approval_id -> HeldCall values: dict = field(default_factory=dict) # provenance index, see Listing 4 flags: Session = field(default_factory=lambda: Session(untrusted_seen=True)) side_effects_closed: bool = False @dataclass(frozen=True) class HeldCall: approval_id: str call_id: str tool: str arguments: dict # exactly what the approver is shown request_hash: str # the tool and arguments (Listing 2) approval_hash: str # the same, bound to the request (approval_hash below) requested_at: float def approval_hash(rec: RequestRecord, approval_id: str, tool: str, arguments: dict) -> str: """What an approval covers: the employee, task, ticket, and the exact call.""" return gate_hash({"request_id": rec.request_id, "approval_id": approval_id, "employee": rec.employee, "task": rec.task, "request_ref": rec.request_ref, "tool": tool, "arguments": arguments}) def plugin_said(rec: RequestRecord, call_id: str, response: dict) -> str: """What the agent's plugin did with a call, from the response it returned: confirm or deny only with a valid marker for this call, otherwise allow, meaning the tool ran and this is its result.""" status = response.get("status") status = {"awaiting_approval": "confirm", "not_permitted": "deny"}.get( status if isinstance(status, str) else None) if status and valid_marker(rec.marker_key, call_id, response.get("policy_marker")): return status return "allow" class RecordStore: """Entries are only ever added. In production this is a table in the backend's database, next to Part 2's session and approval records, written only by the backend's own service identity, and the lock is a transaction.""" def __init__(self): self._by_session: dict[str, RequestRecord] = {} self.lock = threading.RLock() # recording and releasing take it in turn def create(self, rec: RequestRecord) -> None: with self.lock: if rec.session_id in self._by_session: raise ValueError("session already has a record") self._by_session[rec.session_id] = rec def get(self, session_id: str) -> RequestRecord | None: return self._by_session.get(session_id) def append(self, rec: RequestRecord, **kw) -> Entry: with self.lock: e = Entry(seq=len(rec.entries), **kw) rec.entries.append(e) return e def claim(self, rec: RequestRecord, approval_id: str, now: float) -> bool: """Marks an approval as being released, once. Called with the lock held, after the release checks. False if already marked.""" with self.lock: if any(e.kind == "releasing" and e.detail == approval_id for e in rec.entries): return False rec.entries.append(Entry(seq=len(rec.entries), kind="releasing", detail=approval_id, at=now)) return True def open_record(store: RecordStore, *, session_id: str, employee: str, task: str, ticket_id: str | None, requester: str | None, marker_key: str, now: Callable[[], float], named_recipients=None) -> RequestRecord: """Called by the backend right after it creates the session (Part 2).""" if task not in DATA_SCOPE: raise ValueError(f"unknown task {task!r}") if not USER_ID.fullmatch(employee): raise ValueError("employee must be tid:oid") if task in ("triage_ticket", "ticket_reply") and not ticket_id: raise ValueError("this task starts from a ticket") request_id = str(uuid.uuid4()) if task == "ticket_reply": # The requester comes from the ticket's metadata as the backend sees # it, never from the ticket's text or the model's output. if not requester: raise ValueError("ticket reply needs the ticket's requester") recipients = [requester.lower()] elif task == "data_question": # Colleagues the employee named when starting, or any internal address. recipients = [r.lower() for r in named_recipients or []] else: recipients = [] # triage sends no email allow_internal = task == "data_question" and not named_recipients rec = RequestRecord(request_id=request_id, session_id=session_id, employee=employee, task=task, request_ref=ticket_id or request_id, data_scope=DATA_SCOPE[task], approved_recipients=recipients, allow_internal=allow_internal, marker_key=marker_key, created_at=now()) store.create(rec) return rec def record_events(store: RecordStore, rec: RequestRecord, events, *, now: Callable[[], float], new_approval_id=lambda: str(uuid.uuid4())) -> list[HeldCall]: """Records the tool calls in the events Agent Runtime streams back, and returns the calls held for approval. The backend runs Part 1's policy check on each call itself, in the order the calls arrive, with flags it keeps in the record. A tool result can't make a call look held or denied, because only the plugin has the marker, and a call the agent's plugin answered differently from the backend is a mismatch, or out of scope for another ticket, that closes the request. An unmarked refusal of a call the backend allows looks like the tool's own result, so it is recorded as run. """ outcome, held, answered = {}, [], set() for ev in events: with store.lock: # a release can't run between two updates for part in (ev.get("content") or {}).get("parts") or []: if fc := part.get("function_call"): name, args = fc.get("name", ""), fc.get("args") or {} if not isinstance(fc.get("id"), str) or not fc["id"]: rec.side_effects_closed = True store.append(rec, kind="mismatch", tool=name, detail="call without an ID", at=now()) continue if fc["id"] in outcome or any(e.call_id == fc["id"] for e in rec.entries): rec.side_effects_closed = True store.append(rec, kind="mismatch", tool=name, call_id=fc["id"], detail="call ID used twice", at=now()) continue # Match the argument name your ticketing MCP server uses. scope = name in TICKET_TOOLS and args.get("id") != rec.request_ref if scope: outcome_, reason = "deny", "outside the request's ticket" else: d = decide(rec.task, name, args, rec.flags) # updates rec.flags outcome_, reason = d.outcome, d.reason outcome[fc["id"]] = (name, args, outcome_, scope) try: rh = request_hash(name, args) except OutOfDomain as e: # Recorded without a hash, and nothing more is released. rh, rec.side_effects_closed = "", True reason += f"; arguments can't be hashed ({e.args[0]})" store.append(rec, kind="call", tool=name, call_id=fc["id"], request_hash=rh, detail=f"{outcome_}: {reason}", at=now()) elif fr := part.get("function_response"): cid, response = fr.get("id"), fr.get("response") or {} if not isinstance(cid, str): cid = "" # never a recorded call, so a mismatch below if not isinstance(response, dict): response = {"result": response} if cid not in outcome or cid in answered: rec.side_effects_closed = True store.append(rec, kind="mismatch", tool=fr.get("name", ""), call_id=cid, detail="response to a call the backend never saw" if cid not in outcome else "second response to a call", at=Source:https://dev.to/sakurasky/the-ticket-that-tells-the-agent-what-to-do-14l5