> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/block/goose/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent

> Core Agent implementation for the Goose AI framework

The `Agent` is the main orchestrator in Goose that manages conversations, extensions, tools, and provider interactions.

## Overview

The Agent is responsible for:

* Managing conversation flow and message handling
* Coordinating tool execution (both platform and extension tools)
* Managing extensions (MCP servers, frontend tools)
* Handling permission checks and confirmations
* Processing retry logic and error recovery
* Auto-compaction of conversation history

## Struct Definition

```rust theme={null}
pub struct Agent {
    pub provider: SharedProvider,
    pub config: AgentConfig,
    pub extension_manager: Arc<ExtensionManager>,
    // ... internal fields
}
```

**Source:** `crates/goose/src/agents/agent.rs:136-153`

## Configuration

### AgentConfig

Configuration for Agent initialization.

```rust theme={null}
pub struct AgentConfig {
    pub session_manager: Arc<SessionManager>,
    pub permission_manager: Arc<PermissionManager>,
    pub scheduler_service: Option<Arc<dyn SchedulerTrait>>,
    pub goose_mode: GooseMode,
    pub disable_session_naming: bool,
    pub goose_platform: GoosePlatform,
}
```

**Source:** `crates/goose/src/agents/agent.rs:106-113`

<ParamField path="session_manager" type="Arc<SessionManager>" required>
  Manages session persistence and retrieval
</ParamField>

<ParamField path="permission_manager" type="Arc<PermissionManager>" required>
  Handles permission policies for tool execution
</ParamField>

<ParamField path="scheduler_service" type="Option<Arc<dyn SchedulerTrait>>">
  Optional scheduler for recurring tasks
</ParamField>

<ParamField path="goose_mode" type="GooseMode" required>
  Operating mode: `Auto`, `Chat`, or `Agentic`
</ParamField>

<ParamField path="disable_session_naming" type="bool" required>
  Whether to disable automatic session naming
</ParamField>

<ParamField path="goose_platform" type="GoosePlatform" required>
  Platform type: `GooseCli` or `GooseDesktop`
</ParamField>

### GoosePlatform

```rust theme={null}
pub enum GoosePlatform {
    GooseDesktop,
    GooseCli,
}
```

**Source:** `crates/goose/src/agents/agent.rs:91-94`

## Constructor Methods

### new()

Create a new Agent with default configuration.

```rust theme={null}
impl Agent {
    pub fn new() -> Self
}
```

**Returns:** Agent instance with default settings

**Source:** `crates/goose/src/agents/agent.rs:205-216`

**Example:**

```rust theme={null}
let agent = Agent::new();
```

### with\_config()

Create an Agent with custom configuration.

```rust theme={null}
pub fn with_config(config: AgentConfig) -> Self
```

<ParamField path="config" type="AgentConfig" required>
  Custom agent configuration
</ParamField>

**Returns:** Configured Agent instance

**Source:** `crates/goose/src/agents/agent.rs:218-252`

**Example:**

```rust theme={null}
let config = AgentConfig::new(
    session_manager,
    permission_manager,
    None,
    GooseMode::Auto,
    false,
    GoosePlatform::GooseCli,
);
let agent = Agent::with_config(config);
```

## Core Methods

### reply()

Process a user message and generate a streaming response.

```rust theme={null}
pub async fn reply(
    &self,
    user_message: Message,
    session_config: SessionConfig,
    cancel_token: Option<CancellationToken>,
) -> Result<BoxStream<'_, Result<AgentEvent>>>
```

<ParamField path="user_message" type="Message" required>
  The user's input message
</ParamField>

<ParamField path="session_config" type="SessionConfig" required>
  Session configuration including ID and settings
</ParamField>

<ParamField path="cancel_token" type="Option<CancellationToken>">
  Token to cancel the operation
</ParamField>

**Returns:** Stream of `AgentEvent` including messages, tool calls, and system notifications

**Source:** `crates/goose/src/agents/agent.rs:871-1078`

**Example:**

```rust theme={null}
let message = Message::user().with_text("Run tests in the project");
let mut stream = agent.reply(message, session_config, None).await?;

while let Some(event) = stream.next().await {
    match event? {
        AgentEvent::Message(msg) => println!("Message: {:?}", msg),
        AgentEvent::ModelChange { model, mode } => {
            println!("Model changed to {} in {} mode", model, mode)
        }
        _ => {}
    }
}
```

### provider()

Get the current LLM provider.

```rust theme={null}
pub async fn provider(&self) -> Result<Arc<dyn Provider>, anyhow::Error>
```

**Returns:** Arc reference to the active provider

**Source:** `crates/goose/src/agents/agent.rs:447-452`

## Extension Management

### add\_extension()

Add a new extension to the agent.

```rust theme={null}
pub async fn add_extension(
    &self,
    extension: ExtensionConfig,
    session_id: &str,
) -> ExtensionResult<()>
```

