Tool, Retrieval, and Memory Poisoning

Michael BrenndoerferDecember 2, 202634 min read

Learn how tool schemas, retrieval snapshots, and durable memory lose integrity. Validate, authorize, and quarantine records across boundaries.

Language AI HandbookAll chapters
Part 61 of 67Agentic AI and Protocol Security
Chapter 467Tool, Retrieval, and Memory Poisoning
Reading the full chapter · 11 sections · 34 min11 sections · 34 min

All 11 sections · 34 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Tool, Retrieval, and Memory Poisoning

The catalog assistant showed a return window yesterday. Today it cites the same policy by name and gives a different answer. The team finds a new index snapshot, a revised tool description, and a saved note from an earlier turn. Which one was allowed to influence the answer?

A review begins by recording what the model saw. It needs the origin of each record, the revision that made it into context, and the decision that admitted it. This chapter follows those decisions across tools, retrieval, and durable memory, then tests them with a local catalog fixture.

Follow the record across boundaries

Here, poisoning means that a record used by the agent has lost integrity and is still treated as acceptable input or state. A record can be inaccurate or unauthorized even when its shape is valid. The previous chapter considered how instructions can appear in supplied content. Here we focus on the records that survive beyond their creation: tool definitions, index snapshots, and stored memory.

Provenance describes where a record came from and how it was produced. The W3C PROV data model represents entities, activities, and the parties involved in producing them. In the catalog example, the source document is one entity, indexing is an activity, and the index snapshot is a derived entity. The service approving the release has a separate role from the process that created the snapshot. W3C PROV-DM

Give every boundary an explicit question.

SurfaceAdmission questionEvidence to retain
Tool definitionIs this the approved definition for this server and operation?Server identity, tool name, contract revision
RetrievalMay this request use this record from this snapshot?Source identifier, revision, index snapshot, access decision
Durable memoryWho authorized this kind of record to persist for this subject and purpose?Write origin, confirmation, scope, retention status

In this chapter, a boundary can admit a record for a specific purpose. A reviewed definition can describe an available operation. An eligible index record can be provided as evidence for a particular request. A confirmed preference can be saved under the patron's own namespace. The decision applies to that use. The host keeps authority in its own policy when checking a new use.

Suppose the index snapshot changed shortly before a disputed answer. The snapshot identifier tells the investigator which collection was queried. The supplied record identifier and revision identify the passage used in the answer. An ingestion receipt can identify which source revision and approved process generated that snapshot. A separate admission decision explains why its records were eligible for the particular request. Both are useful when following a record through the system. A record that passed one checkpoint still needs any evidence required by the next boundary.

The following exercises keep their effects in memory. A gate checks that an object is usable for the intended purpose. An independent observer would be needed to verify that an operation produced the intended result. The fixtures exercise the first of those questions. They also show what an operator can conclude when a record is excluded from normal reads but retained for audit.

Tool poisoning: schemas, descriptions, and implementations

A tool definition and a tool result cross different boundaries. The definition tells the host and model how to describe an available operation. The result supplies data after the call. Review definition revisions before exposing them to the model, and validate results against the approved contract before using them elsewhere. A compromised implementation can return an incorrect value that still conforms to a result schema.

JSON Schema can express structural constraints on a document. Passing those checks establishes conformity to the schema being used. For example, a catalog lookup can accept a syntactically valid item identifier while the caller lacks access to the item it names. Enforce the access decision in the host or service that owns the operation. Keep the policy inputs, such as the authenticated caller, under the application's control. JSON Schema Validation, Draft 2020-12

In revision 2026-07-28 of the Model Context Protocol (MCP), clients must treat tool annotations from untrusted servers as untrusted. Maintain the host's approved capability classification independently of the tool's own description. If a tool advertised as a lookup is approved for reading only, the effect boundary should enforce that restriction. MCP Tools, revision 2026-07-28

Schema checks and independent authorization

A narrow schema makes code review easier because the reviewer can follow a small set of known argument shapes. Restrict optional fields to those you need. Use explicit types, ranges and allowed identifiers where the product contract permits them. Enforce structural rules with the declared schema and enforce access rules against verified caller identity and the actual resource. Keep their results separate in logs so an operator can explain why a call stopped.

Suppose a catalog administrator investigates a disputed lookup. A trace may show that the tool accepted a valid item code. The relevant decision is whether the caller was authorized for that particular item at that time. The shape check narrows the accepted input contract. The resource service uses current authoritative state to decide access. If the schema evolves, review its effects on both accepted documents and the resource checks the tool needs.

Description and result review

Compare tool descriptions to the approved service contract when a definition enters the catalog or receives a revision. For a tool with side effects, use a host-side classification based on verified policy. If the host cannot establish the effect boundary, restrict what the tool can do. A description may express intended behavior but an implementation can change independently, so preserve the approved definition revision and the implementation or deployment evidence paired with it.

Review how the host handles results. A schema can tell us whether an item status belongs to an accepted set. Whether that specific status is current for the actual item depends on evidence from the resource provider. If a result arrives without the required identity or freshness evidence, avoid automatically merging it into an approved source or writing it to durable memory. Instead review which inputs the operation had and what data it returned. The local example below checks typed arguments and compares mock policy decisions for invented records.

