npm package: @ironclads/cloudflare-mcp
Description: Enterprise-grade MCP Server for Cloudflare management with DNS, SSL, Cache, Firewall, and Zone settings support
Author: kappa
Latest version: 1.0.3

# Cloudflare MCP Server

A robust **Model Context Protocol (MCP) Server** for managing Cloudflare DNS records with comprehensive error handling, validation, and logging.

[![npm version](https://img.shields.io/npm/v/cloudflare-mcp.svg)](https://git.actions.it.com/kappa/cloudflare-mcp)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🚀 Features

### DNS Management
- 📋 List DNS records for any domain with optional type filtering
- ➕ Create new DNS records (A, AAAA, CNAME, MX, TXT, etc.)
- 🗑️ Delete DNS records by ID
- 🔍 Search DNS records across all zones
- 🌍 Add/remove domains (zones) to/from Cloudflare
- 📊 List all domains in your account

### Cache Management
- 🚀 **Cache Purging**: Clear all cache or specific files for faster deployments
- 🔧 **Development Mode**: Toggle dev mode to bypass cache during development

### SSL/TLS Security
- 🔒 **SSL Settings**: View and manage SSL/TLS configuration
- 🛡️ **SSL Modes**: Update SSL mode (Off, Flexible, Full, Full Strict)

### Zone Configuration
- ⚙️ **Zone Settings**: View and modify all zone-level settings
- 🎯 **Specific Settings**: Get/update individual settings like security level, browser checks

### Firewall Security
- 🛡️ **Firewall Rules**: Create, update, delete, and list security rules
- 🚫 **IP Blocking**: Block specific IP addresses or IP ranges
- 🌍 **Country Blocking**: Block or challenge traffic from specific countries
- 🤖 **Bot Protection**: Challenge suspicious traffic and block malicious bots

### Production-Ready Features
- 🛡️ **Input Validation**: Comprehensive parameter validation with clear error messages
- 📊 **Structured Logging**: JSON-formatted logs with configurable levels
- ⚙️ **Configuration Management**: Environment-based configuration with validation
- 🚨 **Error Handling**: Custom error classes with proper JSON-RPC error codes
- 🎯 **Type Safety**: Full TypeScript support with strict typing
- 📖 **JSON-RPC 2.0**: Complete MCP protocol compliance

## 📦 Installation

### Option 1: NPM Package (Recommended)

```bash
# Install globally
npm install -g @kappa/cloudflare-mcp

# Or install locally
npm install @kappa/cloudflare-mcp
```

### Option 2: From Source

```bash
git clone https://git.actions.it.com/kappa/cloudflare-mcp.git
cd cloudflare-mcp
npm install
npm run build
```

## 🔧 Configuration

### Environment Variables

```bash
# Required
export CF_API_TOKEN="your_cloudflare_api_token"

# Optional
export LOG_LEVEL="INFO"          # DEBUG, INFO, WARN, ERROR (default: INFO)
export REQUEST_TIMEOUT="30000"   # Request timeout in ms (default: 30000)
export MAX_RETRIES="3"          # Max API retries (default: 3)
```

### MCP Client Configuration

```json
{
  "mcpServers": {
    "cloudflare": {
      "command": "cloudflare-mcp",
      "args": [],
      "env": {
        "CF_API_TOKEN": "your_cloudflare_api_token",
        "LOG_LEVEL": "DEBUG"
      }
    }
  }
}

# Alternative with shorter command name
{
  "mcpServers": {
    "cloudflare": {
      "command": "cf-mcp",
      "args": [],
      "env": {
        "CF_API_TOKEN": "your_cloudflare_api_token"
      }
    }
  }
}
```

## 🛠️ Available MCP Tools

| Tool Name | Description | Parameters | Validation |
|-----------|-------------|------------|------------|
| **DNS Management** ||||
| `list_dns_records` | List DNS records for a domain | `domain`, `record_type?` | Domain format, record type enum |
| `create_dns_record` | Create a new DNS record | `domain`, `type`, `name`, `content`, `proxied?`, `ttl?` | All parameters validated |
| `delete_dns_record` | Delete a DNS record by ID | `domain`, `record_id` | Domain format, record ID format |
| `search_dns_records` | Search records across all zones | `record_name` | Record name format |
| `add_zone` | Add a domain to Cloudflare | `domain` | Domain format validation |
| `delete_zone` | Remove a domain from Cloudflare | `domain` | Domain format validation |
| `list_zones` | List all domains in account | none | No validation needed |
| **Cache Management** ||||
| `purge_cache` | Purge cache for a domain | `domain`, `files?` | Domain format, URL validation |
| `toggle_dev_mode` | Toggle development mode | `domain`, `enabled` | Domain format, boolean validation |
| **SSL/TLS Management** ||||
| `get_ssl_settings` | Get SSL/TLS settings | `domain` | Domain format validation |
| `update_ssl_mode` | Update SSL mode | `domain`, `mode` | Domain format, SSL mode enum |
| **Zone Settings** ||||
| `get_zone_settings` | Get all zone settings | `domain` | Domain format validation |
| `get_zone_setting` | Get specific zone setting | `domain`, `setting_name` | Domain and setting name validation |
| `update_zone_setting` | Update zone setting | `domain`, `setting_name`, `value` | All parameters validated |
| **Firewall Security** ||||
| `list_firewall_rules` | List all firewall rules | `domain` | Domain format validation |
| `create_firewall_rule` | Create firewall rule | `domain`, `expression`, `action`, `description?`, `priority?` | Expression and action validation |
| `update_firewall_rule` | Update firewall rule | `domain`, `rule_id`, `expression?`, `action?`, etc. | Rule ID UUID format validation |
| `delete_firewall_rule` | Delete firewall rule | `domain`, `rule_id` | Domain and rule ID validation |
| `get_firewall_rule` | Get firewall rule details | `domain`, `rule_id` | Domain and rule ID validation |

## 📝 Usage Examples

### List DNS Records with Type Filter
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_dns_records",
    "arguments": {
      "domain": "example.com",
      "record_type": "A"
    }
  }
}
```

### Create DNS Record with Validation
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "create_dns_record",
    "arguments": {
      "domain": "example.com",
      "type": "A",
      "name": "api",
      "content": "192.168.1.100",
      "proxied": true,
      "ttl": 300
    }
  }
}
```

