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

# Agent Loops

> Create autonomous AI workflows with tool access

Agent Loops are autonomous AI workflows that can execute multi-step tasks, access tools via MCP (Model Context Protocol) servers, and operate without direct user interaction.

<Frame caption="Agent loops overview">
  <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/01_agent_loops_list.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=889ee22ef0b7c9a587488da9f68b95ce" alt="Agent loops list" width="1920" height="941" data-path="images/screenshots/04-agentic/01_agent_loops_list.png" />
</Frame>

## Overview

An Agent Loop is an AI agent that:

* **Runs Autonomously**: Executes tasks without user messages
* **Uses Tools**: Accesses MCP servers for capabilities like file systems, databases, APIs
* **Makes Decisions**: Determines which tools to use and when
* **Sends Results**: Delivers output via callback webhooks
* **Iterates**: Can run multiple reasoning steps to complete tasks

Unlike bots (which respond to user messages), Agent Loops are proactive and task-oriented.

## Use Cases

<CardGroup cols={2}>
  <Card title="Scheduled Reports" icon="calendar">
    Generate and send daily/weekly reports automatically
  </Card>

  <Card title="Data Processing" icon="database">
    Process files, databases, or API data on schedule
  </Card>

  <Card title="Monitoring" icon="radar">
    Check systems and alert on issues
  </Card>

  <Card title="Content Generation" icon="file-pen">
    Create blog posts, summaries, or documentation
  </Card>
</CardGroup>

## Agent Loop Components

### System Prompt

Instructions that define the agent's behavior:

```
You are a data analyst. Every day at 9 AM, you:
1. Fetch yesterday's sales data from the database
2. Calculate key metrics (total sales, top products)
3. Generate a summary report
4. Send the report via webhook
```

<Frame caption="System prompt configuration">
  <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/05_system_prompt.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=4564b8396fc8a9848f8e0125d1f967b2" alt="System prompt" width="1920" height="941" data-path="images/screenshots/04-agentic/05_system_prompt.png" />
</Frame>

### User Message

The task or question given to the agent:

```
Generate today's sales report and send it to the team.
```

<Frame caption="User message input">
  <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/06_user_message.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=9633bf51dda8771c74475991c73e0d05" alt="User message" width="1920" height="941" data-path="images/screenshots/04-agentic/06_user_message.png" />
</Frame>

### MCP Servers

Tools the agent can use:

* **File System**: Read/write files
* **Database**: Query SQL databases
* **HTTP**: Make API requests
* **Custom**: Your own tool implementations

<Frame caption="MCP server configuration">
  <img src="https://mintcdn.com/chatbotplatform/mEifhYwIHJplQGSI/images/screenshots/04-agentic/07_mcp_server_configured.png?fit=max&auto=format&n=mEifhYwIHJplQGSI&q=85&s=4f9f3947017b1b84e61c389c06ab511f" alt="MCP server configured" width="1920" height="941" data-path="images/screenshots/04-agentic/07_mcp_server_configured.png" />
</Frame>

### Callback Webhook

Where to send results when the agent completes its task:

<Frame caption="Callback webhook setup">
  <img src="https://mintcdn.com/chatbotplatform/mEifhYwIHJplQGSI/images/screenshots/04-agentic/08_callback_configured.png?fit=max&auto=format&n=mEifhYwIHJplQGSI&q=85&s=8bd907880130d580f0c5b3baf5fde3d3" alt="Callback configured" width="1920" height="941" data-path="images/screenshots/04-agentic/08_callback_configured.png" />
</Frame>

## Creating an Agent Loop