A worked example: schema validation versus authorization

The fixture defines a small lookup schema and checks each proposed call against it. Calls that pass go to a separate policy check using mock caller entitlements.

PythonIn [3]
CollapseExpand
import json

# Inert tool schema: a fictional account lookup with a constrained id format.
TOOL_SCHEMA = {
    "name": "lookup_account",
    "parameters": {
        "type": "object",
        "properties": {
            "account_id": {"type": "string", "pattern": "^acct-[0-9]{4}$"},
            "region": {"type": "string", "enum": ["us", "eu"]},
        },
        "required": ["account_id"],
        "additionalProperties": False,
    },
}

This hand-written validator receives an already decoded mapping from the fixture. It checks field types, an anchored pattern, an enum, required keys and extra keys. A production adapter would first enforce the top-level object requirement. The exercise shows the order of field checks before authorization.

PythonIn [4]
CollapseExpand
import re


def validate_call(schema, call):
    params = schema["parameters"]
    props = params["properties"]
    errors = []
    # required keys
    for key in params.get("required", []):
        if key not in call:
            errors.append(f"missing required: {key}")
    # no extra keys
    if params.get("additionalProperties") is False:
        for key in call:
            if key not in props:
                errors.append(f"unexpected key: {key}")
    # per-property checks
    for key, value in call.items():
        spec = props.get(key, {})
        if "type" in spec and not isinstance(value, str):
            errors.append(f"{key}: wrong type")
        if "pattern" in spec and isinstance(value, str):
            if not re.fullmatch(spec["pattern"], value):
                errors.append(f"{key}: pattern mismatch")
        if "enum" in spec and value not in spec["enum"]:
            errors.append(f"{key}: not in enum")
    return errors


assert validate_call(TOOL_SCHEMA, {"account_id": "acct-0001"}) == []
assert validate_call(TOOL_SCHEMA, {"account_id": "acct-0001" + chr(10)}) == [
    "account_id: pattern mismatch"
]

The six fixtures include one permitted request and one well-formed request for an account outside the caller's allowed region. The program gets the mock entitlements from its caller context. The proposed call supplies account and optional region values.

PythonIn [5]
CollapseExpand
# Caller context is a separate, trusted input, not something the model supplies.
CALLER = {"role": "support", "entitled_regions": ["us"]}

# Inert records mapping account -> owning region (fictional).
ACCOUNT_REGIONS = {"acct-0001": "us", "acct-0002": "eu", "acct-0003": "us"}


def authorize_call(call, caller):
    reasons = []
    acct = call.get("account_id")
    region = ACCOUNT_REGIONS.get(acct)
    if region is None:
        reasons.append("unknown account")
    elif region not in caller["entitled_regions"]:
        reasons.append("region not entitled")
    req_region = call.get("region")
    if req_region is not None and req_region != region:
        reasons.append("region mismatch")
    return reasons
PythonIn [6]
CollapseExpand
calls = [
    {"account_id": "acct-0001"},  # valid + authorized
    {"account_id": "acct-0002"},  # valid shape, unauthorized region
    {"account_id": "acct-9999"},  # valid shape, unknown account
    {"account_id": "acct-0001", "region": "eu"},  # valid shape, region mismatch
    {"account_id": "bad-format"},  # pattern failure
    {"account_id": "acct-0001", "debug": True},  # extra property
]

for call in calls:
    schema_errs = validate_call(TOOL_SCHEMA, call)
    auth_errs = (
        authorize_call(call, CALLER) if not schema_errs else ["(skipped)"]
    )
    print(
        json.dumps(call),
        "-> schema:",
        schema_errs or "ok",
        "| auth:",
        auth_errs or "ok",
    )
ConsoleOut [6]
CollapseExpand
{"account_id": "acct-0001"} -> schema: ok | auth: ok
{"account_id": "acct-0002"} -> schema: ok | auth: ['region not entitled']
{"account_id": "acct-9999"} -> schema: ok | auth: ['unknown account']
{"account_id": "acct-0001", "region": "eu"} -> schema: ok | auth: ['region mismatch']
{"account_id": "bad-format"} -> schema: ['account_id: pattern mismatch'] | auth: ['(skipped)']
{"account_id": "acct-0001", "debug": true} -> schema: ['unexpected key: debug'] | auth: ['(skipped)']

The output shows the critical gap. {"account_id": "acct-0002"} passes schema validation cleanly (it is a well-formed account id) yet authorization rejects it because the caller is not entitled to the EU region.

The matrix distinguishes authorization failure from an authorization check that never ran. Review the schema row before interpreting the authorization row.

PythonIn [7]
CollapseExpand
# Recompute the two-check outcome for each candidate call, deterministically.
call_rows = []
for call in calls:
    schema_errs = validate_call(TOOL_SCHEMA, call)
    auth_errs = (
        authorize_call(call, CALLER) if not schema_errs else ["(skipped)"]
    )
    call_rows.append(
        {
            "call": json.dumps(call),
            "schema_ok": not schema_errs,
            "auth_ok": (not schema_errs) and (not auth_errs),
        }
    )
