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

# MCP Servers

> Configure tools for your Agent Loops via Model Context Protocol

MCP (Model Context Protocol) servers provide tools that Agent Loops can use to interact with external systems, access data, and perform actions beyond text generation.

## Overview

Model Context Protocol is a standard for connecting AI agents to tools and data sources. MCP servers expose capabilities (tools) that agents can call during execution.

**Example**: An HTTP MCP server lets agents make API requests, a File System MCP server enables file operations, and a Database MCP server allows SQL queries.

## Available MCP Servers

### HTTP Client

Make HTTP requests to external APIs.

**Capabilities**:

* GET, POST, PUT, DELETE, PATCH requests
* Custom headers and authentication
* Request body formatting
* Response parsing

**Use Cases**:

* Call REST APIs
* Fetch data from web services
* Send webhooks
* Integrate with third-party services

**Configuration**:

```
Server Type: HTTP Client
URL: Auto-configured
Authentication: Configure per-request via agent instructions
```

**Example Agent Instructions**:

```
Use the HTTP tool to make a GET request to:
https://api.openweathermap.org/data/2.5/weather?q=San Francisco&appid=YOUR_KEY

Parse the JSON response and extract temperature and conditions.
```

### File System (Coming Soon)

Read and write files.

**Capabilities**:

* Read file contents
* Write new files
* List directories
* Check file existence
* Get file metadata

**Use Cases**:

* Process uploaded files
* Generate reports and save to storage
* Read configuration files
* Log data to files

### Database (Coming Soon)

Execute SQL queries.

**Capabilities**:

* SELECT queries
* INSERT, UPDATE, DELETE statements
* Transaction support
* Multiple database support (PostgreSQL, MySQL, SQLite)

**Use Cases**:

* Query application data
* Generate reports from database
* Update records based on rules
* Data analysis and aggregation

### Custom MCP Servers

Deploy your own MCP servers for custom tools.

## Configuring MCP Servers

<Steps>
  <Step title="Create/Edit Agent Loop">
    Open the agent loop configuration page.
  </Step>

  <Step title="Go to MCP Servers Section">
    Find the **MCP Servers** or **Tools** section.
  </Step>

  <Step title="Add Server">
    Click **Add MCP Server** and choose the type.
  </Step>

  <Step title="Configure Connection">
    Enter server URL and any required authentication:

    * Server URL: The MCP server endpoint
    * Auth Headers: Authentication tokens if needed
  </Step>

  <Step title="Save">
    Click **Save** to enable the tool for this agent loop.
  </Step>
</Steps>

## Using MCP Tools in Agents

### Instructing the Agent

Tell the agent about available tools in the system prompt:

```
You have access to these tools:

1. HTTP Client: Make API requests
   - Use this to call external services
   - Example: Fetch data from REST APIs

2. File System: Read and write files
   - Use this to access uploaded files
   - Example: Read CSV file for processing

When you need to use a tool, clearly state your intention
and provide all required parameters.
```

### Tool Call Example

Agent decides to use a tool:

```
Agent Thought: "I need to fetch the weather data. I'll use the HTTP tool."

Tool Call:
{
  "tool": "http_client",
  "method": "GET",
  "url": "https://api.weather.com/v1/current?city=SF",
  "headers": {
    "Authorization": "Bearer API_KEY"
  }
}

Tool Response:
{
  "temperature": 62,
  "conditions": "Partly Cloudy",
  "humidity": 65
}

Agent: "I received the weather data. Temperature is 62°F with partly cloudy conditions."
```

## Building Custom MCP Servers

Create your own tools by implementing an MCP server:

### MCP Server Requirements

Your server must:

1. **Accept Tool Call Requests**: POST requests with tool name and parameters
2. **Execute Tool Logic**: Perform the requested action
3. **Return Results**: JSON response with output
4. **Handle Errors**: Return error messages when things fail

### Example MCP Server (Node.js)

