> ## 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.

# Building a Grounded Support Bot

> Add agentic loops and MCP servers for responses grounded in real data

Take your support bot to the next level by adding Agentic Loops that can search your knowledge base, look up orders, check inventory, and provide responses grounded in real data. This intermediate guide builds on the basic support bot with tool-calling capabilities.

## What You'll Learn

By the end of this guide, you'll be able to:

* Understand how Agentic Loops enhance bot responses
* Connect MCP servers to provide tools for your bot
* Ground AI responses in real-time data
* Handle complex support queries that require data lookups
* Combine multiple tools for sophisticated workflows

## Prerequisites

Before starting, you should have:

* Completed the [Basic Support Bot](https://docs.chatbotplatform.io/guides/support-bot-basics.md) guide
* A working bot connected to at least one channel
* Basic understanding of APIs and webhooks
* Access to data sources you want the bot to query (optional)

## Understanding Agentic Loops

Regular bots send messages to an AI integration and return the response. This works well for general questions, but falls short when you need to:

* Search a knowledge base for specific information
* Look up order status in a database
* Check real-time inventory levels
* Fetch current weather or other external data
* Perform calculations or data transformations

**Agentic Loops** solve this by giving your AI access to tools (MCP servers) that can interact with external systems. The AI can decide when to use these tools, call them automatically, and incorporate the results into its response.

### How It Works

```
User: "What's the status of order #12345?"

1. Bot receives message → Integration processes → Identifies need for order lookup
2. Integration calls Agentic Loop with user message
3. Agentic Loop runs with access to MCP servers:
   - AI identifies it needs to look up order data
   - Calls HTTP MCP server to query order API
   - Receives order status data
   - Formats response with actual order information
4. Response sent back through bot to user

User receives: "Order #12345 was shipped on Jan 15 via USPS.
Tracking: 9400123456789. Estimated delivery: Jan 18."
```

## Step 1: Create an Agentic Loop

**1. Navigate to Agentic Loops**

From your dashboard, click **Agentic Loops** in the sidebar.

**2. Create New Loop**

Click **Create Agentic Loop**.

![Agentic loops list](https://mintlify.s3.us-west-1.amazonaws.com/chatbotplatform/images/screenshots/04-agentic/01_loops_index.png)

Agentic Loops dashboard

**3. Configure the Loop**

Enter the following details:

* **Name**: "Support Bot Knowledge Search"
* **Description**: "Searches knowledge base for accurate support answers"
* **Max Iterations**: 10 (allow up to 10 reasoning steps)

![Create loop form](https://mintlify.s3.us-west-1.amazonaws.com/chatbotplatform/images/screenshots/04-agentic/02_create_loop_form.png)

Create agentic loop form

**4. Write System Prompt**

Define the agent's role and available tools:

```
You are a customer support assistant with access to tools
to search the knowledge base and look up real-time data.

When a customer asks a question:
1. Determine if you need to search for information
2. Use the http tool to search the knowledge base API
3. Use the search results to provide an accurate answer
4. Cite sources when possible

Guidelines:
- Always search the knowledge base before answering
- If the knowledge base doesn't have the answer, say so
- Never make up information
- Keep responses concise and helpful
```

**5. Add Initial User Message**

This message starts the loop. You can leave it blank if the bot will provide the message dynamically:

```
{{user_message}}
```

This placeholder will be replaced with the actual user question when triggered from your bot.

**6. Save the Loop**

Click **Create** to save your agentic loop.

## Step 2: Add MCP Servers

MCP servers provide tools that your agentic loop can use. Let's add servers for common support scenarios.

**1. Add HTTP Client Server**

The HTTP Client MCP server allows the agent to make API calls.

1. In your agentic loop, go to the **MCP Servers** tab
2. Click **Add MCP Server**
3. Select **HTTP Client**
4. Configure access:
   * **Allow all domains**: Enable if your APIs are on different domains
   * **Allowed domains**: Or specify specific domains (e.g., `api.yourcompany.com`)
5. Click **Add**

![MCP server setup](https://mintlify.s3.us-west-1.amazonaws.com/chatbotplatform/images/screenshots/04-agentic/03_mcp_server_config.png)

MCP server configuration

**2. Add Time Server (Optional)**

If your bot needs to know the current time for date-based queries:

1. Click **Add MCP Server**
2. Select **Time**
3. Set timezone: `America/New_York` (or your timezone)
4. Click **Add**

**3. Add Google Maps Server (Optional)**

For location-based support (store locator, service areas):

1. Click **Add MCP Server**
2. Select **Google Maps**
3. Enter your Google Maps API key
4. Click **Add**

The agent will automatically see available tools from all connected MCP servers and decide when to use them based on the user's question.

## Step 3: Connect Loop to Your Bot

Now we need to modify your bot's integration to use the agentic loop.

### Option A: Update Existing Integration

Modify your webhook integration to call the agentic loop:

```javascript theme={null}
// Your integration endpoint
app.post('/support-bot', async (req, res) => {
  const { messages, conversation_id, user } = req.body;
  const userMessage = messages[messages.length - 1].content;

  // Call Chatbot Platform Agentic Loop API
  const loopResponse = await fetch(
    'https://api.chatbotplatform.io/v1/agentic-loops/loop_123/execute',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user_message: userMessage,
        conversation_id: conversation_id
      })
    }
  );

  const result = await loopResponse.json();

  // Return the agent's response
  res.json({
    content: result.final_response,
    metadata: {
      iterations_used: result.iterations,
      tools_called: result.tools_used
    }
  });
});
```

### Option B: Use Agentic Loop Directly

Set the agentic loop as your bot's integration:

**1. Get Loop Webhook URL**

Copy the webhook URL from your agentic loop settings:

```
https://api.chatbotplatform.io/v1/agentic-loops/loop_123/webhook
```

**2. Create New Integration**

In your bot's Integrations tab:

* **Name**: "Agentic Support Loop"
* **Webhook URL**: Paste the loop webhook URL
* **Headers**: Add authentication

```
Authorization: Bearer YOUR_API_KEY
```

**3. Set as Primary**

Set this integration's weight to 100 to use it for all messages.

## Step 4: Create Knowledge Base Search

To search your knowledge base, you'll need an API endpoint that the agent can call.

### Example: Search API

```javascript theme={null}
// Your knowledge base search API
app.post('/api/search-knowledge-base', async (req, res) => {
  const { query } = req.body;

  // Search your documentation
  const results = await searchDocs(query);

  // Return relevant articles
  res.json({
    results: results.map(doc => ({
      title: doc.title,
      url: doc.url,
      excerpt: doc.excerpt,
      relevance: doc.score
    }))
  });
});
```

### Update System Prompt

Tell the agent how to use this API:

```
You have access to a knowledge base search tool via HTTP.

To search the knowledge base:
1. Use the http tool to POST to https://api.yourcompany.com/search-knowledge-base
2. Send body: {"query": "user's question"}
3. You'll receive relevant articles with titles, URLs, and excerpts

Example workflow:
User: "How do I reset my password?"

Step 1: Search knowledge base
POST https://api.yourcompany.com/search-knowledge-base
Body: {"query": "reset password"}

Step 2: Get results like:
[{
  "title": "Password Reset Guide",
  "url": "https://help.yourcompany.com/password-reset",
  "excerpt": "To reset your password, click 'Forgot Password'..."
}]

Step 3: Provide answer based on results:
"To reset your password, click the 'Forgot Password' link on the login
page. You can find detailed instructions here: [Password Reset Guide]
(https://help.yourcompany.com/password-reset)"
```

## Step 5: Test the Grounded Bot

**1. Send a Knowledge Base Question**

Ask something that requires searching your documentation:

```
User: How do I update my billing information?
```

**2. Observe the Agent Working**

The agentic loop will:

1. Receive the question
2. Decide it needs to search the knowledge base
3. Call the HTTP tool to search
4. Receive search results
5. Format a response with accurate information
6. Return the answer to the user

**3. Check the Logs**

View the loop execution logs to see:

* Number of iterations used
* Which tools were called
* API responses received
* Agent's reasoning process

![Execution logs](https://mintlify.s3.us-west-1.amazonaws.com/chatbotplatform/images/screenshots/04-agentic/04_loop_logs.png)

Loop execution logs

**4. Verify Accuracy**

Confirm the response includes:

* Accurate information from your knowledge base
* Links to relevant documentation
* No hallucinated or made-up information

## Advanced Patterns

### Pattern 1: Multi-Step Order Lookup

Handle complex queries that require multiple API calls:

```
User: "I ordered a blue shirt last week. Has it shipped?"

Agent workflow:
1. Extract: product="blue shirt", timeframe="last week"
2. Call API: GET /api/orders?user_id=123&product_type=shirt&color=blue
3. Filter results by date (last 7 days)
4. For matching order, call: GET /api/orders/{id}/shipping
5. Format response with order number, status, and tracking
```

### Pattern 2: Inventory Check

Check product availability before answering:

```
User: "Do you have the XL red hoodie in stock?"

Agent workflow:
1. Parse: size="XL", color="red", product="hoodie"
2. Call API: GET /api/inventory?sku=hoodie-red-xl
3. Check quantity > 0
4. Respond with availability and estimated delivery
```

### Pattern 3: Context-Aware Support

Use conversation history to provide better answers:

```
User: "I bought a laptop last month"
Bot: "Great! How can I help with your laptop?"

User: "It won't turn on"
Bot: *Searches knowledge base for "laptop won't turn on"*
    *Finds troubleshooting guide*
    "Let's troubleshoot this. First, please try these steps:
    1. Check if the charging cable is connected
    2. Hold the power button for 10 seconds..."
```

## API Examples

> [accordion] Execute an agentic loop
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/agentic-loops/loop_123/execute \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "user_message": "What is the status of order #12345?",
> >     "conversation_id": "conv_456"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch(
> >   'https://api.chatbotplatform.io/v1/agentic-loops/loop_123/execute',
> >   {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       user_message: 'What is the status of order #12345?',
> >       conversation_id: 'conv_456'
> >     })
> >   }
> > );
> >
> > const result = await response.json();
> > console.log('Response:', result.final_response);
> > console.log('Iterations:', result.iterations);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/agentic-loops/loop_123/execute', [
> >         'user_message' => 'What is the status of order #12345?',
> >         'conversation_id' => 'conv_456'
> >     ]);
> >
> > $result = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.post(
> >     'https://api.chatbotplatform.io/v1/agentic-loops/loop_123/execute',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'user_message': 'What is the status of order #12345?',
> >         'conversation_id': 'conv_456'
> >     }
> > )
> >
> > result = response.json()
> > print('Response:', result['final_response'])
> > ```

> [accordion] Get loop execution history
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/agentic-loops/loop_123/executions \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch(
> >   'https://api.chatbotplatform.io/v1/agentic-loops/loop_123/executions',
> >   {
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY'
> >     }
> >   }
> > );
> >
> > const executions = await response.json();
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $executions = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/agentic-loops/loop_123/executions')
> >     ->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/agentic-loops/loop_123/executions',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > executions = response.json()
> > ```

