# MCP

Connect Twig AI agents to external tools, data sources, and services using the Model Context Protocol.

## Overview

The **Model Context Protocol (MCP)** is an open protocol that standardizes how AI applications connect to external data sources and tools. MCP enables Twig agents to access real-time data, execute actions, and integrate with third-party services beyond their built-in capabilities.

### Key Benefits

* **Extensibility**: Add custom tools and data sources without modifying agent code
* **Standardization**: Use a consistent protocol across different integrations
* **Real-time Data**: Access live data from external systems during conversations
* **Tool Execution**: Enable agents to perform actions in external systems
* **Modular Architecture**: Add or remove capabilities dynamically

## Architecture

MCP follows a client-server architecture:

```
┌─────────────┐         ┌─────────────┐         ┌─────────────┐
│   Twig AI   │  MCP    │ MCP Server  │         │  External   │
│   Agent     │◄───────►│  (Host)     │◄───────►│  Services   │
└─────────────┘         └─────────────┘         └─────────────┘
  (MCP Client)           (Protocol)              (Data/Tools)
```

* **MCP Client**: Twig AI agent that requests data or tools
* **MCP Server**: Host that provides resources and tools to the agent
* **Resources**: Data sources (files, databases, APIs)
* **Tools**: Actions the agent can execute

## Getting Started

### Prerequisites

* Twig AI account with API access
* MCP server implementation (or use pre-built servers)
* Understanding of [Twig REST API](/product/developer-api/overview.md)

### Quick Setup

1. **Choose or Build an MCP Server**
   * Use pre-built servers for common integrations
   * Build custom servers for proprietary systems
2. **Configure Connection**
   * Register your MCP server endpoint
   * Set up authentication credentials
   * Define available resources and tools
3. **Enable for Agents**
   * Assign MCP capabilities to specific agents
   * Configure which resources agents can access
   * Test the integration

## MCP Concepts

### Resources

Resources are data sources that agents can query:

* **Files**: Documents, PDFs, spreadsheets
* **Databases**: SQL, NoSQL, vector databases
* **APIs**: REST, GraphQL endpoints
* **Real-time Streams**: Logs, metrics, events

**Example Resource:**

```json
{
  "uri": "file:///docs/policy.pdf",
  "name": "Company Policy Document",
  "mimeType": "application/pdf",
  "description": "Latest company policies and procedures"
}
```

### Tools

Tools are actions agents can execute:

* **Data Operations**: Search, filter, aggregate
* **System Actions**: Create tickets, send emails
* **Calculations**: Complex computations, data transformations
* **Integrations**: Trigger workflows in external systems

**Example Tool:**

```json
{
  "name": "create_support_ticket",
  "description": "Create a new support ticket in Zendesk",
  "inputSchema": {
    "type": "object",
    "properties": {
      "title": { "type": "string" },
      "description": { "type": "string" },
      "priority": { "type": "string", "enum": ["low", "medium", "high"] }
    },
    "required": ["title", "description"]
  }
}
```

### Prompts

Prompts are reusable templates for common agent interactions:

```json
{
  "name": "analyze_customer_data",
  "description": "Analyze customer behavior patterns",
  "arguments": [
    {
      "name": "customer_id",
      "description": "Customer identifier",
      "required": true
    }
  ]
}
```

## Configuration

### Connecting an MCP Server

#### API Endpoint

```bash
POST /api/v1/mcp/servers
```

#### Request Body

```json
{
  "name": "Zendesk Integration",
  "description": "Access Zendesk tickets and create support tickets",
  "endpoint": "https://mcp.example.com/zendesk",
  "auth": {
    "type": "bearer",
    "token": "YOUR_MCP_SERVER_TOKEN"
  },
  "capabilities": {
    "resources": true,
    "tools": true,
    "prompts": false
  }
}
```

#### Response

```json
{
  "serverId": "mcp-server-123",
  "status": "active",
  "connectedAt": "2026-01-26T10:30:00Z",
  "availableResources": 12,
  "availableTools": 5
}
```

