Skip to content

jmbish04/core-cloudflare-management-api

Repository files navigation

πŸ”₯ Cloudflare Management API

A comprehensive Cloudflare Worker that serves as a secure proxy and management layer over the Cloudflare TypeScript SDK. Features OpenAPI documentation, audit logging, MCP support, RPC endpoints, and an AI agent interface.

✨ Features

  • πŸ” Secure Authentication: Bearer token authentication with audit logging
  • πŸ“Š Comprehensive Audit Logging: All requests logged to D1 database with Analytics Engine integration
  • πŸ“– OpenAPI 3.1 Documentation: Complete API documentation with interactive Swagger UI
  • πŸ”Œ Model Context Protocol (MCP): Integration with AI assistants (Claude, Cursor, Copilot, etc.)
  • πŸ€– AI Agent Interface: Natural language interface for managing infrastructure
  • ⚑ RPC Endpoints: JSON-RPC 2.0 support for Worker-to-Worker service bindings
  • πŸ”„ Workflow Automation: High-level "easy button" flows for common tasks
  • πŸ—οΈ Full Cloudflare Coverage: Workers, Pages, DNS, Tunnels, Access, Storage (D1, KV, R2), and more

πŸš€ Quick Start

Prerequisites

  • Wrangler CLI installed
  • Cloudflare account with API token
  • Node.js 18+ installed

Installation

  1. Clone the repository

    git clone <your-repo-url>
    cd core-cloudflare-management-api
  2. Install dependencies

    npm install
  3. Create D1 database

    wrangler d1 create audit-logs-db

    Update wrangler.toml with your database ID:

    [[d1_databases]]
    binding = "AUDIT_LOGS_DB"
    database_name = "audit-logs-db"
    database_id = "your-database-id-here"
  4. Run migrations

    npm run db:migrate
  5. Set secrets

    wrangler secret put CLOUDFLARE_API_TOKEN
    # Enter your Cloudflare API token
    
    wrangler secret put CLOUDFLARE_ACCOUNT_ID
    # Enter your Cloudflare account ID
    
    wrangler secret put WORKER_API_KEY
    # Enter a secure API key for accessing this proxy API
  6. Deploy

    npm run deploy

πŸ“š API Documentation

Once deployed, visit:

  • Interactive Docs: https://your-worker.workers.dev/docs
  • OpenAPI Spec: https://your-worker.workers.dev/openapi.json
  • HTML Documentation: Deploy public/index.html to Cloudflare Pages or a CDN

πŸ”‘ Authentication

All API requests require a Bearer token in the Authorization header:

curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://your-worker.workers.dev/api/cloudflare-sdk/workers/scripts

πŸ“– API Endpoints

Core SDK Routes

