pub struct ToolContext { /* private fields */ }Expand description
Context passed to Rust tools during dispatch, mirroring the Python SDK’s ToolContext.
Provides access to the current conversation ID, a shared key-value state store that persists across tool calls within the same agent turn, and an idle flag.
The state is backed by Arc<Mutex<HashMap>> so it can be cheaply cloned
and shared across concurrent tool invocations.
§get_state vs set_state error handling
These two methods intentionally handle mutex poisoning differently:
-
get_statereturns the caller-supplieddefaultwhen the lock is poisoned. Reads are best-effort — a missing value is indistinguishable from a default, so returningdefaultkeeps the tool running without surfacing infrastructure errors to the model. -
set_statereturnsErrwhen the lock is poisoned. Writes that silently vanish can cause subtle logic bugs, so callers must handle the failure explicitly.
Implementations§
Source§impl ToolContext
impl ToolContext
Sourcepub fn new(conversation_id: Option<String>) -> Self
pub fn new(conversation_id: Option<String>) -> Self
Create a new context with the given conversation ID.
Create a context that shares an externally-provided state map.
Use this when multiple ToolContext instances (e.g. successive tool
calls within the same agent) must read/write the same state store.
Sourcepub fn conversation_id(&self) -> Option<&str>
pub fn conversation_id(&self) -> Option<&str>
Return the conversation ID, if one has been set.
Sourcepub fn get_state(&self, key: &str, default: Value) -> Value
pub fn get_state(&self, key: &str, default: Value) -> Value
Retrieve a value from the shared state, returning default if the key
is absent or the lock is poisoned.
This method never fails — on a poisoned lock it logs a warning and
returns default. See the struct-level docs for rationale.
Sourcepub fn set_state(&self, key: &str, value: Value) -> Result<(), ToolError>
pub fn set_state(&self, key: &str, value: Value) -> Result<(), ToolError>
Insert or update a value in the shared state.
Unlike get_state, this method returns Err on a
poisoned lock because silently dropping a write can cause subtle bugs.
See the struct-level docs for rationale.
§Errors
Returns ToolError
if the mutex is poisoned.