<Steps>
  <Step title="Navigate to Agent Loops">
    From your dashboard, click **Agent Loops** in the sidebar.

    <Frame caption="Agent loops list">
      <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/01_agent_loops_list.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=889ee22ef0b7c9a587488da9f68b95ce" alt="Agent loops list" width="1920" height="941" data-path="images/screenshots/04-agentic/01_agent_loops_list.png" />
    </Frame>
  </Step>

  <Step title="Click Create">
    Click **Create Agent Loop** to open the form.

    <Frame caption="Create agent loop form">
      <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/03_create_agent_loop_form.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=a216a802be35c9cafd00000a9f080993" alt="Create form" width="1920" height="941" data-path="images/screenshots/04-agentic/03_create_agent_loop_form.png" />
    </Frame>
  </Step>

  <Step title="Name Your Agent">
    Give it a descriptive name:

    <Frame caption="Agent loop named">
      <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/04_agent_loop_named.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=47e422b4c94ae76db528703e54f0188f" alt="Named agent" width="1920" height="941" data-path="images/screenshots/04-agentic/04_agent_loop_named.png" />
    </Frame>
  </Step>

  <Step title="Write System Prompt">
    Define the agent's role and behavior.
  </Step>

  <Step title="Set User Message">
    Provide the task or question.
  </Step>

  <Step title="Configure MCP Servers">
    Add any tools the agent needs (optional but recommended).
  </Step>

  <Step title="Add Callback Webhook">
    Specify where to send results (optional).
  </Step>

  <Step title="Configure Advanced Settings">
    Set model, max iterations, timeout, etc.

    <Frame caption="Advanced settings">
      <img src="https://mintcdn.com/chatbotplatform/mEifhYwIHJplQGSI/images/screenshots/04-agentic/09_advanced_settings.png?fit=max&auto=format&n=mEifhYwIHJplQGSI&q=85&s=8f09968be16ce840ba1b856d30531a26" alt="Advanced settings" width="1920" height="941" data-path="images/screenshots/04-agentic/09_advanced_settings.png" />
    </Frame>
  </Step>

  <Step title="Save">
    Click **Create** to save the agent loop.

    <Frame caption="Complete agent loop">
      <img src="https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/10_agent_loop_complete.png?fit=max&auto=format&n=QhGUbEN05MzAjt2K&q=85&s=3cfd56725f35009b045c00560c3f38ba" alt="Complete agent" width="1920" height="941" data-path="images/screenshots/04-agentic/10_agent_loop_complete.png" />
    </Frame>
  </Step>
</Steps>

## Running Agent Loops

### Manual Execution

Run an agent loop on demand:

<Steps>
  <Step title="Open Agent Loop">
    Navigate to the agent loop details page.
  </Step>

  <Step title="Click Run">
    Click the **Run** button to start execution.
  </Step>

  <Step title="Monitor Progress">
    Watch the execution log for status updates.
  </Step>

  <Step title="Review Results">
    Check the output and any callback webhook responses.
  </Step>
</Steps>

### Scheduled Execution (Coming Soon)

Future support for:

* Cron-based schedules (daily, weekly, monthly)
* Interval-based triggers (every N minutes/hours)
* Event-based triggers (webhook received, file uploaded)

### API Execution

Trigger agent loops via API:

```bash theme={null}
curl -X POST https://api.chatbotplatform.io/v1/agent-loops/{id}/run \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"
```

See [API Reference](/api-reference/introduction) for details.

## MCP Servers

Model Context Protocol (MCP) servers provide tools for agents:

### Built-in MCP Servers

**File System**:

* Read files
* Write files
* List directories

**HTTP Client**:

* Make GET/POST/PUT/DELETE requests
* Handle authentication
* Parse responses

**Database** (Coming Soon):

* Query SQL databases
* Execute statements
* Transaction support

### Custom MCP Servers

Deploy your own MCP servers:

<Steps>
  <Step title="Implement MCP Protocol">
    Follow the MCP specification to create a tool server.
  </Step>

  <Step title="Deploy Server">
    Host your MCP server at a public endpoint.
  </Step>

  <Step title="Add to Agent Loop">
    Configure the MCP server URL in your agent loop settings.
  </Step>

  <Step title="Test">
    Run the agent and verify tool calls work correctly.
  </Step>
</Steps>