```javascript theme={null}
const express = require('express');
const app = express();
app.use(express.json());

// Tool: Send Email
app.post('/tools/send_email', async (req, res) => {
  const { to, subject, body } = req.body.parameters;

  try {
    await sendEmail(to, subject, body);
    res.json({
      success: true,
      message: `Email sent to ${to}`
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// Tool: Query Database
app.post('/tools/query_database', async (req, res) => {
  const { query } = req.body.parameters;

  try {
    const results = await database.query(query);
    res.json({
      success: true,
      data: results
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

app.listen(3000);
```

### Registering Custom MCP Server

<Steps>
  <Step title="Deploy Your Server">
    Host your MCP server at a public URL (e.g., [https://your-mcp-server.com](https://your-mcp-server.com)).
  </Step>

  <Step title="Document Your Tools">
    Create documentation for each tool describing:

    * Tool name
    * Required parameters
    * Return format
    * Example usage
  </Step>

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

  <Step title="Update System Prompt">
    Document the available tools in your agent's system prompt.
  </Step>
</Steps>

## Tool Call Format

MCP servers receive tool calls in this format:

```json theme={null}
{
  "tool": "tool_name",
  "parameters": {
    "param1": "value1",
    "param2": "value2"
  },
  "context": {
    "agent_loop_id": "loop_abc123",
    "execution_id": "exec_xyz789"
  }
}
```

Expected response:

```json theme={null}
{
  "success": true,
  "result": {
    "output": "Tool execution result",
    "metadata": {
      "execution_time_ms": 150
    }
  }
}
```

Or error response:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "TOOL_ERROR",
    "message": "Description of what went wrong"
  }
}
```

## Security Considerations

<CardGroup cols={2}>
  <Card title="Authentication" icon="lock">
    Secure your MCP server with API keys or tokens
  </Card>

  <Card title="Input Validation" icon="shield-check">
    Validate all parameters before execution
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Implement rate limits to prevent abuse
  </Card>

  <Card title="Audit Logging" icon="file-lines">
    Log all tool calls for security review
  </Card>
</CardGroup>

### Securing Custom MCP Servers

**Authentication**:

```javascript theme={null}
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (apiKey !== process.env.MCP_API_KEY) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});
```

**Authorization**:

```javascript theme={null}
app.post('/tools/delete_user', async (req, res) => {
  // Check if agent loop has permission for this action
  const { agent_loop_id } = req.body.context;
  if (!hasPermission(agent_loop_id, 'delete_user')) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  // ... proceed with deletion
});
```

## Best Practices

<Callout type="tip">
  Start with built-in MCP servers before building custom ones. Only create custom servers when you need capabilities not available in standard tools.
</Callout>

### Tool Design

**Do**:

* Create focused tools (one tool = one capability)
* Use clear, descriptive tool names
* Validate all inputs
* Return structured, parseable output
* Include error messages when things fail

**Don't**:

* Create overly complex tools
* Return unstructured text
* Skip input validation
* Expose dangerous operations without auth
* Leave errors unhandled

### Agent Instructions

**Clear Documentation**:

```
HTTP Tool Usage:
- To fetch data: Specify method (GET), URL, and any headers
- The tool returns JSON responses
- Example: GET https://api.example.com/data
```

**Expected Format**:

```
When calling the database tool, use this query format:
SELECT column1, column2 FROM table WHERE condition

The tool will return an array of objects with the selected columns.
```

## Troubleshooting

### Tool Not Being Called

**Possible Causes**:

* Agent doesn't know about the tool (add to system prompt)
* Instructions are unclear about when to use it
* Agent decided tool wasn't needed

**Solutions**:

* Explicitly mention tool in system prompt
* Provide examples of tool usage
* Make task require the tool

### Tool Call Fails

**Check**:

* MCP server URL is correct
* Server is running and accessible
* Authentication is configured
* Parameters are valid
* Review MCP server logs

### Wrong Parameters Sent

**Possible Causes**:

* Agent misunderstood parameter requirements
* System prompt lacks detail

**Solutions**:

* Clearly document required parameters
* Provide examples in system prompt
* Validate parameters in MCP server

## Next Steps

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

  <Card title="Callbacks" icon="webhook" href="/agent-loops/callbacks">
    Receive agent loop results
  </Card>
</CardGroup>