### Assigning to Agents

Enable MCP for specific agents:

```bash
PUT /api/ai-agent-managers/{agentId}/mcp
```

```json
{
  "mcpServers": ["mcp-server-123"],
  "allowedResources": [
    "file:///docs/*",
    "db://tickets/*"
  ],
  "allowedTools": [
    "create_support_ticket",
    "search_knowledge_base"
  ]
}
```

## Using MCP Resources

### Query Resources

Agents automatically query MCP resources when relevant:

**User Question:**

```
"What's our current refund policy?"
```

**Agent Behavior:**

1. Identifies need for policy document
2. Queries MCP server for `file:///docs/refund-policy.pdf`
3. Retrieves content
4. Generates response using retrieved data

### Manual Resource Access

Explicitly request resources via API:

```bash
POST /api/mcp/resources/query
```

```json
{
  "serverId": "mcp-server-123",
  "resourceUri": "file:///docs/refund-policy.pdf",
  "agentId": "agent-123"
}
```

## Using MCP Tools

### Automatic Tool Execution

Agents decide when to use tools based on context:

**User Request:**

```
"Create a support ticket for billing issue"
```

**Agent Actions:**

1. Identifies need to create ticket
2. Calls `create_support_ticket` tool
3. Receives confirmation
4. Reports back to user

### Tool Execution Flow

```json
{
  "toolName": "create_support_ticket",
  "arguments": {
    "title": "Billing Issue - Invoice #12345",
    "description": "Customer reports incorrect charge on invoice",
    "priority": "high"
  }
}
```

**Response:**

```json
{
  "success": true,
  "result": {
    "ticketId": "ZD-9876",
    "ticketUrl": "https://support.example.com/tickets/9876",
    "createdAt": "2026-01-26T10:35:00Z"
  }
}
```

## Pre-built MCP Servers

### Available Integrations

| Server           | Resources                 | Tools                 | Status |
| ---------------- | ------------------------- | --------------------- | ------ |
| **Zendesk**      | Tickets, Articles         | Create/Update Tickets | Stable |
| **Salesforce**   | Accounts, Contacts, Cases | Create Records        | Beta   |
| **GitHub**       | Repositories, Issues, PRs | Create Issues         | Stable |
| **Google Drive** | Documents, Sheets         | Read Files            | Stable |
| **Slack**        | Messages, Channels        | Send Messages         | Beta   |
| **PostgreSQL**   | Tables, Views             | Query Data            | Stable |
| **MongoDB**      | Collections               | Query/Aggregate       | Beta   |

### Installing Pre-built Servers

```bash
curl -X POST https://api.twig.so/api/v1/mcp/install \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "zendesk",
    "credentials": {
      "subdomain": "your-company",
      "apiToken": "YOUR_ZENDESK_TOKEN",
      "email": "admin@company.com"
    }
  }'
```

## Building Custom MCP Servers

### Server Implementation

Create a server that implements the MCP protocol:

**Required Endpoints:**

* `POST /mcp/initialize` - Handshake and capability negotiation
* `GET /mcp/resources/list` - List available resources
* `POST /mcp/resources/read` - Read specific resource
* `GET /mcp/tools/list` - List available tools
* `POST /mcp/tools/call` - Execute a tool

### Example: Node.js Server

```javascript
import express from 'express';
import { MCPServer } from '@modelcontextprotocol/sdk';

const server = new MCPServer({
  name: "Custom CRM Integration",
  version: "1.0.0"
});

// Register resources
server.resource({
  uri: "crm://customers/*",
  name: "Customer Database",
  description: "Access customer records"
}, async (uri) => {
  const customerId = uri.split('/').pop();
  const customer = await db.customers.findById(customerId);
  return {
    mimeType: "application/json",
    content: JSON.stringify(customer)
  };
});

// Register tools
server.tool({
  name: "update_customer",
  description: "Update customer information",
  inputSchema: {
    type: "object",
    properties: {
      customerId: { type: "string" },
      updates: { type: "object" }
    }
  }
}, async (args) => {
  const result = await db.customers.update(
    args.customerId,
    args.updates
  );
  return { success: true, customerId: result.id };
});

server.listen(3000);
```

