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

# Integrations Overview

> Connect CallIntel with external platforms. CallIntel supports seamless integration with popular platforms through the Model Context Protocol (MCP).

## Available Integrations

<Columns cols={2}>
  <Card title="Telegram" icon="send" href="/guides/integrations/telegram">
    Send and receive Telegram messages.
  </Card>

  <Card title="Gmail" icon="envelope" href="/guides/integrations/gmail">
    Send emails and manage inbox.
  </Card>

  <Card title="WhatsApp" icon="whatsapp" href="/guides/integrations/whatsapp">
    WhatsApp messaging integration.
  </Card>
</Columns>

## Integration Architecture

```
Agent Service
    │
    └─► MCP Client
            │
            ├─► TCP Connection
            │
            └─► MCP Server Process
                    │
                    ├─► Telegram Tools
                    ├─► Gmail Tools
                    ├─► WhatsApp Tools
                    └─► Shopify Tools
```

## MCP Service Setup

MCP services run as separate processes listening on specific ports:

```yaml theme={null}
services:
  tele_mcp:
    port: 8100
    tools:
      - send_message
      - read_message
      - get_chat_info

  gmail_mcp:
    port: 8101
    tools:
      - send_email
      - read_email
      - list_labels

  whatsapp_mcp:
    port: 8102
    tools:
      - send_message
      - read_message
      - create_group
```

## Using Integrations

### Basic Tool Execution

```python theme={null}
from Service.McpService import McpService

mcp = McpService()

# Send Telegram message
result = await mcp.execute_tool(
    service="telegram",
    tool="send_message",
    arguments={
        "chat_id": "123456789",
        "text": "Hello from CallIntel!"
    }
)

print(result)
```

### In Agent Context

Agents can automatically use integration tools:

```python theme={null}
system_prompt = """
You are a customer support agent for TechCorp.

You have access to the following tools:
1. Send email to customers
2. Send Telegram messages
3. Look up orders in Shopify
4. Check email threads

Use these tools to help customers efficiently.
"""

agent = await agent_service.create_agent({
    "name": "Support Agent",
    "system_prompt": system_prompt,
    "available_tools": [
        "gmail.send_email",
        "telegram.send_message",
        "shopify.get_orders"
    ]
})
```

### Tool Result Processing

```python theme={null}
# When an agent calls a tool
tool_result = await mcp.execute_tool(
    service="shopify",
    tool="get_orders",
    arguments={"customer_id": "cust-123"}
)

# Result is passed back to agent
agent_input = f"Customer orders: {tool_result}"
response = await agent_service.process_message(
    agent_id,
    agent_input
)
```

## Configuration by Service

### Telegram

**Setup:**

1. Create bot with BotFather
2. Get API token
3. Set webhook URL

**Environment:**

```env theme={null}
TELEGRAM_BOT_TOKEN=your_token
TELEGRAM_API_URL=https://api.telegram.org
TELE_MCP_SERVER_URL=http://tele_mcp:8100
```

**Docker Compose:**

```yaml theme={null}
tele_mcp:
  build:
    dockerfile: docker/Dockerfile.tele
  image: tele_mcp_service:latest
  ports:
    - "8100:8100"
  environment:
    - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
    - SUPABASE_URL=${SUPABASE_URL}
    - SUPABASE_KEY=${SUPABASE_KEY}
```

### Gmail

**Setup:**

1. Create Google Cloud project
2. Enable Gmail API
3. Create OAuth credentials
4. Download credentials JSON

**File Structure:**

```
integrations/mcp_gmail/
├── credentials.json
├── mcp_client.py
├── mcp_server.py
└── predefined_email.py
```

**Environment:**

```env theme={null}
GMAIL_CREDENTIALS_FILE=integrations/mcp_gmail/credentials.json
GMAIL_MCP_SERVER_URL=http://gmail_mcp:8101
```

### WhatsApp

**Setup:**

1. Create Meta/WhatsApp Business account
2. Get access token
3. Configure webhook

**Database:**

```
integrations/mcp_whatsapp/
├── database.py
├── mcp_client.py
├── mcp_server.py
└── config.py
```

**Environment:**

```env theme={null}
WHATSAPP_API_TOKEN=your_token
WHATSAPP_PHONE_NUMBER=your_number
WHATSAPP_MCP_SERVER_URL=http://whatsapp_mcp:8102
```

### Shopify

**Setup:**

1. Create Shopify app
2. Get API credentials
3. Install app on store

**Plugin Location:**

```
integrations/shopify_plugin/
├── client.py
├── models.py
└── auth.py
```

**Environment:**

```env theme={null}
SHOPIFY_API_KEY=your_key
SHOPIFY_API_SECRET=your_secret
SHOPIFY_STORE_URL=your_store.myshopify.com
```

## Common Integration Patterns