### Error Response Example
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "error": {
    "code": -32602,
    "message": "Invalid domain format",
    "data": {
      "field": "domain"
    }
  }
}
```

### Cache Management Examples

#### Purge All Cache
```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "tools/call",
  "params": {
    "name": "purge_cache",
    "arguments": {
      "domain": "example.com"
    }
  }
}
```

#### Purge Specific Files
```json
{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "tools/call",
  "params": {
    "name": "purge_cache",
    "arguments": {
      "domain": "example.com",
      "files": [
        "https://example.com/style.css",
        "https://example.com/script.js"
      ]
    }
  }
}
```

#### Toggle Development Mode
```json
{
  "jsonrpc": "2.0",
  "id": 6,
  "method": "tools/call",
  "params": {
    "name": "toggle_dev_mode",
    "arguments": {
      "domain": "example.com",
      "enabled": true
    }
  }
}
```

### SSL/TLS Management Examples

#### Get SSL Settings
```json
{
  "jsonrpc": "2.0",
  "id": 7,
  "method": "tools/call",
  "params": {
    "name": "get_ssl_settings",
    "arguments": {
      "domain": "example.com"
    }
  }
}
```

#### Update SSL Mode
```json
{
  "jsonrpc": "2.0",
  "id": 8,
  "method": "tools/call",
  "params": {
    "name": "update_ssl_mode",
    "arguments": {
      "domain": "example.com",
      "mode": "full"
    }
  }
}
```

### Zone Settings Examples

#### Get All Zone Settings
```json
{
  "jsonrpc": "2.0",
  "id": 9,
  "method": "tools/call",
  "params": {
    "name": "get_zone_settings",
    "arguments": {
      "domain": "example.com"
    }
  }
}
```

#### Update Security Level
```json
{
  "jsonrpc": "2.0",
  "id": 10,
  "method": "tools/call",
  "params": {
    "name": "update_zone_setting",
    "arguments": {
      "domain": "example.com",
      "setting_name": "security_level",
      "value": "high"
    }
  }
}
```

### Firewall Security Examples

#### List Firewall Rules
```json
{
  "jsonrpc": "2.0",
  "id": 11,
  "method": "tools/call",
  "params": {
    "name": "list_firewall_rules",
    "arguments": {
      "domain": "example.com"
    }
  }
}
```

#### Block Specific IP Address
```json
{
  "jsonrpc": "2.0",
  "id": 12,
  "method": "tools/call",
  "params": {
    "name": "create_firewall_rule",
    "arguments": {
      "domain": "example.com",
      "expression": "ip.src eq 192.168.1.100",
      "action": "block",
      "description": "Block suspicious IP",
      "priority": 1
    }
  }
}
```

#### Block Country Traffic
```json
{
  "jsonrpc": "2.0",
  "id": 13,
  "method": "tools/call",
  "params": {
    "name": "create_firewall_rule",
    "arguments": {
      "domain": "example.com",
      "expression": "ip.geoip.country eq \"CN\"",
      "action": "challenge",
      "description": "Challenge traffic from China",
      "priority": 2
    }
  }
}
```

#### Challenge High Threat Score
```json
{
  "jsonrpc": "2.0",
  "id": 14,
  "method": "tools/call",
  "params": {
    "name": "create_firewall_rule",
    "arguments": {
      "domain": "example.com",
      "expression": "cf.threat_score gt 50",
      "action": "js_challenge",
      "description": "Challenge high threat score visitors",
      "priority": 5
    }
  }
}
```

#### Update Firewall Rule
```json
{
  "jsonrpc": "2.0",
  "id": 15,
  "method": "tools/call",
  "params": {
    "name": "update_firewall_rule",
    "arguments": {
      "domain": "example.com",
      "rule_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "action": "managed_challenge",
      "description": "Updated rule description"
    }
  }
}
```

## 🔐 Authentication

Create a Cloudflare API token with these permissions:
- **Zone**: Zone Settings, Zone Zone, Zone DNS
- **Zone**: Cache Purge (for cache management)
- **Zone**: Security (for firewall rules)
- **Account**: Account Account Details

Create your token at: https://dash.cloudflare.com/profile/api-tokens

## 🏗️ Development

### Project Structure
```
src/
├── cf-api.ts      # Cloudflare API client with error handling
├── config.ts      # Configuration management system
├── constants.ts   # Constants and enums
├── errors.ts      # Custom error classes
├── index.ts       # MCP server main logic
├── logger.ts      # Structured logging system
├── tools.ts       # MCP tool definitions
├── types.ts       # TypeScript type definitions
└── validator.ts   # Input validation system
```

### Build & Development Commands
```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Run server (development)
npm start