### Python Server Example

```python
from mcp.server import MCPServer, Resource, Tool

server = MCPServer(name="Analytics Integration")

@server.resource("analytics://metrics/{metric_name}")
async def get_metric(uri: str) -> Resource:
    metric_name = uri.split('/')[-1]
    data = await analytics_db.get_metric(metric_name)
    return Resource(
        uri=uri,
        mimeType="application/json",
        content=json.dumps(data)
    )

@server.tool("calculate_forecast")
async def calculate_forecast(time_range: str, metric: str) -> dict:
    forecast = await ml_model.predict(metric, time_range)
    return {"forecast": forecast, "confidence": 0.85}

if __name__ == "__main__":
    server.run(host="0.0.0.0", port=8080)
```

## Security & Permissions

### Authentication

MCP servers support multiple auth methods:

#### Bearer Token

```json
{
  "auth": {
    "type": "bearer",
    "token": "YOUR_TOKEN"
  }
}
```

#### OAuth 2.0

```json
{
  "auth": {
    "type": "oauth2",
    "clientId": "YOUR_CLIENT_ID",
    "clientSecret": "YOUR_CLIENT_SECRET",
    "tokenUrl": "https://auth.example.com/token"
  }
}
```

#### API Key

```json
{
  "auth": {
    "type": "apiKey",
    "key": "YOUR_API_KEY",
    "header": "X-API-Key"
  }
}
```

### Access Control

Restrict agent access to specific resources:

```json
{
  "permissions": {
    "resources": {
      "allow": ["file:///public/*"],
      "deny": ["file:///private/*"]
    },
    "tools": {
      "allow": ["search_*", "read_*"],
      "deny": ["delete_*", "admin_*"]
    }
  }
}
```

### Audit Logging

All MCP interactions are logged:

```json
{
  "timestamp": "2026-01-26T10:40:00Z",
  "agentId": "agent-123",
  "serverId": "mcp-server-123",
  "action": "tool_call",
  "toolName": "create_support_ticket",
  "success": true,
  "duration": 245
}
```

## Monitoring & Debugging

### Server Health

Check MCP server status:

```bash
GET /api/v1/mcp/servers/{serverId}/health
```

```json
{
  "status": "healthy",
  "latency": 45,
  "uptime": 2592000,
  "lastCheck": "2026-01-26T10:45:00Z",
  "metrics": {
    "resourceQueries": 1250,
    "toolCalls": 487,
    "errors": 3
  }
}
```

### Debug Mode

Enable detailed logging for troubleshooting:

```bash
PUT /api/v1/mcp/servers/{serverId}/debug
```

```json
{
  "debug": true,
  "logLevel": "verbose",
  "includePayloads": true
}
```

### Common Issues

#### Connection Failures

* Verify server endpoint is accessible
* Check authentication credentials
* Ensure firewall rules allow traffic

#### Tool Execution Errors

* Validate tool input schema
* Check server-side error logs
* Test tool independently

#### Resource Access Denied

* Review agent permissions
* Verify resource URIs are correct
* Check MCP server access controls

## Best Practices

### Resource Design

✅ **Good Practices:**

* Use descriptive resource URIs
* Provide clear descriptions
* Include relevant metadata
* Cache frequently accessed resources

❌ **Avoid:**

* Exposing sensitive data without auth
* Large resources without pagination
* Ambiguous resource naming

### Tool Design

✅ **Good Practices:**

* Clear, action-oriented tool names
* Comprehensive input schemas
* Detailed descriptions
* Idempotent operations when possible

❌ **Avoid:**

* Destructive operations without confirmation
* Tools with unclear side effects
* Missing error handling

### Performance

* Cache MCP responses when appropriate
* Implement timeouts for tool calls
* Use pagination for large datasets
* Monitor resource query latency

### Security

