An agent service puts the current tenant in a ContextVar, then starts several tool tasks. Each task gets its own context. One adapter changes scope.get()["tenant"] before a lookup. A sibling can now perform its lookup using that changed tenant, even though nobody called scope.set() in the sibling.

I would not accept task-local context as proof of tenant isolation without inspecting the values stored inside it. A context isolates bindings. A dictionary referenced by those bindings can still be the same dictionary.

The example below reproduces that aliasing in one process, without a model or database. It does not demonstrate an exploit in Claude Code or any other agent product. It tests an application pattern that a Python tool adapter might use. Whether the mistake causes unauthorised access depends on the destination’s checks.

What Python copies when it creates a task

Python’s asyncio.create_task documentation says that, unless a custom context is supplied, the task receives a copy of the current context. The Context.copy contract describes a shallow copy.

There are two separate operations to understand:

scope.set(new_scope)              # Replace this context's binding.
scope.get()["tenant"] = "beta"    # Mutate the object the binding refers to.

The second line does not replace a binding. If the parent and two children refer to that dictionary, they can all observe the mutation. This is ordinary object aliasing across copied contexts; it does not require simultaneous execution on different CPU cores.

In a tool adapter, the damage may happen before a database query. A mutable context can affect the namespace used for retrieval, the credential selected for an API client, or the tenant written into an audit record. Logging the ambient tenant after the call can then record the changed value rather than the scope under which the operation started.

Keep the identity verified at request admission separate from adapter-local options. The adapter should receive a validated operation scope and should not be allowed to choose a different tenant merely by editing a convenience dictionary.

Run the shared-value failure

Download and inspect agent-context-mutation.py. It uses Python 3.11 or later and the standard library. It performs no network calls and writes no files.

python3 agent-context-mutation.py
python3 agent-context-mutation.py --test
python3 -O agent-context-mutation.py --test

The first case binds {"tenant": "alpha"} in the parent. It creates a writer and a reader in a TaskGroup. The writer changes the dictionary to beta, then signals an asyncio.Event. The reader waits for that signal before reading the tenant. Once both children finish, the parent reads it too.

The event makes the observation deterministic. The test is asking whether the mutation is visible after it happens, rather than relying on a sleep to make a scheduling race likely.

The executed example returned:

{
  "shared_dictionary": {
    "sibling": "beta",
    "parent": "beta"
  },
  "immutable_rebinding": {
    "writer": "beta",
    "sibling": "alpha",
    "parent": "alpha"
  }
}

The first result is the defect. A child changed the parent’s tenant dictionary and the sibling read the change. The second result comes from a different design: an immutable value and a child-local replacement binding.

Seven unique regression tests passed on Python 3.11.15, both normally and under optimisation. They cover shared mutation, isolated rebinding, missing context, immutable fields, nested aliases after a shallow dictionary copy, reset after an exception, and inheritance at task creation. The checks use unittest, so python -O does not remove them.

Replace the value instead of editing it

The repaired fixture uses a small value object:

@dataclass(frozen=True)
class Scope:
    tenant: str
    grants: frozenset[str]

A child that needs a different fixture scope binds a new value and restores its previous binding in finally:

child_token = scope.set(Scope("beta", frozenset()))
try:
    # Work using this child's binding.
    ...
finally:
    scope.reset(child_token)

The sibling and parent retain alpha. Rebinding to beta is a demonstration of binding isolation, not a production permission grant. In a real service, only a trusted admission path should construct an authorised scope. Any tool code that can call set() can replace its own ambient value.

Python’s frozen dataclass documentation also warns against reading too much into the word “frozen”: it emulates immutability rather than creating an absolute protection boundary. The fixture uses strings and a frozenset so ordinary application code cannot mutate the nested grants collection. A frozen dataclass containing a list would still leave that list mutable. Type annotations alone would not stop a caller passing a list where a frozenset is expected; production construction needs validation.

Copying a dictionary in each child is an incomplete repair when it contains nested mutable objects. The regression test copies {"grants": ["read"]}, appends "write" through the copy and checks that the original list changed. If your scope includes client objects or caches, a blind deep copy may be inappropriate too. Prefer a deliberately small value containing validated identifiers and immutable permission data.

Task creation fixes the inherited binding

The fixture includes a separate timing test. The parent binds alpha, calls create_task, then binds beta before awaiting the child. The child returns alpha; the parent reads beta.

That behaviour is useful, but it can surprise an adapter that creates tasks before finishing request admission. A later parent set() does not update an already-created child’s copied binding. Establish the validated scope before creating the tasks that should inherit it.

Avoid a mutable default such as ContextVar("scope", default={}). It provides a shared object to code that never established a scope. The example declares the variable without a default, and a test enters an empty context to verify that get() raises LookupError. A production adapter can turn that missing-scope error into an explicit refusal before dispatch. Defaulting silently to a tenant or a privileged service identity would defeat that check.

Reset tokens in finally at the boundary that owns a binding. Resetting changes the binding back; it cannot undo mutations already made to an object. If the old and new bindings point to the same mutated dictionary, resetting a token does not restore the dictionary’s previous contents.

Enforce access where the operation happens

An immutable scope reduces accidental cross-task state changes. It cannot authenticate a user, revoke an expired grant or stop hostile code running inside the same Python process. The destination still needs to enforce the authenticated identity, requested tenant and operation permissions.

For RAG, check the scope on every path that loads document content, including neighbour expansion after search. An isolated context cannot repair an expansion query that omits authorisation. For orchestration, use the task-group cancellation pattern where appropriate, but test shared values separately: task lifetime and object ownership are different contracts.

At dispatch, capture the validated scope in an operation record with the request identifier. Do not reconstruct the original tenant later by reading whatever happens to be in an ambient mutable object. Keep that record distinct from a fresh destination-side authorisation decision, which may reject a permission that was valid when the request began.

For the wider approach to tool permissions and review, see my Claude Code book, available as a Kindle edition on Amazon UK.

Add a sibling task to your adapter tests. Have one child attempt to change the scope, then check the other child’s dispatch arguments and the parent’s operation record. Test both a replacement binding and a nested mutation; a passing result for one says nothing about the other.