All Cloudflare SDK operations are available under /api/cloudflare-sdk/:

  • Workers: /api/cloudflare-sdk/workers/*
  • Pages: /api/cloudflare-sdk/pages/*
  • DNS: /api/cloudflare-sdk/dns/*
  • Tunnels: /api/cloudflare-sdk/tunnels/*
  • Access: /api/cloudflare-sdk/access/*
  • Tokens: /api/cloudflare-sdk/tokens/*
  • Zones: /api/cloudflare-sdk/zones/*
  • Storage: /api/cloudflare-sdk/storage/* (D1, KV, R2)

Workflow Automation

High-level workflows available under /api/flows/:

Create Worker with GitHub CI/CD

curl -X POST https://your-worker.workers.dev/api/flows/workers/create_with_github_cicd \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "workerName": "my-worker",
    "githubOwner": "myorg",
    "githubRepo": "my-repo",
    "productionBranch": "main",
    "buildCommand": "npm run build"
  }'

Setup All Bindings (Super Easy Button!)

curl -X POST https://your-worker.workers.dev/api/flows/advanced/setup-bindings \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "my-app",
    "bindings": ["kv", "d1", "r2", "analytics_engine"]
  }'

This creates all bindings with consistent naming and returns a ready-to-use wrangler.toml!

AI Agent

Natural language interface at /agent:

curl -X POST https://your-worker.workers.dev/agent \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "List all my workers and create a KV namespace called sessions"
  }'

Model Context Protocol (MCP)

MCP endpoint at /mcp for integration with AI assistants.

Claude Desktop Setup

Add to ~/Library/Application Support/Claude/config.json:

{
  "mcpServers": {
    "cloudflare": {
      "url": "https://your-worker.workers.dev/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_API_KEY"
      }
    }
  }
}

Cursor Setup

Add to Cursor settings (Settings β†’ MCP):

{
  "mcp.servers": {
    "cloudflare": {
      "url": "https://your-worker.workers.dev/mcp",
      "apiKey": "YOUR_API_KEY"
    }
  }
}

GitHub Copilot Setup

In repository settings, add to .github/copilot-mcp.json:

{
  "servers": [{
    "name": "cloudflare",
    "url": "https://your-worker.workers.dev/mcp",
    "auth": {
      "type": "bearer",
      "token": "$CLOUDFLARE_API_KEY"
    }
  }]
}

RPC Endpoints

JSON-RPC 2.0 endpoint at /rpc/:method:

curl -X POST https://your-worker.workers.dev/rpc/workers.list \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id": 1}'

Service Binding Example

# wrangler.toml
[[services]]
binding = "CLOUDFLARE_API"
service = "core-cloudflare-manager-api"
// Your Worker code
export default {
  async fetch(request: Request, env: Env) {
    const workers = await env.CLOUDFLARE_API.listWorkers();
    return Response.json(workers);
  }
}

πŸ—„οΈ Audit Logging

All API requests are automatically logged to D1 and Analytics Engine. Query logs via:

curl -X GET "https://your-worker.workers.dev/api/audit-logs?page=1&limit=50" \
  -H "Authorization: Bearer YOUR_API_KEY"

πŸ”„ Workflow Examples

Example 1: Deploy a Complete Application Stack

// Create all bindings for your app
const response = await fetch('https://your-worker.workers.dev/api/flows/advanced/setup-bindings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    appName: 'todo-app',
    bindings: ['kv', 'd1', 'r2']
  })
});

const { wranglerToml } = await response.json();
// Copy wranglerToml to your project!

Example 2: Setup Worker with GitHub CI/CD

curl -X POST https://your-worker.workers.dev/api/flows/workers/create_with_github_cicd \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "workerName": "api-gateway",
    "githubOwner": "mycompany",
    "githubRepo": "api-gateway",
    "productionBranch": "production",
    "buildCommand": "npm run build",
    "rootDir": "/"
  }'

Example 3: Using the AI Agent

curl -X POST https://your-worker.workers.dev/agent \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Create a D1 database called users-db, a KV namespace called sessions, and an R2 bucket called uploads"
  }'

πŸ—οΈ Project Structure

core-cloudflare-management-api/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts                    # Main entry point
β”‚   β”œβ”€β”€ types.ts                    # Shared types and schemas
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”œβ”€β”€ auth.ts                 # Bearer token authentication
β”‚   β”‚   └── auditLog.ts             # Audit logging middleware
β”‚   └── routes/
β”‚       β”œβ”€β”€ agent.ts                # AI agent endpoint
β”‚       β”œβ”€β”€ sdk/
β”‚       β”‚   β”œβ”€β”€ index.ts            # SDK router
β”‚       β”‚   β”œβ”€β”€ workers.ts          # Workers management
β”‚       β”‚   β”œβ”€β”€ pages.ts            # Pages management
β”‚       β”‚   β”œβ”€β”€ dns.ts              # DNS management
β”‚       β”‚   β”œβ”€β”€ tunnels.ts          # Tunnels management
β”‚       β”‚   β”œβ”€β”€ tokens.ts           # API tokens management
β”‚       β”‚   β”œβ”€β”€ access.ts           # Zero Trust Access
β”‚       β”‚   β”œβ”€β”€ zones.ts            # Zones management
β”‚       β”‚   └── storage.ts          # D1, KV, R2 management
β”‚       └── flows/
β”‚           β”œβ”€β”€ index.ts            # Basic workflows
β”‚           └── advanced.ts         # Advanced workflows
β”œβ”€β”€ migrations/
β”‚   └── 0001_create_audit_logs.sql  # D1 migration
β”œβ”€β”€ public/
β”‚   └── index.html                  # Documentation landing page
β”œβ”€β”€ wrangler.toml                   # Worker configuration
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── README.md

πŸ› οΈ Development

Cloudflare API Schemas

This project uses a git submodule to maintain a link to the official Cloudflare API schemas repository. The schemas are located in api-schemas-main/.

Initial Setup (for new clones):

# Clone with submodules
git clone --recurse-submodules <repo-url>

# Or if already cloned, initialize submodules
git submodule update --init --recursive

Update to Latest Schemas:

# Update to latest version from Cloudflare's repository
# This automatically backs up the previous version with a date stamp
npm run update:schemas

# Or manually:
git submodule update --remote api-schemas-main
git add api-schemas-main api-schemas-backups
git commit -m "chore: Update Cloudflare API schemas"

Version Backups: When updating schemas, the previous version is automatically backed up to api-schemas-backups/ with a timestamp:

  • Format: api-schemas-backups/api-schemas-YYYY-MM-DD_HH-MM-SS/
  • Each backup includes a .backup-metadata.txt file with commit information
  • This allows you to reference or restore previous schema versions if needed

Using the Schemas: The OpenAPI schemas are available at:

  • api-schemas-main/openapi.json - Full OpenAPI 3.1 specification (current version)
  • api-schemas-main/openapi.yaml - YAML format (current version)
  • api-schemas-main/common.yaml - Common schema definitions (current version)
  • api-schemas-backups/ - Historical versions with date stamps

Local Development

npm run dev

Access the API at http://localhost:8787

Run Migrations Locally

npm run db:migrate

Type Checking

npm run type-check

πŸ“Š Analytics & Observability

The API logs detailed metrics to:

  1. D1 Database: Full request/response audit trail
  2. Analytics Engine: Performance metrics and observability data

Query Analytics Engine via Cloudflare's GraphQL API or dashboard.

πŸ”’ Security

  • Authentication: Bearer token required for all endpoints (except /health)
  • Audit Logging: Every request logged with timestamp, IP, headers, body, and response
  • Secrets Management: All sensitive data stored in Worker secrets
  • CORS: Configurable CORS headers
  • Input Validation: Zod schemas for all requests

🚧 Roadmap

  • Durable Objects for agent conversation state
  • Workflows for multi-step operations
  • Queues for async task processing
  • Workers AI integration for enhanced agent capabilities
  • WebSocket support for real-time updates
  • GraphQL API layer
  • Rate limiting and quotas
  • Multi-account support

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

πŸ“ License

MIT License - see LICENSE file for details

πŸ™ Acknowledgments

Built with:

πŸ“ž Support


Made with ❀️ for the Cloudflare Developer Community

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •