Skip to main content

Agent

Struct Agent 

Source
pub struct Agent { /* private fields */ }
Expand description

Agent that orchestrates interactions between a language model and tools

Create an agent using the builder pattern:

use mixtape_core::{Agent, ClaudeSonnet4_5, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let agent = Agent::builder()
        .bedrock(ClaudeSonnet4_5)
        .with_system_prompt("You are a helpful assistant")
        .build()
        .await?;

    let response = agent.run("Hello!").await?;
    println!("{}", response);
    Ok(())
}

Implementations§

Source§

impl Agent

Source

pub fn builder() -> AgentBuilder

Create a new AgentBuilder for fluent configuration

§Example
use mixtape_core::{Agent, ClaudeHaiku4_5, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let agent = Agent::builder()
        .bedrock(ClaudeHaiku4_5)
        .with_system_prompt("You are a helpful assistant")
        .build()
        .await?;

    let response = agent.run("Hello!").await?;
    println!("{}", response);
    Ok(())
}
Source§

impl Agent

Source

pub fn authorizer(&self) -> &RwLock<ToolCallAuthorizer>

Get the authorizer to grant/revoke permissions.

Source

pub async fn respond_to_authorization( &self, proposal_id: &str, response: AuthorizationResponse, ) -> Result<(), PermissionError>

Respond to an authorization request with a choice.

Use this to respond to crate::AgentEvent::PermissionRequired events.

Source

pub async fn grant_tool_permission( &self, proposal_id: &str, tool_name: &str, scope: Scope, ) -> Result<(), PermissionError>

Grant permission to trust this tool entirely.

This saves a tool-wide grant that will auto-authorize all future calls.

Source

pub async fn grant_params_permission( &self, proposal_id: &str, tool_name: &str, params_hash: &str, scope: Scope, ) -> Result<(), PermissionError>

Grant permission for this exact call.

This saves an exact-match grant for the specific parameters.

Source

pub async fn authorize_once( &self, proposal_id: &str, ) -> Result<(), PermissionError>

Authorize a request once (don’t save).

Source

pub async fn deny_authorization( &self, proposal_id: &str, reason: Option<String>, ) -> Result<(), PermissionError>

Deny an authorization request.

Source§

impl Agent

Source

pub async fn run(&self, user_message: &str) -> Result<AgentResponse, AgentError>

Run the agent with a user message

This will execute an agentic loop, calling the model and executing tools until the model returns a final text response.

Returns an AgentResponse containing the text response, tool call history, token usage statistics, and timing information.

If a session store is configured, this will automatically load and resume the session for the current directory.

§Errors

Returns AgentError which can be:

  • Provider - API errors (authentication, rate limits, network issues)
  • Tool - Tool execution failures
  • Session - Session storage errors (if session feature enabled)
  • NoResponse - Model returned no text
  • MaxTokensExceeded - Response hit token limit
  • ContentFiltered - Response was filtered
  • ToolDenied - Tool execution was denied by user/policy
Source§

impl Agent

Source

pub fn add_tool<T: Tool + 'static>(&mut self, tool: T)
where T::Input: Serialize,

Add a tool to the agent’s toolbox

Source

pub fn list_tools(&self) -> Vec<ToolInfo>

List all configured tools

Source

pub fn format_tool_input( &self, tool_name: &str, params: &Value, context: Display, ) -> Option<String>

Format tool input parameters for presentation

Returns formatted string if the tool has a custom presenter, None otherwise (caller should fall back to JSON).

Source

pub fn format_tool_output( &self, tool_name: &str, result: &ToolResult, context: Display, ) -> Option<String>

Format tool output for presentation

Returns formatted string for the tool output.

Source§

impl Agent

Source

pub fn add_hook(&self, hook: impl AgentHook + 'static) -> HookId

Add an event hook to observe agent execution.

Returns a HookId that can be used to remove the hook later via remove_hook.

Hooks receive notifications about agent lifecycle, model calls, and tool executions in real-time.

§Example
use mixtape_core::{Agent, ClaudeSonnet4_5, AgentEvent, AgentHook};

struct Logger;

impl AgentHook for Logger {
    fn on_event(&self, event: &AgentEvent) {
        println!("Event: {:?}", event);
    }
}

let agent = Agent::builder()
    .bedrock(ClaudeSonnet4_5)
    .build()
    .await?;
let hook_id = agent.add_hook(Logger);

// Later, remove the hook
agent.remove_hook(hook_id);
Source

pub fn remove_hook(&self, id: HookId) -> bool

Remove a previously registered hook.

Returns true if the hook was found and removed, false otherwise.

Source

pub fn model_name(&self) -> &str

Get the model name for display

Source

pub async fn shutdown(&self)

Gracefully shutdown the agent, disconnecting MCP servers

Call this before dropping the agent to ensure clean subprocess termination.

Source

pub fn get_context_usage(&self) -> ContextUsage

Get current context usage information

Returns statistics about how much of the context window is being used, including the number of messages and estimated token count.

Source

pub fn last_context_info(&self) -> Option<ContextLoadResult>

Get information about the most recently loaded context files

Returns None if run() has not been called yet.

§Example
let response = agent.run("Hello").await?;

if let Some(ctx) = agent.last_context_info() {
    println!("Loaded {} context files ({} bytes)",
        ctx.files.len(), ctx.total_bytes);
    for file in &ctx.files {
        println!("  - {}", file.resolved_path.display());
    }
}

Auto Trait Implementations§

§

impl !Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl !UnwindSafe for Agent

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.