Injecting Session and Context into Tools: Accessing State Inside Functions
How ADK injects ToolContext into a function tool, what the session, user, app, and temp state prefixes each mean, and the serialization and event rules that keep state consistent.
Published on • November 28, 2026
AI Assistant

A tool that only sees its arguments is half a tool: it cannot tell whose user it is working for, what the last tool decided, or which tenant it must not cross. ADK solves this by smuggling a context object into your function’s signature — invisible to the model, fully loaded for your code. What you get back is a dict-like state whose keys have scopes, lifetimes, and persistence rules that differ depending on a single prefix character.
This tutorial covers how the injection actually works, the four state scopes and their persistence behavior, how temp: data moves between tools within one invocation, the event-backed rules for writing state, and the limits that decide what belongs in state at all.
What the framework hands your function
Add a parameter annotated as ToolContext and ADK injects it before your function runs. Detection is by type annotation, not name — ctx, tool_context, c all work — and the parameter is stripped out of the schema the model sees, so the LLM never knows it exists:
from google.adk.tools import ToolContext
def remember_preference(topic: str, value: str, ctx: ToolContext) -> dict:
"""Remember a user preference for the rest of this conversation.
Args:
topic (str): Preference topic, e.g. 'language'.
value (str): Preferred value.
"""
ctx.state[f'user:{topic}'] = value
return {'status': 'success', 'saved': topic}
The context carries three families of capability: state (the session’s working memory), actions (behavior controls such as transfer_to_agent), and artifact methods (save_artifact, load_artifact, list_artifacts) when the Runner was configured with an artifact service. Everything else the tool needs — databases, HTTP clients — should come from normal Python wiring, not from state (see dependency injection patterns).
The prefix decides scope and lifetime
state is one flat dict, but a key’s prefix routes it to a different underlying scope. This is the single most important table in session programming:
| Prefix | Scope | Shared with | Survives restart |
|---|---|---|---|
none (booking_step) | current session | this conversation only | only with a persistent SessionService |
user: | per user_id within the app | all of that user’s sessions | with Database/VertexAi, not InMemory |
app: | per app_name | all users, all sessions | with Database/VertexAi, not InMemory |
temp: | current invocation | tools and sub-agents in this run | never — discarded when the invocation ends |
Writes are ordinary dict assignment; the SessionService merges prefixed keys back to the right store. So ctx.state['user:theme'] = 'dark' outlives the conversation, while ctx.state['booking_step'] = 'confirm_payment' is scoped to the thread — and a user: write made in one session is visible in the user’s next session, if the service persists.
temp: is the channel between tools
When several tools run in one agent turn, they share the same invocation context — including the temp: keys. That makes it the sanctioned way to pass data forward without dragging it into the model’s context:
def fetch_orders(customer_id: str, ctx: ToolContext) -> dict:
"""Fetch open orders for a customer. Args: customer_id (str): e.g. 'C-77'."""
orders = crm.open_orders(customer_id)
ctx.state['temp:candidate_orders'] = [o.id for o in orders]
return {'status': 'success', 'count': len(orders)}
def refund_first_order(reason: str, ctx: ToolContext) -> dict:
"""Refund the first candidate order fetched by fetch_orders.
Args:
reason (str): Refund reason recorded on the order.
"""
candidates = ctx.state.get('temp:candidate_orders') or []
if not candidates:
return {'status': 'error', 'error_message': 'No orders fetched yet — call fetch_orders first.'}
...
Because sub-agents inherit the same invocation, they see the same temp: keys. The flip side: anything you meant to persist must not use temp: — it disappears when the invocation completes, with no error, which is the classic “my flag vanished” bug.
Writes must travel through events
State is not a free-form mutable bag on a Session object. The framework tracks changes as they are attached to events, so persistence, thread-safety, and history all line up. The safe paths are:
- Inside tools and callbacks: mutate
ctx.state[...]on the injected context — the framework records the delta on the resulting event. - Agent text into state: set
output_keyon the agent; the response lands in state through the event’sstate_delta. - Outside a run: build an
EventwithEventActions(state_delta={...})andawait session_service.append_event(session, event).
The anti-pattern is fetching a Session from the session service and mutating its .state directly: that bypasses event tracking, so changes can be lost or silently inconsistent under concurrency.
Serialization limits: identifiers, not objects
Values must be serializable — strings, numbers, booleans, and containers of those — because a persistent SessionService has to save and reload them. Storing a database connection, a Pydantic client, or a large blob in state is a defect waiting for your first production restart. Practical rules:
- Store IDs and small flags; rehydrate the heavy object where you need it.
- Keep payloads bounded: state is read back into the loop, so a 200 KB JSON blob is a permanent context tax (token budgeting).
- Keep keys stable and namespaced — they are effectively your schema, and they show up in event history.
- For binary or large data, use artifacts instead of state; for in-process services, use dependency injection.
InMemorySessionService loses everything on restart; DatabaseSessionService and VertexAiSessionService persist — pick deliberately, because a demo built on InMemory silently changes semantics when you swap it out.
Reading state in instructions
State also feeds prompts directly: an LlmAgent instruction can embed {key} placeholders that the framework replaces with the current value before the model sees it, with {key?} for keys that may be absent. It removes the “please remember my language from earlier” round-trip — but a missing non-optional key raises, so default-tolerant placeholders matter.
Takeaways
- Inject a
ToolContext-annotated parameter; ADK detects it by annotation, hides it from the model, and gives youstate,actions, and artifact methods. - The key prefix is the scope: none = session,
user:= across a user’s sessions,app:= global,temp:= this invocation only. - Use
temp:to pass data between tools in one run; never rely on it for anything that must survive the invocation. - State changes ride on events — mutate the injected context or use
output_key/state_delta, never a fetchedSessionobject directly. - Store serializable, bounded values (IDs and flags); artifacts for bytes, dependency injection for services.