Learn more in [MCP Servers](/agent-loops/mcp-servers).

## Callback Webhooks

Send agent results to external systems:

### Webhook Format

The callback webhook receives:

```json theme={null}
{
  "agent_loop_id": "loop_abc123",
  "execution_id": "exec_xyz789",
  "status": "completed",
  "result": {
    "output": "The agent's final response",
    "tool_calls": 5,
    "iterations": 3
  },
  "metadata": {
    "started_at": "2024-01-15T10:00:00Z",
    "completed_at": "2024-01-15T10:02:30Z",
    "duration_seconds": 150
  }
}
```

### Response Expected

Your webhook should return:

```json theme={null}
{
  "received": true
}
```

HTTP 200 status indicates success.

Learn more in [Callbacks](/agent-loops/callbacks).

## Advanced Settings

### Max Iterations

Limit how many reasoning steps the agent can take:

| Iterations   | Use Case                 |
| ------------ | ------------------------ |
| 5            | Simple tasks             |
| 10 (default) | Standard tasks           |
| 20           | Complex multi-step tasks |
| 50+          | Very complex workflows   |

More iterations = longer execution time.

### Timeout

Maximum execution time in seconds:

* 60s: Quick tasks
* 300s (5 min): Standard
* 900s (15 min): Long-running tasks
* 3600s (1 hour): Maximum

Agent stops if timeout is reached.

## Best Practices

<CardGroup cols={2}>
  <Card title="Clear Instructions" icon="memo">
    Write explicit system prompts and tasks
  </Card>

  <Card title="Right Tools" icon="wrench">
    Provide only necessary MCP servers
  </Card>

  <Card title="Set Limits" icon="gauge">
    Use appropriate iteration and timeout limits
  </Card>

  <Card title="Test First" icon="vial">
    Run manually before scheduling
  </Card>
</CardGroup>

### System Prompt Tips

**Good**:

```
You are a sales analyst. Your task is to:
1. Query the database for yesterday's orders
2. Calculate total revenue and average order value
3. Identify top 5 products by sales
4. Format the results as a JSON report
5. Send the report via the callback webhook
```

**Bad**:

```
Analyze sales data.
```

Be specific about steps, data sources, and expected output.

## Troubleshooting

### Agent Doesn't Complete

**Check**:

* Max iterations is sufficient
* Timeout is long enough
* MCP servers are accessible
* System prompt is clear

### Tool Calls Fail

**Check**:

* MCP server URLs are correct
* Authentication is configured
* Server is running and responsive
* Agent has permission to access tools

### No Callback Received

**Check**:

* Callback URL is correct
* Webhook endpoint is accessible
* Agent loop completed successfully
* Check execution logs for errors

## API Access

Manage agent loops programmatically using the API.

