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

# Using Tools with MCP Servers

> Connect your agents to real-world data sources to eliminate hallucinations

Model Context Protocol (MCP) servers provide tools that enable Agentic Loops to access real-world data instead of hallucinating responses. This is the key to grounding AI in verifiable facts.

## Why Tools Eliminate Hallucinations

### The Problem: LLMs Guess When They Don't Know

```
User: "What's the current price of AAPL stock?"

LLM (No Tools): "Apple stock is trading around $180."
[HALLUCINATION: Training data from months ago, price is wrong]

Agent (With Tools): [Calls stock_price API]
                    "Apple stock is currently at $193.42."
[GROUNDED: Real-time data from stock market API]
```

### The Solution: Tools Provide Real Data

Tools transform your agent from a text generator into a data-driven assistant:

* **No Tool**: Agent guesses based on outdated training data
* **With Tool**: Agent fetches current, verifiable information

Every tool call is logged, making every fact in your agent's response traceable to its source. This builds trust and enables debugging.

## Available MCP Servers

### Built-In MCP Servers

These servers are ready to use without additional setup:

> [card] [Time Utilities](https://docs.chatbotplatform.io/mcp-servers/time.md)
>
> Current time, date utilities, timezone conversion

> [card] [OpenRouter](https://docs.chatbotplatform.io/mcp-servers/openrouter.md)
>
> AI model recommendations and capabilities

> [card] [Conversation Archives](https://docs.chatbotplatform.io/mcp-servers/conversation-archives)
>
> Access conversation history and summaries

> [card] [Reminders](https://docs.chatbotplatform.io/mcp-servers/reminders)
>
> Create and manage reminders for conversations

### External Data Source MCP Servers

These require API keys from external services:

> [card] [Google Maps](https://docs.chatbotplatform.io/mcp-servers/google-maps.md)
>
> Geocoding, place search, directions, location services

### Custom MCP Servers

Build your own MCP servers for proprietary data sources:

> [card] [Build Custom MCP Servers](https://docs.chatbotplatform.io/mcp-servers/building-servers.md)
>
> Learn how to create custom MCP servers using Laravel's MCP package

## Configuring MCP Servers

**1. Open Agent Loop Settings**

Navigate to your Agentic Loop configuration page.

**2. Add MCP Server**

In the **MCP Servers** section, click **Add Server**.

![MCP server configured](https://mintcdn.com/chatbotplatform/IwOyuSig9ydzaHpG/images/screenshots/04-agentic/07_mcp_server_configured.png?fit=max\&auto=format\&n=IwOyuSig9ydzaHpG\&q=85\&s=bec5c6035662f70e5b6d997c1740bffe)

MCP server configuration

**3. Select Server Type**

Choose from available MCP servers:

* **Time Utilities**: No additional config required
* **Google Maps**: Requires Google Maps API key
* **Custom Server**: Enter your server URL

**4. Configure Authentication**

For servers requiring API keys:

```
Server: Google Maps
API Key Header: X-Google-Maps-Api-Key
API Key: YOUR_GOOGLE_MAPS_API_KEY
```

**5. Test Connection**

Click **Test** to verify the MCP server is accessible.

**6. Save**

Click **Save** to enable the tool for your agent.

## Using MCP Tools in Your Agent

### 1. Document Tools in System Prompt

The agent needs to know what tools are available and when to use them.

**Example System Prompt**:

```
You are a location-aware assistant with access to these tools:

1. Google Maps MCP Server
   - geocode: Convert addresses to coordinates
     Parameters: {address: string}
     Returns: {lat: number, lng: number, formatted_address: string}

   - search_places: Find nearby locations
     Parameters: {query: string, location?: string}
     Returns: [{name: string, address: string, rating: number}]

   - get_directions: Get route between two locations
     Parameters: {origin: string, destination: string, mode?: string}
     Returns: {distance: string, duration: string, steps: array}

When users ask about locations, addresses, or directions, use these
tools to provide accurate, current information. Never guess locations
or directions.
```

### 2. Agent Decides When to Use Tools

During execution, the agent analyzes the user's question and determines which tool to use:

```
User: "How do I get from San Francisco to Palo Alto?"

Agent Reasoning:
"This is a directions request. I need to use the get_directions
tool from Google Maps MCP."

Tool Call:
{
  tool: "get_directions",
  parameters: {
    origin: "San Francisco, CA",
    destination: "Palo Alto, CA",
    mode: "driving"
  }
}

Tool Response:
{
  distance: "35 miles",
  duration: "45 minutes",
  steps: [
    "Head south on US-101 S",
    "Take exit 398 for University Ave",
    ...
  ]
}

Agent Response:
"To get from San Francisco to Palo Alto, take US-101 South for
about 35 miles. The drive takes approximately 45 minutes. Key steps:
head south on US-101 S, then take exit 398 for University Ave."

[GROUNDED: Every detail from Google Maps API]
```

### 3. Multiple Tool Calls

Complex queries may require multiple tool calls:

```
User: "Find coffee shops near the Golden Gate Bridge"

Iteration 1:
Agent: "I need the coordinates of Golden Gate Bridge first."
Tool Call: geocode({address: "Golden Gate Bridge, San Francisco"})
Response: {lat: 37.8199, lng: -122.4783}

Iteration 2:
Agent: "Now I'll search for coffee shops near those coordinates."
Tool Call: search_places({
  query: "coffee shop",
  location: "37.8199,-122.4783"
})
Response: [
  {name: "Blue Bottle Coffee", address: "2 Marina Blvd", rating: 4.5},
  {name: "Equator Coffees", address: "2001 Chestnut St", rating: 4.3},
  ...
]

Iteration 3:
Agent: "I have the results. I'll format them clearly."
Response: "Here are coffee shops near the Golden Gate Bridge:

1. Blue Bottle Coffee - 2 Marina Blvd (4.5⭐)
2. Equator Coffees - 2001 Chestnut St (4.3⭐)
..."

[GROUNDED: Real places from Google Maps API]
```

## Real-World Examples by Use Case

### Example 1: Order Tracking System

**Goal**: Stop hallucinating order statuses.

**MCP Server Configuration**:

```
Server: Custom Order Database MCP
URL: https://your-api.com/mcp/orders
Authentication: Bearer token

Tools:
- get_order_status
- get_tracking_info
- get_order_history
```

**System Prompt**:

```
You track customer orders using our order database.

Available Tools:
- get_order_status: Get current order status
  Parameters: {order_id: string}
  Returns: {status, date_ordered, date_shipped, tracking_number}

Process:
1. Extract order ID from user question
2. Call get_order_status with order ID
3. Format response with actual data
4. If order not found, say so clearly

NEVER guess order information. Every fact must come from the database.
```

**Result**: 100% accurate order information, zero hallucinations.

### Example 2: Weather Information Bot

**Goal**: Provide current weather, not outdated training data.

**MCP Server Configuration**:

```
Server: Custom Weather MCP (or HTTP Client)
URL: https://api.weather.com/mcp
API Key: YOUR_WEATHER_API_KEY

Tools:
- get_current_weather
- get_forecast
```

**System Prompt**:

```
You provide weather information using real-time data.

Available Tools:
- get_current_weather: Get current conditions
  Parameters: {city: string}
  Returns: {temperature, condition, humidity, wind}

CRITICAL: Always call get_current_weather before answering.
Never use training data for weather information.
```

**Result**: Always current weather data, no outdated information.

### Example 3: Location-Based Recommendations

**Goal**: Recommend actual places, not fictional locations.

**MCP Server Configuration**:

```
Server: Google Maps MCP
API Key: YOUR_GOOGLE_MAPS_API_KEY

Tools:
- search_places
- geocode
- get_place_details
```

**System Prompt**:

```
You recommend locations using Google Maps data.

Available Tools:
- search_places: Find locations by query
  Parameters: {query: string, location?: string, radius?: number}
  Returns: [{name, address, rating, types}]

Process:
1. Understand what user is looking for (restaurants, hotels, etc.)
2. Use search_places to find actual locations
3. Present results with names, addresses, and ratings
4. All recommendations must come from the API

NEVER invent place names or addresses. Only recommend real locations
from the search results.
```

**Result**: All recommendations are real, verified locations.

### Example 4: Calendar Assistant

**Goal**: Schedule meetings based on actual availability.

**MCP Server Configuration**:

```
Server: Custom Calendar MCP
URL: https://your-app.com/mcp/calendar
Authentication: Bearer token

Tools:
- check_availability
- create_event
- list_events
```

**System Prompt**:

```
You manage calendar events with access to real availability data.

Available Tools:
- check_availability: Find available time slots
  Parameters: {date: string, attendees: array, duration: number}
  Returns: [{start_time, end_time, available: boolean}]

- create_event: Schedule a meeting
  Parameters: {title, start, end, attendees}
  Returns: {event_id, confirmation}

Process:
1. Parse meeting request (date, attendees, duration)
2. Call check_availability to find open slots
3. Present available options to user
4. Once confirmed, create event
5. Provide confirmation with event details

NEVER suggest meeting times without checking availability first.
```

**Result**: Zero scheduling conflicts, all meetings based on real availability.

## Authentication Patterns

MCP servers use different authentication methods:

### Pattern 1: Public (No Authentication)

Some servers are publicly accessible:

```
Server: Time Utilities
URL: https://app.chatbotplatform.io/mcp/time
Authentication: None required
```

### Pattern 2: Conversation API Key

Servers accessing conversation data use the conversation's API key:

```
Server: Conversation Archives
URL: https://app.chatbotplatform.io/mcp/archives
Authentication: Automatically provided (conversation API key)
```

### Pattern 3: External API Key

Servers proxying external services require API keys:

```
Server: Google Maps
URL: https://app.chatbotplatform.io/mcp/google-maps
Authentication: X-Google-Maps-Api-Key header
Value: YOUR_GOOGLE_MAPS_API_KEY
```

### Pattern 4: Custom Authentication

Your custom MCP servers can use any auth method:

```
Server: Custom Internal API
URL: https://your-api.com/mcp
Authentication: Bearer token or API key
Headers:
  Authorization: Bearer YOUR_INTERNAL_API_TOKEN
  X-Organization-ID: your_org_id
```

## Building Custom MCP Servers

Create tools for your proprietary data sources:

### When to Build Custom MCP Servers

Build custom servers when you need to:

* Access your internal databases
* Connect to proprietary APIs
* Implement custom business logic
* Integrate with legacy systems
* Provide domain-specific tools

### MCP Server Requirements

Your server must:

1. **Accept tool call requests** (POST /tools/{tool_name})
2. **Execute the requested action**
3. **Return structured JSON responses**
4. **Handle errors gracefully**

### Example: Order Database MCP Server

```javascript theme={null}
// server.js - Node.js MCP Server
const express = require('express');
const app = express();
app.use(express.json());

// Tool: Get Order Status
app.post('/tools/get_order_status', async (req, res) => {
  const { order_id } = req.body.parameters;

  try {
    // Query your database
    const order = await database.query(
      'SELECT * FROM orders WHERE order_id = ?',
      [order_id]
    );

    if (!order) {
      return res.json({
        success: false,
        error: 'Order not found'
      });
    }

    res.json({
      success: true,
      data: {
        order_id: order.id,
        status: order.status,
        date_ordered: order.created_at,
        date_shipped: order.shipped_at,
        tracking_number: order.tracking_number
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// Tool: Get Tracking Info
app.post('/tools/get_tracking_info', async (req, res) => {
  const { tracking_number } = req.body.parameters;

  try {
    // Call shipping carrier API
    const tracking = await shippingAPI.getTracking(tracking_number);

    res.json({
      success: true,
      data: {
        tracking_number,
        status: tracking.status,
        location: tracking.current_location,
        estimated_delivery: tracking.estimated_delivery,
        history: tracking.events
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

app.listen(3000, () => {
  console.log('Order Database MCP Server running on port 3000');
});
```

### Deploying Your MCP Server

**1. Deploy to Production**

Host your MCP server at a publicly accessible URL:

* Use services like Railway, Fly.io, or AWS
* Ensure HTTPS is enabled
* Example: [https://your-mcp-server.com](https://your-mcp-server.com)

**2. Document Your Tools**

Create clear documentation for each tool:

```
Tool: get_order_status
Description: Retrieves current status of an order
Parameters:
  - order_id (string, required): The order ID to look up
Returns:
  - order_id (string): Order identifier
  - status (string): Current status
  - date_ordered (string): Order date
  - date_shipped (string): Ship date (if applicable)
  - tracking_number (string): Tracking number (if applicable)
Errors:
  - "Order not found" if order_id doesn't exist
```

**3. Add to Agent Loop**

Configure your custom MCP server in the agent loop:

```
Server Type: Custom
URL: https://your-mcp-server.com
Authentication: Bearer YOUR_API_TOKEN
```

**4. Update System Prompt**

Document the tools in your agent's system prompt:

```
Available Tools:
- get_order_status: Get order details
  Parameters: {order_id: string}
  Returns: {order_id, status, dates, tracking}
```

> [card] [Build Custom MCP Servers](https://docs.chatbotplatform.io/mcp-servers/building-servers.md)
>
> Complete guide to building MCP servers with Laravel's MCP package

## Tool Call Format

### Request Format

MCP servers receive tool calls in this format:

```json theme={null}
POST /tools/get_order_status

{
  "tool": "get_order_status",
  "parameters": {
    "order_id": "12345"
  },
  "context": {
    "agent_loop_id": "loop_abc123",
    "execution_id": "exec_xyz789",
    "conversation_id": "conv_def456"
  }
}
```

### Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "order_id": "12345",
    "status": "shipped",
    "date_ordered": "2024-01-15",
    "tracking_number": "1Z999AA10123456784"
  },
  "metadata": {
    "execution_time_ms": 45,
    "source": "order_database"
  }
}
```

### Error Response

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ORDER_NOT_FOUND",
    "message": "No order found with ID 12345",
    "details": {
      "order_id": "12345",
      "checked_at": "2024-01-16T10:30:00Z"
    }
  }
}
```

## Troubleshooting

### Tool Not Being Called

**Symptom**: Agent provides answer without calling tool (hallucination).

**Possible Causes**:

* Tool not mentioned in system prompt
* Instructions unclear about when to use tool
* Agent decided tool wasn't necessary

**Solutions**:

```
Update System Prompt:
"CRITICAL: You MUST use the [tool_name] tool for [use case].
NEVER answer without calling this tool first."

Add explicit process steps:
"Process:
1. Identify the [parameter] from user question
2. Call [tool_name] with [parameter]
3. Wait for response
4. Format response data
Do not skip step 2."
```

### Tool Call Fails

**Symptom**: Error message in execution log, agent can't complete task.

**Check**:

* MCP server URL is correct and accessible
* Authentication credentials are valid
* MCP server is running and responsive
* Parameters match expected format
* Network connectivity between platform and server

**Debug**:

```bash theme={null}
# Test MCP server manually
curl -X POST https://your-mcp-server.com/tools/your_tool \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{"tool": "your_tool", "parameters": {"param": "value"}}'
```

### Wrong Parameters Sent

**Symptom**: Tool receives incorrect or missing parameters.

**Possible Causes**:

* System prompt doesn't document parameters clearly
* Agent misunderstood parameter requirements
* Parameter validation is missing

**Solutions**:

```
Document parameters explicitly:
"Tool: get_order_status
Parameters:
  - order_id (string, required): The order ID, e.g., '12345'
  - include_history (boolean, optional): Include order history

Example call:
{
  tool: 'get_order_status',
  parameters: {
    order_id: '12345',
    include_history: true
  }
}"
```

### Tool Responses Are Inconsistent

**Symptom**: Sometimes works, sometimes doesn't.

**Check**:

* Timeout settings (increase if needed)
* Rate limiting on external APIs
* Data availability (some queries may return no results)
* Error handling in MCP server code

## Best Practices

> [card] Start Simple
>
> Begin with one tool, add more as needed

> [card] Document Clearly
>
> Explicit tool documentation in system prompts

> [card] Test Thoroughly
>
> Test tools separately before agent integration

> [card] Handle Errors
>
> Provide clear error messages for debugging

### System Prompt Best Practices

**Do**:

* List all available tools with descriptions
* Document parameters and return values
* Provide usage examples
* Specify when to use each tool
* Include error handling instructions

**Don't**:

* Assume agent knows about tools (document everything)
* Use vague descriptions ("use this when needed")
* Skip parameter documentation
* Forget to mention required vs. optional parameters

### MCP Server Design

**Do**:

* Create focused, single-purpose tools
* Use clear, descriptive tool names
* Validate all input parameters
* Return structured, consistent JSON
* Include helpful error messages

**Don't**:

* Create overly complex multi-purpose tools
* Return unstructured text responses
* Skip input validation
* Ignore errors or return generic "failed" messages

## Next Steps

> [card] [Best Practices](https://docs.chatbotplatform.io/agentic-loops/best-practices.md)
>
> Optimize for performance, cost, and reliability

> [card] [Available MCP Servers](https://docs.chatbotplatform.io/mcp-servers/overview.md)
>
> Explore all built-in MCP servers

> [card] [Build Custom Servers](https://docs.chatbotplatform.io/mcp-servers/building-servers.md)
>
> Create tools for your proprietary systems

> [card] [Complete API Reference](https://app.chatbotplatform.io/openapi)
>
> View the full API specification for MCP server integration


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