Context
The context objects that give agents, tools, and callbacks access to session state, services, and execution information.
Context objects are the bridge between your agent code and the ADK-TS runtime. Every callback, tool function, and agent implementation receives a context object that grants access to session state, loaded services, and information about the current execution.
ADK-TS provides four context types arranged in a hierarchy โ each extends the last, adding capabilities:
InvocationContext is a standalone class โ it is not in the inheritance chain above, but it is the internal data source that all three context types wrap.
When to use each
| Context | Use when |
|---|---|
ReadonlyContext | Generating dynamic instructions; read-only inspection of session state |
CallbackContext | Agent lifecycle callbacks that modify state or read/write artifacts |
ToolContext | Tool implementations that need memory search, artifact listing, or flow control |
InvocationContext | Custom agent implementations that need direct access to services |
Quick examples
Dynamic instruction (ReadonlyContext)
Instruction providers receive ReadonlyContext. Use it to personalise system prompts without risking any side effects:
import { LlmAgent, Runner, InMemorySessionService } from "@iqai/adk";
import type { ReadonlyContext } from "@iqai/adk";
const agent = new LlmAgent({
name: "assistant",
description: "A helpful assistant that greets users by name",
model: "gemini-2.5-flash",
instruction: (ctx: ReadonlyContext) => {
const name = ctx.state["user:name"] || "there";
return `You are a helpful assistant. The user's name is ${name}.`;
},
});
const runner = new Runner({
agent,
appName: "my-app",
sessionService: new InMemorySessionService(),
});Tool with memory (ToolContext)
Tool functions receive ToolContext as their second parameter, injected automatically by the framework:
import { createTool, ToolContext } from "@iqai/adk";
import { z } from "zod";
const recallTool = createTool({
name: "recall",
description: "Search the user's long-term memory",
schema: z.object({ query: z.string() }),
fn: async ({ query }, ctx: ToolContext) => {
const results = await ctx.searchMemory(query);
return results.map(r => r.memory.content);
},
});Next steps
๐ ReadonlyContext
Immutable access to invocation identity and session state
๐ CallbackContext
Mutable state and artifact operations for agent lifecycle callbacks
๐ ๏ธ ToolContext
Memory search, artifact listing, and flow control for tools
โ๏ธ InvocationContext
Full service access for custom agent implementations
๐ก Context Patterns
State scoping, anti-patterns, and testing strategies
๐๏ธ Context Caching
Cache large prompts across requests to reduce latency and cost