<AccordionGroup>
  <Accordion title="Create an agent loop via API">
    <Tabs>
      <Tab title="cURL">
        ```bash theme={null}
        curl -X POST https://api.chatbotplatform.io/v1/agent-loops \
          -H "Authorization: Bearer YOUR_API_KEY" \
          -H "Content-Type: application/json" \
          -d '{
            "name": "Daily Sales Report",
            "system_prompt": "You generate daily sales reports.",
            "user_message": "Generate today\u0027s sales report.",
            "mcp_servers": ["filesystem", "http"],
            "callback_url": "https://your-app.com/webhook",
            "max_iterations": 10,
            "timeout": 300
          }'
        ```
      </Tab>

      <Tab title="JavaScript">
        ```javascript theme={null}
        const response = await fetch('https://api.chatbotplatform.io/v1/agent-loops', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: 'Daily Sales Report',
            system_prompt: 'You generate daily sales reports.',
            user_message: 'Generate today\'s sales report.',
            mcp_servers: ['filesystem', 'http'],
            callback_url: 'https://your-app.com/webhook',
            max_iterations: 10,
            timeout: 300
          })
        });
        const data = await response.json();
        ```
      </Tab>

      <Tab title="PHP">
        ```php theme={null}
        $response = Http::withToken('YOUR_API_KEY')
            ->post('https://api.chatbotplatform.io/v1/agent-loops', [
                'name' => 'Daily Sales Report',
                'system_prompt' => 'You generate daily sales reports.',
                'user_message' => 'Generate today\'s sales report.',
                'mcp_servers' => ['filesystem', 'http'],
                'callback_url' => 'https://your-app.com/webhook',
                'max_iterations' => 10,
                'timeout' => 300
            ]);

        $agentLoop = $response->json();
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        response = requests.post(
            'https://api.chatbotplatform.io/v1/agent-loops',
            headers={'Authorization': 'Bearer YOUR_API_KEY'},
            json={
                'name': 'Daily Sales Report',
                'system_prompt': 'You generate daily sales reports.',
                'user_message': 'Generate today\'s sales report.',
                'mcp_servers': ['filesystem', 'http'],
                'callback_url': 'https://your-app.com/webhook',
                'max_iterations': 10,
                'timeout': 300
            }
        )
        agent_loop = response.json()
        ```
      </Tab>
    </Tabs>
  </Accordion>

  <Accordion title="Run an agent loop">
    <Tabs>
      <Tab title="cURL">
        ```bash theme={null}
        curl -X POST https://api.chatbotplatform.io/v1/agent-loops/loop_123/run \
          -H "Authorization: Bearer YOUR_API_KEY"
        ```
      </Tab>

      <Tab title="JavaScript">
        ```javascript theme={null}
        const response = await fetch('https://api.chatbotplatform.io/v1/agent-loops/loop_123/run', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY'
          }
        });
        const execution = await response.json();
        ```
      </Tab>

      <Tab title="PHP">
        ```php theme={null}
        $response = Http::withToken('YOUR_API_KEY')
            ->post('https://api.chatbotplatform.io/v1/agent-loops/loop_123/run');

        $execution = $response->json();
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        response = requests.post(
            'https://api.chatbotplatform.io/v1/agent-loops/loop_123/run',
            headers={'Authorization': 'Bearer YOUR_API_KEY'}
        )
        execution = response.json()
        ```
      </Tab>
    </Tabs>
  </Accordion>

  <Accordion title="List agent loop executions">
    <Tabs>
      <Tab title="cURL">
        ```bash theme={null}
        curl https://api.chatbotplatform.io/v1/agent-loops/loop_123/executions \
          -H "Authorization: Bearer YOUR_API_KEY"
        ```
      </Tab>

      <Tab title="JavaScript">
        ```javascript theme={null}
        const response = await fetch('https://api.chatbotplatform.io/v1/agent-loops/loop_123/executions', {
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY'
          }
        });
        const { data } = await response.json();
        ```
      </Tab>

      <Tab title="PHP">
        ```php theme={null}
        $response = Http::withToken('YOUR_API_KEY')
            ->get('https://api.chatbotplatform.io/v1/agent-loops/loop_123/executions');

        $executions = $response->json('data');
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        response = requests.get(
            'https://api.chatbotplatform.io/v1/agent-loops/loop_123/executions',
            headers={'Authorization': 'Bearer YOUR_API_KEY'}
        )
        executions = response.json()['data']
        ```
      </Tab>
    </Tabs>
  </Accordion>
</AccordionGroup>

<Card title="Complete API Reference" icon="code" href="https://app.chatbotplatform.io/openapi">
  View the full API specification with all endpoints, parameters, and response schemas.
</Card>

## Next Steps

<CardGroup cols={2}>
  <Card title="Getting Started" icon="rocket" href="/agent-loops/getting-started">
    Create your first agent loop
  </Card>

  <Card title="MCP Servers" icon="server" href="/agent-loops/mcp-servers">
    Configure tool access
  </Card>

  <Card title="Callbacks" icon="webhook" href="/agent-loops/callbacks">
    Set up result webhooks
  </Card>
</CardGroup>