* Always use HTTPS for MCP endpoints
* Rotate credentials regularly
* Implement rate limiting on servers
* Audit tool executions
* Use least-privilege access

## Examples

### Customer Support Integration

Enable agents to access support tickets and create new ones:

**Setup:**

```bash
POST /api/v1/mcp/servers
```

```json
{
  "name": "Support System",
  "endpoint": "https://mcp.example.com/support",
  "capabilities": {
    "resources": true,
    "tools": true
  }
}
```

**Usage:**

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

Agent: [Queries resource: support://tickets/12345]
       "Ticket #12345 is currently in progress. 
        It was assigned to Sarah and last updated 2 hours ago."

User: "Create a new ticket for a billing issue."

Agent: [Calls tool: create_ticket]
       "I've created ticket #12346 for your billing issue. 
        You can track it at https://support.example.com/12346"
```

### Database Analytics

Query live database metrics:

```bash
POST /api/mcp/resources/query
```

```json
{
  "serverId": "mcp-postgres-prod",
  "resourceUri": "db://analytics/metrics/daily_users",
  "agentId": "agent-analytics"
}
```

**Response:**

```json
{
  "data": {
    "metric": "daily_active_users",
    "value": 15420,
    "change": "+5.2%",
    "timestamp": "2026-01-26T00:00:00Z"
  }
}
```

## API Reference

### List MCP Servers

```bash
GET /api/v1/mcp/servers
```

### Get Server Details

```bash
GET /api/v1/mcp/servers/{serverId}
```

### Update Server Configuration

```bash
PUT /api/v1/mcp/servers/{serverId}
```

### Remove Server

```bash
DELETE /api/v1/mcp/servers/{serverId}
```

### Test Connection

```bash
POST /api/v1/mcp/servers/{serverId}/test
```

## SDK Support

### TypeScript/JavaScript

```typescript
import { TwigAI } from '@twig-ai/sdk';

const twig = new TwigAI({ apiKey: process.env.TWIG_API_KEY });

// Add MCP server
await twig.mcp.addServer({
  name: "Custom Integration",
  endpoint: "https://mcp.example.com",
  auth: { type: "bearer", token: "TOKEN" }
});

// Query with MCP enabled
const response = await twig.chat({
  prompt: "Get latest customer data",
  agentId: "agent-123",
  mcpEnabled: true
});
```

### Python (Coming Soon)

```python
from twig_ai import TwigAI

twig = TwigAI(api_key=os.environ["TWIG_API_KEY"])

# Add MCP server
twig.mcp.add_server(
    name="Custom Integration",
    endpoint="https://mcp.example.com",
    auth={"type": "bearer", "token": "TOKEN"}
)
```

## Resources

### Documentation

* [MCP Protocol Specification](https://modelcontextprotocol.io/docs)
* [Official MCP SDK](https://github.com/modelcontextprotocol/sdk)
* [Twig REST API](/product/developer-api/overview.md)

### Tools & Libraries

* [MCP TypeScript SDK](https://www.npmjs.com/package/@modelcontextprotocol/sdk)
* [MCP Python SDK](https://pypi.org/project/mcp/)
* [MCP Server Examples](https://github.com/modelcontextprotocol/servers)

### Community

* [MCP Community Forum](https://community.modelcontextprotocol.io)
* [Example Integrations](https://github.com/twig-ai/mcp-examples)
* [Twig Developer Discord](/product/developer-api/mcp.md)

## Next Steps

* [Explore REST API Overview](/product/developer-api/overview.md) to understand Twig's API fundamentals
* [Review Authentication](/product/developer-api/authentication.md) to secure your integrations
* [Check Rate Limits](/product/developer-api/rate-limits.md) for MCP usage quotas
* [Browse Pre-built Integrations](#pre-built-mcp-servers) to get started quickly

For custom MCP server development, refer to the [official MCP documentation](https://modelcontextprotocol.io) and our [code examples](https://github.com/twig-ai/mcp-examples).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.twig.so/product/developer-api/mcp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