matrix = [
    [int(row["schema_ok"]) for row in call_rows],
    [int(row["auth_ok"]) if row["schema_ok"] else 2 for row in call_rows],
]
VisualizationOut [8]
CollapseExpand
Two rows compare schema and authorization. Four calls pass schema, only call 1 passes authorization, and the last two skip authorization.
Schema and authorization checks for six fictional requests. Two fail schema and never reach authorization.

The valid shape checks do not provide region entitlements. In this fixture four calls pass the schema. Of those four, one is authorized. For the final two, the schema check fails and authorization is skipped. In a deployment the service still applies authorization before using the requested resource. Choose and document the order of validation and access checks with its disclosure policy in mind: the fact that a resource exists can itself be sensitive in some systems. The plot makes the skipped state explicit so an investigator can distinguish a policy reason from an operation that never reached the policy check.

Key Parameters

The key parameters for tool-call validation are:

  • pattern: A regular expression constraining the allowed shape of a parameter such as account_id. Tighter patterns reject malformed inputs before authorization.
  • enum: The set of permitted values for a parameter such as region. Enums eliminate free-string ambiguity.
  • required: The list of keys that must be present. Missing required keys are rejected.
  • additionalProperties: The example rejects unexpected keys when this property is set to false.

Retrieval poisoning: controlling what evidence the model sees

A retrieved passage can be relevant to a question and outside the set of sources the caller is entitled to use. Define the eligible corpus first. For the catalog, bind a request to its catalog scope and an approved index snapshot. Before adding a result to the model's context, check that the result carries the source revision and policy scope required by the request.

Review the path from raw source to indexed record. An approved source revision may yield many derived records. A source reference on each record lets you identify what to invalidate when that revision is withdrawn. Cached answers and summaries can also depend on the revision, so consider invalidation at each downstream reuse point. Keep the snapshot identifier with the trace so an investigator can tell which revision the assistant had available during an earlier answer.

Quarantine an unapproved snapshot from normal reads while keeping enough evidence for review. An integrity check can show that the snapshot matches an approved reference. A mistaken policy document can still pass that check. Approval of a snapshot and evaluation of the answers based on it address different questions.

Review before indexing

Validate whether the source publisher is authorized for the corpus and whether the record has the expected revision. A catalog document can move through an importer, a chunking stage and an indexing job before it appears in a result. Each stage should preserve a stable revision reference or a link to the upstream record. If the input uses a mutable location, capture the actual revision accessed. If the release process replaces an entire index, record the verification evidence associated with the snapshot.

Permission to send an indexed record to a caller depends on the scope at the time of retrieval. Approval to include a source in the corpus is decided at a different boundary. In a multi-tenant application, scope changes can invalidate cached results even when the source bytes and ranking score stay the same. Reapplying request policy on reuse helps the service evaluate those dimensions independently.

Record release and quarantine

When the service sees an unapproved revision, it excludes the candidate from normal context. The review queue can retain the candidate identifier and related evidence. Review staff may need the original record to tell whether the importer changed representations or whether a source never had approval. Their access is for investigation under separate policy. Exclusion from normal retrieval avoids supplying out-of-scope data to the model.

Keep eligibility and relevance calculations distinct. A lookup can score a candidate for relevance without establishing that it may enter the trusted context. If a chart includes a quarantined candidate, its score is a diagnostic value. A similarly scoring record may have a different admission result for a different purpose. The fixture lets you see scores and scope decisions side by side.

A worked example: comparing approved and held catalog revisions

Build a deterministic retrieval fixture from three fictional catalog records. Two are part of the approved snapshot. The third record has a different origin and revision, represented as local fields. A mock allowlist describes which source is approved for ingestion and a snapshot marker represents verified release metadata. The digest printed for investigation is a fingerprint of fixture text. A deployment compares that digest with an independently approved reference.

PythonIn [9]
CollapseExpand
import hashlib
from dataclasses import dataclass, field, replace
from typing import Optional


def content_hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass
class CatalogRecord:
    doc_id: str
    text: str
    source: str
    author: str
    snapshot: str
    relevance_score: int
    integrity_reviewed: bool = False
    quarantined: bool = False
    reason: str = ""

    @property
    def digest(self) -> str:
        return content_hash(self.text)

The approved snapshot contains two authored fixtures, both tagged v1. These provide accepted baseline data. The intake gate checks later candidates against the mock release label and approval fields.

PythonIn [10]
CollapseExpand
ALLOWLISTED_SOURCES = {"internal-catalog"}

trusted_records = [
    CatalogRecord(
        "p-100",
        "The Kestrel widget ships in matte grey.",
        "internal-catalog",
        "catalog-team",
        "v1",
        relevance_score=3,
        integrity_reviewed=True,
    ),
    CatalogRecord(
        "p-101",
        "The Heron widget supports two power modes.",
        "internal-catalog",
        "catalog-team",
        "v1",
        relevance_score=1,
        integrity_reviewed=True,
    ),
]

SNAPSHOT = "v1"

A review candidate describes a new color in the invented catalog. Its record carries a different source and a draft snapshot. Both fields are controlled fixture observations. The approved snapshot remains the version in normal use throughout the exercise.

