Overview
ToolContext carries request-scoped identity to your tools—answering the question “who is making this request?” It provides user IDs, organization IDs, session information, and auth claims that tools need to act on behalf of specific users.
Class Definition
Features
- Request identity: Carry user_id, org_id, session_id, and auth claims
- Typed metadata fields: Access
tool_nameandtool_call_iddirectly - Dict-style access: Simple
ctx["key"]syntax for accessing identity data - Lightweight: Only request-scoped data, not infrastructure
Using ToolContext
The Recommended Pattern
Close over infrastructure at tool definition time, receive identity at runtime:Accessing Identity Data
Tools access request-scoped identity using dict-style syntax:Accessing Metadata Fields
Tools can also access typed metadata about the current execution:Passing Context to Agent
Context is provided per-request with the identity of who is making the request:Agent-Level Context (Shared Identity Defaults)
For scenarios where some identity data is constant (e.g., service accounts, system agents):Context Merging
When both agent-level and run-level contexts are provided, they merge with run-level taking precedence:Parameter Naming Convention
The tool runner looks for specific parameter names to identify context parameters:ToolContext
Preferred short form. Must be the first parameter.
ToolContext
Alternative longer form. Must be the first parameter.
Typed Fields
These fields are automatically populated by the agent:Dict-Style Access Methods
ToolContext supports full dict-style access for backward compatibility:
Common Context Keys
Here are common keys used in ToolContext—all represent request identity, not infrastructure:Examples
Multi-Tenant Data Access
Permission-Gated Actions
Personalized Recommendations
Audit Logging
Error Handling
Missing Context
When a tool expects identity but none is provided:Missing Identity Keys
Handle optional identity gracefully:Backward Compatibility
Tools Without Context
Tools without a context parameter work normally:Existing Code Works Unchanged
TheToolContext dataclass is fully backward compatible. Existing tools using dict-style access continue to work:
Testing with Context
Testing is clean because infrastructure is separate from identity:Testing Permission Checks
Best Practices
Close Over Infrastructure
Capture databases, API clients, and other infrastructure when defining tools:Document Expected Identity
Document what identity keys your tools expect:Validation Helper
Create a validation helper for required identity:Identity Factory
Create identity context consistently from your auth layer:See Also
- Agent - Agent.run() with tool_context
- Adding Tools - Creating custom tools
- Structured Output Guide - Complete guide including tool context