<ParamField path="extension" type="ExtensionConfig" required>
  Configuration for the extension (MCP, STDIO, or Frontend)
</ParamField>

<ParamField path="session_id" type="&str" required>
  Session ID to associate the extension with
</ParamField>

**Source:** `crates/goose/src/agents/agent.rs:715-734`

**Example:**

```rust theme={null}
let extension = ExtensionConfig::Mcp {
    name: "filesystem".to_string(),
    url: "http://localhost:3000".to_string(),
    env: None,
};
agent.add_extension(extension, "session_123").await?;
```

### remove\_extension()

Remove an extension from the agent.

```rust theme={null}
pub async fn remove_extension(&self, name: &str, session_id: &str) -> Result<()>
```

<ParamField path="name" type="&str" required>
  Name of the extension to remove
</ParamField>

<ParamField path="session_id" type="&str" required>
  Associated session ID
</ParamField>

**Source:** `crates/goose/src/agents/agent.rs:818-830`

### list\_extensions()

Get all active extensions.

```rust theme={null}
pub async fn list_extensions(&self) -> Vec<String>
```

**Returns:** Vector of extension names

**Source:** `crates/goose/src/agents/agent.rs:832-837`

### list\_tools()

Get all available tools for a session.

```rust theme={null}
pub async fn list_tools(&self, session_id: &str, extension_name: Option<String>) -> Vec<Tool>
```

<ParamField path="session_id" type="&str" required>
  Session ID
</ParamField>

<ParamField path="extension_name" type="Option<String>">
  Optional filter for specific extension
</ParamField>

**Returns:** Vector of available MCP tools

**Source:** `crates/goose/src/agents/agent.rs:796-816`

## Tool Execution

### dispatch\_tool\_call()

Execute a single tool call.

```rust theme={null}
pub async fn dispatch_tool_call(
    &self,
    tool_call: CallToolRequestParams,
    request_id: String,
    cancellation_token: Option<CancellationToken>,
    session: &Session,
) -> (String, Result<ToolCallResult, ErrorData>)
```

<ParamField path="tool_call" type="CallToolRequestParams" required>
  Tool call parameters (name, arguments)
</ParamField>

<ParamField path="request_id" type="String" required>
  Unique request identifier
</ParamField>

<ParamField path="cancellation_token" type="Option<CancellationToken>">
  Token to cancel the operation
</ParamField>

<ParamField path="session" type="&Session" required>
  Current session context
</ParamField>

**Returns:** Tuple of (request\_id, result)

**Source:** `crates/goose/src/agents/agent.rs:495-587`

## Permission Handling

### handle\_confirmation()

Handle user confirmation for a tool execution.

```rust theme={null}
pub async fn handle_confirmation(
    &self,
    request_id: String,
    confirmation: PermissionConfirmation,
)
```

<ParamField path="request_id" type="String" required>
  The tool request ID awaiting confirmation
</ParamField>

<ParamField path="confirmation" type="PermissionConfirmation" required>
  User's permission decision
</ParamField>

**Source:** `crates/goose/src/agents/agent.rs:843-862`

## Events

### AgentEvent

Events emitted during agent execution.

```rust theme={null}
pub enum AgentEvent {
    Message(Message),
    McpNotification((String, ServerNotification)),
    ModelChange { model: String, mode: String },
    HistoryReplaced(Conversation),
}
```

**Source:** `crates/goose/src/agents/agent.rs:156-161`

<ResponseField name="Message" type="Message">
  A conversation message (user, assistant, tool results)
</ResponseField>

<ResponseField name="McpNotification" type="(String, ServerNotification)">
  Notification from an MCP server
</ResponseField>

<ResponseField name="ModelChange" type="{ model: String, mode: String }">
  The active model changed (for lead-worker providers)
</ResponseField>

<ResponseField name="HistoryReplaced" type="Conversation">
  Conversation history was replaced (e.g., after compaction)
</ResponseField>

## Session State Management

### save\_extension\_state()

Persist extension state to session metadata.

```rust theme={null}
pub async fn save_extension_state(&self, session: &SessionConfig) -> Result<()>
```

<ParamField path="session" type="&SessionConfig" required>
  Session configuration
</ParamField>

**Source:** `crates/goose/src/agents/agent.rs:591-611`

### load\_extensions\_from\_session()

Restore extensions from session metadata.

```rust theme={null}
pub async fn load_extensions_from_session(
    self: &Arc<Self>,
    session: &Session,
) -> Vec<ExtensionLoadResult>
```

<ParamField path="session" type="&Session" required>
  Session containing extension metadata
</ParamField>

**Returns:** Vector of load results indicating success/failure per extension

**Source:** `crates/goose/src/agents/agent.rs:638-713`

## Related Types

* [Session](/api/core/session) - Session management
* [Conversation](/api/core/conversation) - Message history
* [Config](/api/core/config) - Configuration system