PythonIn [11]
CollapseExpand
suspicious_revision = CatalogRecord(
    doc_id="p-100",
    text="Alpine travel mug, red finish",
    source="external-scrape",
    author="unknown",
    snapshot="v2-draft",
    relevance_score=3,
    integrity_reviewed=False,
)

The mock intake gate checks a resolved source label, an existing document identifier, the approved snapshot revision and an independent integrity result. The enclosing application supplies the source label, and the fixture retains the separate author field for audit. Integrity review starts unset and the two baseline records explicitly carry a positive result. A production implementation needs authenticated evidence for these inputs.

PythonIn [12]
CollapseExpand
def ingest_gate(record, allowlist, known_ids, approved_snapshot):
    reasons = []
    if record.source not in allowlist:
        reasons.append("Unexpected origin")
    if record.doc_id not in known_ids:
        reasons.append("Unknown document")
    if record.snapshot != approved_snapshot:
        reasons.append("Snapshot not approved")
    if not record.integrity_reviewed:
        reasons.append("Verification missing")
    return reasons
PythonIn [13]
CollapseExpand
known_ids = {r.doc_id for r in trusted_records}
reasons = ingest_gate(
    suspicious_revision, ALLOWLISTED_SOURCES, known_ids, SNAPSHOT
)

if reasons:
    suspicious_revision.quarantined = True
    suspicious_revision.reason = "; ".join(reasons)

print("Quarantined:", suspicious_revision.quarantined)
print("Reasons:")
for r in reasons:
    print("  -", r)
print("Digest of revision:", suspicious_revision.digest)
ConsoleOut [13]
CollapseExpand
Quarantined: True
Reasons:
  - Unexpected origin
  - Snapshot not approved
  - Verification missing
Digest of revision: fd494422f626f8e6ccef4607c27c358e1d980b1846120470b0230d2b7b9c3da7

The gate reports an unexpected origin, an unapproved snapshot and a missing verification result. The document identifier was recognized. An operator can use those distinctions to see why a known item still needs review. The record is retained in a local list with the quarantine flag set. Its content is an ordinary inventory description.

The fixture gives every record an illustrative relevance score. Normal context requires the current gate checks and excludes records under a separate quarantine decision. The diagnostic view prints held records with their assigned scores.

PythonIn [14]
CollapseExpand
def rank_fixture_records(records):
    ranked = [(record.relevance_score, record) for record in records]
    return sorted(ranked, key=lambda pair: pair[0], reverse=True)


def eligible_for_context(record, allowlist, known_ids, approved_snapshot):
    return not record.quarantined and not ingest_gate(
        record, allowlist, known_ids, approved_snapshot
    )


all_records = trusted_records + [suspicious_revision]
admitted_records = [
    record
    for record in all_records
    if eligible_for_context(record, ALLOWLISTED_SOURCES, known_ids, SNAPSHOT)
]
held_records = [record for record in all_records if record.quarantined]


held_reference = replace(trusted_records[0], quarantined=True)
assert (
    ingest_gate(held_reference, ALLOWLISTED_SOURCES, known_ids, SNAPSHOT) == []
)
assert not eligible_for_context(
    held_reference, ALLOWLISTED_SOURCES, known_ids, SNAPSHOT
)
PythonIn [15]
CollapseExpand
trusted_hits = rank_fixture_records(admitted_records)
quarantined_hits = rank_fixture_records(held_records)
assert [score for score, _ in trusted_hits] == [3, 1]
assert [score for score, _ in quarantined_hits] == [3]
assert all(not record.quarantined for _, record in trusted_hits)

print("Trusted context:")
for s, r in trusted_hits:
    print(f"  [{s}] {r.doc_id} ({r.snapshot}, {r.source}): {r.text}")

print("\nQuarantined (visible for review, excluded from prompt):")
for s, r in quarantined_hits:
    print(f"  [{s}] {r.doc_id} ({r.snapshot}, {r.source}): {r.text}")
    print(f"        reason: {r.reason}")
ConsoleOut [15]
CollapseExpand
Trusted context:
  [3] p-100 (v1, internal-catalog): The Kestrel widget ships in matte grey.
  [1] p-101 (v1, internal-catalog): The Heron widget supports two power modes.

Quarantined (visible for review, excluded from prompt):
  [3] p-100 (v2-draft, external-scrape): Alpine travel mug, red finish
        reason: Unexpected origin; Snapshot not approved; Verification missing

The trusted context contains only eligible records from the approved snapshot. The draft color record appears only in the separately printed diagnostic list. Its assigned score ties the highest-scoring eligible record. The comparison shows what the admission rule changes while holding the displayed ranking values fixed. The ranking values are fictional inputs, with no computation over the record's wording.

PythonIn [16]
CollapseExpand
# Use the actual admission and diagnostic pools for the displayed status.
query_scores = [
    {
        "doc_id": record.doc_id,
        "score": record.relevance_score,
        "trusted": trusted,
    }
    for pool, trusted in ((admitted_records, True), (held_records, False))
    for record in pool
]
VisualizationOut [17]
CollapseExpand
Bars of height 3, 1 and 3 distinguish two approved records from one quarantined revision.
Illustrative relevance scores for three fictional catalog records. The held revision ties the highest-scoring approved record and is displayed only for diagnosis.