# Run with debug logging
LOG_LEVEL=DEBUG npm start
```

## 📊 Logging

The server provides structured JSON logging to stderr:

```json
{
  "timestamp": "2025-01-15T10:30:00.000Z",
  "level": "INFO",
  "message": "MCP Server initializing",
  "data": { "version": "1.0.3" }
}
```

Log levels: `DEBUG`, `INFO`, `WARN`, `ERROR`

## 🛡️ Error Handling

### Input Validation Errors
- Domain format validation
- DNS record type validation  
- Required parameter checks
- Data type validation

### API Error Handling
- Cloudflare API error mapping
- Network timeout handling
- Retry logic for transient failures
- Structured error responses

### JSON-RPC Error Codes
- `-32700`: Parse error
- `-32600`: Invalid Request
- `-32601`: Method not found
- `-32602`: Invalid params (validation errors)
- `-32603`: Internal error
- `-32002`: Not initialized

## 🔄 Protocol Support

- **JSON-RPC 2.0**: Full compliance with error handling
- **MCP Version**: `2024-11-05`
- **Transport**: stdio only
- **Authentication**: Bearer token
- **Validation**: Input parameter validation
- **Logging**: Structured logging to stderr

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes with tests
4. Ensure all validation passes
5. Update documentation
6. Submit a pull request

## 🔗 Links

- **Repository**: https://git.actions.it.com/kappa/cloudflare-mcp
- **NPM Package**: https://git.actions.it.com/api/packages/kappa/npm/
- **Cloudflare API**: https://developers.cloudflare.com/api/
- **MCP Protocol**: https://modelcontextprotocol.io/

## 📞 Support

For issues and questions:
- Open an issue on the repository
- Check the [MCP documentation](https://modelcontextprotocol.io/)
- Review Cloudflare API documentation

---

**Enterprise-grade MCP server for Cloudflare DNS management** 🚀