### Email Notification Pattern

```python theme={null}
# Agent sends email to customer
result = await mcp.execute_tool(
    service="gmail",
    tool="send_email",
    arguments={
        "to": "customer@example.com",
        "subject": f"Order {order_id} Status",
        "body": "Your order has been shipped!"
    }
)

if result["success"]:
    logger.info(f"Email sent to customer")
else:
    logger.error(f"Email send failed: {result['error']}")
```

### Message Loop Pattern

```python theme={null}
# Agent sends message to customer
result = await mcp.execute_tool(
    service="telegram",
    tool="send_message",
    arguments={
        "chat_id": customer_telegram_id,
        "text": "Your appointment is confirmed for tomorrow at 2 PM"
    }
)

# Get response (poll or webhook)
messages = await mcp.execute_tool(
    service="telegram",
    tool="read_message",
    arguments={
        "chat_id": customer_telegram_id,
        "limit": 1
    }
)

agent_response = await agent_service.process_message(
    agent_id,
    f"Customer replied: {messages[0]['text']}"
)
```

### Lookup Pattern

```python theme={null}
# Agent needs customer data
customer_data = await mcp.execute_tool(
    service="shopify",
    tool="get_customer",
    arguments={
        "customer_id": "cust-123"
    }
)

# Use data in agent prompt
context = f"""
Customer: {customer_data['name']}
Email: {customer_data['email']}
Orders: {customer_data['total_orders']}
Lifetime Value: ${customer_data['total_spent']}
"""

response = await agent_service.process_message(
    agent_id,
    user_message,
    context=context
)
```

## Error Handling

### Tool Execution Errors

```python theme={null}
try:
    result = await mcp.execute_tool(
        service="gmail",
        tool="send_email",
        arguments={"to": "user@example.com", "subject": "Hi", "body": "Hello"}
    )
    
    if not result["success"]:
        logger.error(f"Tool failed: {result['error']}")
        # Retry or handle gracefully
        
except ConnectionError:
    logger.error("MCP service unavailable")
    # Fall back to alternative
    
except Exception as e:
    logger.error(f"Unexpected error: {e}")
    # Use fallback mechanism
```

### Fallback Strategies

```python theme={null}
async def send_message_with_fallback(service, arguments):
    # Try primary service
    try:
        return await mcp.execute_tool(service, "send_message", arguments)
    except Exception as e:
        logger.error(f"{service} failed: {e}")
        
        # Fall back to email
        try:
            return await mcp.execute_tool(
                "gmail",
                "send_email",
                arguments={
                    "to": arguments.get("email"),
                    "subject": "Message",
                    "body": arguments.get("text")
                }
            )
        except:
            # Log and inform user
            logger.error("All message services failed")
            return {"success": False, "error": "Could not send message"}
```

## Monitoring Integrations

### Health Check

```python theme={null}
async def check_integration_health():
    services = ["telegram", "gmail", "whatsapp", "shopify"]
    health = {}
    
    for service in services:
        try:
            result = await mcp.execute_tool(
                service,
                "health_check",
                {}
            )
            health[service] = "healthy" if result["success"] else "unhealthy"
        except:
            health[service] = "unreachable"
    
    return health
```

### Logging Integration Usage

```python theme={null}
async def log_tool_usage(service, tool, arguments, result):
    await supabase.table("integration_logs").insert({
        "service": service,
        "tool": tool,
        "success": result["success"],
        "error": result.get("error"),
        "timestamp": datetime.now(),
        "arguments_count": len(arguments),
    }).execute()
```

## Performance Tips

1. **Cache Results**: Cache frequently accessed data
2. **Parallel Execution**: Run multiple tool calls simultaneously
3. **Rate Limiting**: Respect API rate limits
4. **Connection Pooling**: Reuse connections
5. **Batch Operations**: Group operations when possible

## Troubleshooting

### Service Not Connecting

```bash theme={null}
# Check if MCP service is running
curl http://localhost:8100/health

# View service logs
docker-compose logs tele_mcp

# Restart service
docker-compose restart tele_mcp
```

### Authentication Failures

```env theme={null}
# Verify credentials are correct
# Check token expiration
# Regenerate tokens if needed
```

### Rate Limiting

```python theme={null}
# Implement exponential backoff
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10)
)
async def execute_with_retry(service, tool, arguments):
    return await mcp.execute_tool(service, tool, arguments)
```

## Next Steps

<Columns cols={2}>
  <Card title="Telegram Integration" icon="send" href="/guides/integrations/telegram">
    Set up Telegram messaging.
  </Card>

  <Card title="Gmail Integration" icon="envelope" href="/guides/integrations/gmail">
    Enable email capabilities.
  </Card>

  <Card title="API Reference" icon="terminal" href="/api-reference/introduction">
    API documentation.
  </Card>
</Columns>