A retrieval service can represent eligibility both at the index and record scope. Preserve the approved snapshot reference at the query boundary and check the record's current eligibility before assembling prompt context. If a snapshot is withdrawn, retire any cached retrieval that references it or check it again before reuse. This exercise omits caches and authorization backends so we can observe which records are included directly.

Key Parameters

The intake gate reads an approved snapshot identifier, allowed publisher labels, known top-level document identifiers and an integrity-verification result. The allowlist names approved sources. A production issuer check requires authenticated evidence for the record and source. The fixture takes both its resolved source label and separate integrity result from its caller. The document identifier probes whether a candidate is associated with a known item. Approval of a new revision requires its own evidence. For a system that combines both a snapshot check and a request access check, retain both decisions so a later review can distinguish failures at these levels.

Memory poisoning: durable writes and their authority

A patron's display theme has an owner and a purpose. A retrieved record that mentions the same theme has a different origin. The fixture accepts a user preference when the application supplies a confirmation flag. That flag is separate from the text of the preference.

A confirmed preference does not authorize catalog operations. Keep preference records out of the store that grants those operations, and check the patron's scope again when recalling a preference. A later correction should replace the old value in active reads. If the application retains history for review, mark which record was superseded so old preferences do not return as current ones. Expiry and withdrawal also need to apply to any derived summaries that the assistant can recall.

Keep preference updates and reference material separate

A record may begin as an approved retrieval result. The decision that admits it to context is limited to that purpose. Durable state persists across requests and can affect users who were absent when the original record was read. An explicit write policy defines which subjects and record kinds an origin may create and which ones require confirmation. In the catalog fixture, a patron can confirm a display preference. A reference can be stored under its own kind, with a separate policy for recall.

Preserve original provenance through summaries. If a recap paraphrases a retrieved record, the fact that a summarizer created the recap should not erase the source revision that supplied its evidence. When a retained note can influence a future decision, keep the reference to the original record and revision. If the note becomes stale, active recall should point to the current value instead of returning the old note as current.

A persistent update also needs a clear ordering rule. The example appends entries sequentially and supersedes the previous entry for the same key and kind. A service with concurrent writers needs an atomic decision about the current revision. Otherwise two accepted writes can race to become active. Before a memory read, scope it to the current patron and intended purpose just as you would scope a new write.

Memory entries and their status

A memory record can retain the author, origin, and order of observation. It can also retain whether the controller accepted the proposed write. The application should check supersession, expiry and current scope at recall.

A worked example: gated memory writes with provenance and conflict handling

The memory store applies an origin-by-kind write policy and records accepted updates. At this boundary the application supplies a verification flag. The store models one user scope and handles one write at a time.

PythonIn [18]
CollapseExpand
from dataclasses import dataclass, field
from datetime import datetime, timezone


@dataclass
class MemoryEntry:
    key: str
    value: str
    kind: str
    source: str
    author: str  # component or principal
    written_at: str
    trusted: bool
    superseded: bool = False


def now_iso():
    return "2025-01-01T00:00:00Z"  # fixed for determinism

The write policy allows a verified user update in the profile or preference kind and a verified tool update in the account or transaction kind. Retrieval and summary origins can propose reference entries only. The caller must also supply successful verification for the proposed write.

PythonIn [19]
CollapseExpand
WRITE_POLICY = {
    "user": {"profile", "preference"},
    "tool": {"account", "transaction"},
    "retrieval": {"reference"},
    "summary": {"reference"},
}


def may_write(source: str, kind: str) -> bool:
    return kind in WRITE_POLICY.get(source, set())

A disallowed write appends a rejection entry without modifying memory entries. An allowed write supersedes the prior active entry with the same key and kind. The history and rejection list help a reviewer distinguish decisions from a workflow that never ran.

PythonIn [20]
CollapseExpand
class MemoryStore:
    def __init__(self):
        self.entries: list[MemoryEntry] = []
        self.rejections: list[str] = []

    def write(self, key, kind, value, source, author, trusted):
        if not trusted or not may_write(source, kind):
            self.rejections.append(f"Write held for {kind} from {source}")
            return False
        entry = MemoryEntry(
            key, value, kind, source, author, now_iso(), trusted
        )
        for e in self.entries:
            if e.key == key and e.kind == kind and not e.superseded:
                e.superseded = True
        self.entries.append(entry)
        return True

    def read_active(self, key, kind):
        active = [
            e
            for e in self.entries
            if e.key == key and e.kind == kind and not e.superseded
        ]
        return active

Exercise a confirmed user preference, a proposal from an origin outside the record kind's policy, and a tool-verified catalog fact. The held proposal uses a neutral value label. Passing the gate requires both the relevant kind permission and the host-supplied verification Boolean. Production code binds that Boolean to the attestation or confirmation for the specific record and scope.

PythonIn [21]
CollapseExpand
store = MemoryStore()