For complete API documentation, see the [OpenAPI specification](https://app.chatbotplatform.io/openapi).

## Best Practices

> [card] Clear Tool Instructions
>
> Document exactly how to use each tool in the system prompt

> [card] Error Handling
>
> Tell the agent what to do when API calls fail

> [card] Limit Iterations
>
> Set appropriate max iterations to prevent infinite loops

> [card] Monitor Usage
>
> Track which tools are used most often and optimize

### System Prompt Tips

**Be Explicit About APIs:**

```
To search orders:
POST https://api.yourcompany.com/orders/search
Headers: {"Authorization": "Bearer {{API_KEY}}"}
Body: {"query": "search terms", "user_id": "{{user_id}}"}
```

**Define Error Responses:**

```
If an API returns an error:
- Try once more
- If it fails again, apologize and tell the user to contact support
- Never expose error details to users
```

**Set Response Format:**

```
Always format responses as:
1. Direct answer to the user's question
2. Supporting details if helpful
3. Link to documentation if available
4. Ask if they need anything else
```

## Troubleshooting

### Loop times out before completing

**Cause:** Too many iterations needed or slow API calls

**Solutions:**

* Increase max iterations
* Optimize your API endpoints for speed
* Simplify the agent's task
* Cache frequently accessed data

### Agent doesn't use tools

**Cause:** System prompt doesn't clearly explain when/how to use tools

**Solutions:**

* Add explicit instructions about tool usage
* Provide examples in the system prompt
* Test with questions that definitely require tool usage
* Check MCP server logs for errors

### Responses are inaccurate

**Cause:** Agent may be hallucinating or misinterpreting API responses

**Solutions:**

* Tell agent to only use information from API responses
* Add explicit instruction to say "I don't know" when unsure
* Format API responses more clearly
* Review execution logs to see what data agent received

### API calls fail

**Cause:** Authentication issues, rate limits, or incorrect endpoints

**Solutions:**

* Verify API credentials are correct
* Check allowed domains in MCP server settings
* Review API logs for specific errors
* Add retry logic for transient failures

## Next Steps

> [card] [Build a Personal Assistant](https://docs.chatbotplatform.io/guides/personal-assistant.md)
>
> Use multiple MCP servers for advanced workflows

> [card] [Deploy to Multiple Channels](https://docs.chatbotplatform.io/guides/multi-channel-deployment.md)
>
> Use the same grounded bot across platforms

> [card] [MCP Server Reference](https://docs.chatbotplatform.io/mcp-servers/overview.md)
>
> Learn about all available MCP servers

> [card] [Agentic Loops Documentation](https://docs.chatbotplatform.io/agentic-loops/overview.md)
>
> Deep dive into agentic loop features

## Related Documentation

* [Agentic Loops Overview](https://docs.chatbotplatform.io/agentic-loops/overview.md) - Core concepts and architecture
* [MCP Servers](https://docs.chatbotplatform.io/mcp-servers/overview.md) - Available tools and how to build custom servers
* [Building Custom MCP Servers](https://docs.chatbotplatform.io/mcp-servers/building-servers.md) - Create your own tools
* [API Reference](https://app.chatbotplatform.io/openapi) - Complete API documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.