> ## Documentation Index
> Fetch the complete documentation index at: https://www.minitap.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent

> The central orchestrator for mobile automation

The `Agent` class is the primary entry point for the SDK. It coordinates all components required for mobile automation.

## Responsibilities

<CardGroup cols={2}>
  <Card title="Device Management" icon="mobile">
    Initializes and manages connections to Android/iOS devices
  </Card>

  <Card title="Server Lifecycle" icon="server">
    Starts and stops the Device Controller server
  </Card>

  <Card title="Task Execution" icon="play">
    Creates and executes automation tasks
  </Card>

  <Card title="Resource Cleanup" icon="trash">
    Handles proper cleanup and resource release
  </Card>
</CardGroup>

## Basic Usage

### Creating an Agent

<Tabs>
  <Tab title="Platform (Recommended)">
    With the platform, simply create an agent - no configuration needed:

    ```python theme={null}
    from minitap.mobile_use.sdk import Agent

    # Create agent (uses MINITAP_API_KEY from environment)
    agent = Agent()
    ```

    All profiles and task configurations are managed on [platform.mobile-use.ai](https://platform.mobile-use.ai).
  </Tab>

  <Tab title="Local Development">
    For local development, configure the agent with profiles:

    ```python theme={null}
    from minitap.mobile_use.sdk import Agent
    from minitap.mobile_use.sdk.builders import Builders
    from minitap.mobile_use.sdk.types import AgentProfile

    # Create profile from config file
    profile = AgentProfile(name="default", from_file="llm-config.defaults.jsonc")

    # Configure agent
    config = Builders.AgentConfig.with_default_profile(profile).build()
    agent = Agent(config=config)
    ```
  </Tab>
</Tabs>

### Agent Lifecycle

<Steps>
  <Step title="Creation">
    Instantiate the agent with optional configuration

    ```python theme={null}
    agent = Agent()
    ```
  </Step>

  <Step title="Initialization">
    Connect to device and start servers

    ```python theme={null}
    agent.init()
    ```
  </Step>

  <Step title="Execution">
    Run automation tasks

    ```python theme={null}
    result = await agent.run_task(goal="Your task here")
    ```
  </Step>

  <Step title="Cleanup">
    Release resources

    ```python theme={null}
    agent.clean()
    ```
  </Step>
</Steps>

## Configuration Options

The agent can be configured using the `AgentConfigBuilder`:

```python theme={null}
from minitap.mobile_use.sdk.builders import Builders
from minitap.mobile_use.sdk.types import AgentProfile, DevicePlatform

# Create profiles
default_profile = AgentProfile(name="default", from_file="llm-config.defaults.jsonc")

# Configure the agent
config = (
    Builders.AgentConfig
    .with_default_profile(default_profile)
    .for_device(platform=DevicePlatform.ANDROID, device_id="emulator-5554")
    .build()
)

agent = Agent(config=config)
```

## Initialization Options

The `init()` method accepts several parameters for robust initialization:

```python theme={null}
agent.init(
    server_restart_attempts=3,  # Retry server startup if it fails
    retry_count=5,              # Number of API call retries
    retry_wait_seconds=5        # Seconds between retries
)
```

<Tip>
  If you have zombie servers from previous runs, use `agent.clean(force=True)` before initializing.
</Tip>

## Device Selection

By default, the agent connects to the first available device. You can specify a device explicitly:

```python theme={null}
from minitap.mobile_use.sdk.types import DevicePlatform

config = (
    Builders.AgentConfig
    .for_device(
        platform=DevicePlatform.ANDROID,
        device_id="your_device_id"
    )
    .build()
)
```

## Server Configuration

The agent manages the Device Controller server which handles all device interactions:

<Accordion title="Device Controller Server">
  Executes device actions and captures screen state using native platform tools:

  * **Android**: Uses ADB (Android Debug Bridge) with UIAutomator2 for UI automation
  * **iOS**: Uses IDB (iOS Development Bridge) for simulator and device control

  Capabilities include:

  * Screenshots and UI hierarchy capture
  * Tap, swipe, scroll gestures
  * App launching and navigation
  * Key press events and text input
</Accordion>

## Complete Example

<Tabs>
  <Tab title="Platform">
    ```python theme={null}
    import asyncio
    from minitap.mobile_use.sdk import Agent
    from minitap.mobile_use.sdk.types import PlatformTaskRequest

    async def main():
        # Create agent (uses MINITAP_API_KEY from .env)
        agent = Agent()
        
        try:
            # Initialize
            if not agent.init():
                print("Failed to initialize agent")
                return
            
            # Run platform task (configured on platform.mobile-use.ai)
            result = await agent.run_task(
                request=PlatformTaskRequest(task="check-notifications")
            )
            print(f"Result: {result}")
            
        except Exception as e:
            print(f"Error: {e}")
        finally:
            # Always clean up
            agent.clean()

    if __name__ == "__main__":
        asyncio.run(main())
    ```
  </Tab>

  <Tab title="Local">
    ```python theme={null}
    import asyncio
    from minitap.mobile_use.sdk import Agent
    from minitap.mobile_use.sdk.types import AgentProfile
    from minitap.mobile_use.sdk.builders import Builders

    async def main():
        # Configure agent with local profile
        profile = AgentProfile(name="default", from_file="llm-config.defaults.jsonc")
        config = Builders.AgentConfig.with_default_profile(profile).build()
        agent = Agent(config=config)
        
        try:
            # Initialize
            if not agent.init():
                print("Failed to initialize agent")
                return
            
            # Run local task
            result = await agent.run_task(
                goal="Check my notifications",
                name="check_notifications"
            )
            print(f"Result: {result}")
            
        except Exception as e:
            print(f"Error: {e}")
        finally:
            # Always clean up
            agent.clean()

    if __name__ == "__main__":
        asyncio.run(main())
    ```
  </Tab>
</Tabs>

## Best Practices

<AccordionGroup>
  <Accordion title="Always use try-finally" icon="shield">
    Ensure `agent.clean()` is called even if errors occur

    ```python theme={null}
    try:
        agent.init()
        await agent.run_task(...)
    finally:
        agent.clean()
    ```
  </Accordion>

  <Accordion title="Handle initialization failures" icon="triangle-exclamation">
    Check the return value of `init()`

    ```python theme={null}
    if not agent.init():
        print("Failed to initialize")
        return
    ```
  </Accordion>

  <Accordion title="Use context managers" icon="brackets-curly">
    Consider wrapping in a context manager for automatic cleanup
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Tasks" icon="list-check" href="/docs/mobile-use-sdk/core-concepts/tasks">
    Learn about task creation and execution
  </Card>

  <Card title="SDK Reference" icon="file-code" href="/docs/mobile-use-sdk/sdk-reference/agent">
    Detailed Agent SDK documentation
  </Card>
</CardGroup>