# Legitimate: user confirms a UI preference.
store.write(
    "ui.theme", "preference", "dark", "user", "user-session-1", trusted=True
)

# A reference source cannot create a catalog fact in this policy.
store.write(
    "catalog.region",
    "account",
    "region-b",
    "retrieval",
    "inventory-reference",
    trusted=False,
)

# The verified tool is allowed to create this record kind.
store.write(
    "catalog.region",
    "account",
    "region-a",
    "tool",
    "catalog-verifier",
    trusted=True,
)

print("Active memory:")
for e in store.entries:
    if not e.superseded:
        print(
            f"  {e.key} = {e.value!r}  (source={e.source}, trusted={e.trusted})"
        )
print("\nRejections:")
for r in store.rejections:
    print("  -", r)
ConsoleOut [21]
CollapseExpand
Active memory:
  ui.theme = 'dark'  (source=user, trusted=True)
  catalog.region = 'region-a'  (source=tool, trusted=True)

Rejections:
  - Write held for account from retrieval

The fixture saves the confirmed preference and tool-verified catalog fact. The retrieval-origin proposal is held and is absent from the active store. A record that was once eligible can become stale or superseded. Retaining the origin and revision lets the owner find entries that should be excluded from later use when the source changes.

Now change the patron's preference through a second confirmed write. The old value remains visible in history and the active preference read selects only the current entry. Insertion order provides the display order in this exercise. A real service should make write ordering and conflict policy explicit.

PythonIn [22]
CollapseExpand
# User changes their mind: new preference supersedes old.
store.write(
    "ui.theme", "preference", "light", "user", "user-session-1", trusted=True
)

active = store.read_active("ui.theme", "preference")
print("Active ui.theme entries:")
for e in active:
    print(f"  {e.value!r} written_at={e.written_at} author={e.author}")

print("\nFull preference history for ui.theme:")
for e in store.entries:
    if e.key == "ui.theme" and e.kind == "preference":
        print(
            f"  {e.value!r} superseded={e.superseded} written_at={e.written_at}"
        )
ConsoleOut [22]
CollapseExpand
Active ui.theme entries:
  'light' written_at=2025-01-01T00:00:00Z author=user-session-1

Full preference history for ui.theme:
  'dark' superseded=True written_at=2025-01-01T00:00:00Z
  'light' superseded=False written_at=2025-01-01T00:00:00Z

The active entry is the latest light value, while the history preserves the earlier dark value marked superseded.

The history for ui.theme can be laid out as a timeline. The earlier write stays in the record, marked inactive, while only the latest value is read back as current.

PythonIn [23]
CollapseExpand
# Collect the ui.theme history in write order with an index for plotting.
theme_history = [
    entry
    for entry in store.entries
    if entry.key == "ui.theme" and entry.kind == "preference"
]
theme_plot = [
    {"idx": i, "value": e.value, "active": (not e.superseded)}
    for i, e in enumerate(theme_history)
]
VisualizationOut [24]
CollapseExpand
Timeline of memory writes showing active and superseded values
The dark theme is superseded in the retained history. The active preference read returns the light theme.

Preserving the earlier entry lets the investigator recover the order of the preference writes. Its inactive status is part of the history. Applications should decide which history is necessary to keep, for what purpose, and for how long. Once a stored record is superseded, its earlier value remains a historical observation. Active reads should honor that status.

A shared integrity harness: provenance, validation, and quarantine

Tool, retrieval and memory decisions need their own controls. They can share an evidence format: the incoming object, the check results, and the decision for a stated use. The next fixture exercises this record using three inputs.

Provenance as a first-class field

For each record the application uses to support a decision, retain the provenance fields relevant to that use. The catalog needs the publisher identity and revision. When comparing artifact contents, retain the verification result and independent reference used for the comparison. Establish freshness with its own policy.

Trust in the provenance metadata depends on its issuance. Record the identity of the authority that assigned each field. In production, a digest needs an independent expected value and a provenance record needs a verified issuer or trusted capture path. The W3C provenance model describes relevant relationships. An application's policy determines how they affect admission or access.

Validation versus authorization versus effect

Use separate decision records for validation, authorization, and observed effect.

  • Validation checks the configured structural rules.
  • Authorization checks whether the identified principal may use the requested operation or record.
  • Effect checking compares the observed outcome with the intended effect, such as whether a stored preference appears in the authorized active read.

The tool example separated validation from permission. In the memory example an approved write can be checked by reading the active entry. At a real effect boundary, the audit record should indicate who observed the change and which request authorized it.

Integrity, provenance, permission, review, effect

Integrity compares the received artifact to an independently trusted reference. Provenance describes origin and production. Permission describes what the acting principal is entitled to do. Review records who approved a transition and on what evidence. Observed effect is an independent observation of the state the action intended to change. One input can pass an integrity check and still need independent approval before activation.

The harness in code

Use a fixture artifact with a fingerprint, an origin, and a separate review flag. The function evaluates those three inputs before marking the record eligible for promotion. A production effect check would need its own direct observation of what changed.

PythonIn [25]
CollapseExpand
@dataclass
class Artifact:
    content_label: str
    source: str
    author: str
    digest: str
    expected_digest: str
    trusted: bool = False

    def integrity_ok(self) -> bool:
        return (
            self.digest == self.expected_digest
            and self.digest == content_hash(self.content_label)
        )


def promote(artifact, allowlist, reviewer_approved: bool):
    checks = {
        "integrity": artifact.integrity_ok(),
        "source_allowlisted": artifact.source in allowlist,
        "reviewer_approved": reviewer_approved,
    }
    artifact.trusted = all(checks.values())
    return checks

Test one intact approved artifact, one artifact with an inconsistent fingerprint, and one artifact delivered with an unexpected origin and no approval. The cases use neutral labels and are evaluated in memory. Comparing the fingerprint demonstrates the form of the integrity decision. The other flags represent expected origin and independent review. The application may consider artifacts for the next stage only if those prerequisites pass.

PythonIn [26]
CollapseExpand
publisher = next(iter(ALLOWLISTED_SOURCES))
good = Artifact(
    "catalog-entry-a",
    publisher,
    "catalog-maintainer",
    content_hash("catalog-entry-a"),
    content_hash("catalog-entry-a"),
)

different_revision = Artifact(
    "catalog-entry-b",
    publisher,
    "catalog-maintainer",
    content_hash("catalog-entry-b"),
    content_hash("catalog-entry-a"),
)

untrusted = Artifact(
    "catalog-entry-c",
    "other-catalog",
    "unverified-origin",
    content_hash("catalog-entry-c"),
    content_hash("catalog-entry-c"),
)

for name, art, approved in [
    ("Approved", good, True),
    ("Different revision", different_revision, True),
    ("Other source", untrusted, False),
]:
    checks = promote(art, ALLOWLISTED_SOURCES, approved)
    print(name, "->", checks, "| trusted:", art.trusted)
ConsoleOut [26]
CollapseExpand
Approved -> {'integrity': True, 'source_allowlisted': True, 'reviewer_approved': True} | trusted: True
Different revision -> {'integrity': False, 'source_allowlisted': True, 'reviewer_approved': True} | trusted: False
Other source -> {'integrity': True, 'source_allowlisted': False, 'reviewer_approved': False} | trusted: False

The second candidate fails the integrity comparison because the observed digest differs from the expected value. The third candidate matches its fingerprint but fails both the origin and review comparisons. A matching digest answers neither of the other two checks.

The per-check results can be shown as a matrix, which makes the "all checks must pass" rule visible and shows which gate blocked each artifact.

PythonIn [27]
CollapseExpand
# Recompute promotion checks for each artifact, keeping per-check outcomes.
harness_artifacts = [
    ("Approved", good, True),
    ("Different revision", different_revision, True),
    ("Other source", untrusted, False),
]
harness_rows = []
for name, art, approved in harness_artifacts:
    checks = promote(art, ALLOWLISTED_SOURCES, approved)
    harness_rows.append({"name": name, "checks": checks})
gate_names = ["integrity", "source_allowlisted", "reviewer_approved"]
grid = [
    [1.0 if row["checks"][g] else 0.0 for g in gate_names]
    for row in harness_rows
]
VisualizationOut [28]
CollapseExpand
The approved record passes every check. The different-revision record fails integrity. The other-source record fails origin and review.
The fictional approval matrix compares integrity, origin, and independent review for three catalog records.

Each fixture retains its three check results. Promotion requires all three to pass. In a deployment, review evidence should identify the approving party, the artifact and the intended use.

Withdraw a snapshot across read surfaces

When a source revision is withdrawn, compare its identifier with the source references still available to the application. A system can keep a historic copy for audit while making the same copy unavailable to ordinary reads. Treat withdrawal as a state change in the active-read policy. Deleting whatever the index last emitted would make it more difficult to explain how an earlier answer was formed. Leaving it eligible would make a later answer depend on a record the owner has withdrawn.

For this example, a downstream record identifies the set of source revisions that produced it. A plain audit reference points to a reviewed source and never enters ordinary prompt context. An indexed passage and a cached answer both depend on the first catalog revision, and a saved summary depends on it indirectly. The summary already carries a closed set of revision references. The fixture therefore checks set membership without trying to reconstruct a derivation graph. A deployment needs to decide whether to record direct source references, retain the derivation graph, or do both. Either design should let a reviewer locate the records that are eligible to be reused for a given request.

PythonIn [29]
CollapseExpand
from dataclasses import dataclass


@dataclass(frozen=True)
class ReadRecord:
    identity: str
    revisions: frozenset[str]
    auditing_only: bool = False


records = {
    "passage": ReadRecord("passage", frozenset({"catalog-r1"})),
    "cached answer": ReadRecord(
        "cached answer", frozenset({"catalog-r1", "catalog-r2"})
    ),
    "saved summary": ReadRecord("saved summary", frozenset({"catalog-r1"})),
    "other item": ReadRecord("other item", frozenset({"catalog-r2"})),
    "audit history": ReadRecord(
        "audit history", frozenset({"catalog-r1"}), auditing_only=True
    ),
}


def available_for_context(record, withdrawn):
    return not record.auditing_only and not record.revisions.intersection(
        withdrawn
    )


before = [
    name
    for name, record in records.items()
    if available_for_context(record, set())
]
after = [
    name
    for name, record in records.items()
    if available_for_context(record, {"catalog-r1"})
]
inactive = [name for name in before if name not in after]
assert after == ["other item"]
assert inactive == ["passage", "cached answer", "saved summary"]
print("Unavailable after source withdrawal:", inactive)
print("Eligible from the remaining revision:", after)
ConsoleOut [29]
CollapseExpand
Unavailable after source withdrawal: ['passage', 'cached answer', 'saved summary']
Eligible from the remaining revision: ['other item']

The withdrawal removes three previously eligible records from normal context. The three remain in the dictionary with their original revision sets. The audit record was already unavailable in normal reads, so it is absent from the newly ineligible list. For the cached answer, retaining both source references matters: if even one contributing revision is withdrawn, you may need to regenerate the answer under the revised policy. Simply attaching the surviving revision would misrepresent the result's origin.

When applying this rule to an application, store the revision expectation alongside the access policy that allowed the original use. The simulated eligibility question is about the withdrawn revision set and the record's purpose flag. Other production decisions also check current principal, scope and authorization. A verified source identity can persist while one particular revision becomes ineligible. A request can retain access to other records from that publisher after the withdrawn revision is excluded. Record the disposition for each affected reuse channel, particularly when caches have their own lifecycle.

This is also a test of the recovery procedure. A restored index snapshot can have the same bytes the service once approved, while the current withdrawal rules still make records inside it ineligible for the present use. Restore historical evidence under an investigation policy and reconstruct ordinary read eligibility from current approved state. Associate the recovery decision with the exact snapshot or revision so a later review can tell which path produced each restored record.

Limitations and impact

The fixtures isolate admission decisions. Deployment needs separate evidence about operation effects and later reuse.

Shape checking has a limited purpose. A structural check validates the configured contract. An approved author can publish an inaccurate value that conforms to it. Record what the implementation checks and how it handles incompatible or stale results. A semantic check should judge meaning from authoritative records when available. In their absence, record uncertainty and ask for review when the decision is consequential.

Source metadata needs independent support. An identifier that appears in a document provides no evidence on its own about who published it. Retain issuance evidence separately and bind it to the record or snapshot used at runtime. Approval of one revision does not carry over to another merely because a label is repeated. A digest comparison documents which bytes passed a specific integrity check. Whether the operation can change state remains a separate question.

Withdrawal has to reach derived records. Removing a source from new indexing is one task. Removing old indexed records from eligibility, invalidating a cached result, and restricting later summary reuse are distinct tasks. The audit trail should identify the revision and affected records so replay can distinguish what was available then from what is allowed now. A rollback to an older snapshot still checks current eligibility.

Effects require direct evidence. A tool acknowledgement records what the tool reported. For a consequential operation, check state at the effect boundary and associate the observation with the authorized request. A memory write acknowledgement can likewise be paired with a scoped read of the current entry. When this observation is unavailable, the audit should record the gap.

A staged deployment can test admission boundaries independently of the model. Construct benign cases with unapproved revisions, withdrawn scope, missing verification or superseded memory. Count which checks deny or hold the fixtures, then verify that approved cases still complete the intended read or update. When a gate sends too many eligible records to review, review whether the evidence that separates their cases is recorded precisely enough. These local cases supply a reproducible answer about eligibility.

Summary

Tool definitions, index records, and durable memory have different admission rules. Retain the origin and revision of each record so the application can review and withdraw it. Validate structure, check the request's scope, and make persistent writes subject to their own policy. Recheck authorization at the point where an operation would take effect.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about tool, retrieval, and memory poisoning.

Tool, Retrieval, and Memory Poisoning

Question 1 of 80 of 8 completed
In this chapter, a tool call with a well-formed account_id passes schema validation but is rejected. According to the worked example, what is the most likely reason?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 19

Agent Supply Chains and Protocol Security

Build a release gate for agent tool supply chains. Verify artifacts, detect drift, and enforce revocation and least privilege.

35 min read
Language AI Handbook · Vol. 19

Audit, Detection, and Incident Response

Design tamper-evident audit trails, build layered detectors that survive base rates, and run incident response with kill switches and evidence preservation.

50 min read
Language AI Handbook · Vol. 19

Secrets, Sandboxes, and Safe Execution

Isolate credentials, bound agent capabilities, and validate outputs through separate policy decisions. Learn to trace enforcement boundaries.

32 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026toolretrieval, author = {Michael Brenndoerfer}, title = {Tool, Retrieval, and Memory Poisoning}, year = {2026}, url = {https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Tool, Retrieval, and Memory Poisoning. Retrieved from https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation
MLAAcademic
Michael Brenndoerfer. "Tool, Retrieval, and Memory Poisoning." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation>.
CHICAGOAcademic
Michael Brenndoerfer. "Tool, Retrieval, and Memory Poisoning." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Tool, Retrieval, and Memory Poisoning'. Available at: https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Tool, Retrieval, and Memory Poisoning. https://mbrenndoerfer.com/writing/tool-retrieval-memory-poisoning-provenance-validation
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy