mcp-server-cloudflare

Scarmonit/mcp-server-cloudflare

3.2

If you are the rightful owner of mcp-server-cloudflare and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

Scarmonit MCP Server is a specialized server designed to facilitate communication with Claude.ai through SSE transport and provide streamable HTTP transport.

Tools
3
Resources
0
Prompts
0

Scarmonit MCP Server

A Model Context Protocol (MCP) server deployed on Cloudflare Workers for site monitoring, analytics, web diagnostics, and remote terminal agent management.

Features

  • Dual Transport Support: Both SSE (/sse) and Streamable HTTP (/mcp) endpoints
  • API Key Authentication: Optional security for production deployments
  • 12 Powerful Tools: Site health, DNS, SSL, performance, terminal agents, and more
  • Terminal Agent System: Connect and control remote agents via WebSocket
  • Cloudflare Workers: Globally distributed, low-latency execution
  • Durable Objects: Persistent state management with SQLite

Endpoints

EndpointDescription
/Server info and available tools
/healthHealth check (no auth required)
/sseServer-Sent Events transport for Claude.ai
/mcpStreamable HTTP transport
/agent/wsWebSocket endpoint for terminal agents
/api/agentsREST API for agent management

Available Tools

Terminal Agent Tools

ToolDescription
list_agentsList all connected terminal agents with status
terminal_executeExecute commands on a connected terminal agent
system_infoGet system information from a connected agent

Site Monitoring Tools

ToolDescription
get_cloudflare_statsCloudflare analytics (requests, bandwidth, cache, threats)
check_site_healthComprehensive site health check with timing metrics
dns_lookupDNS record lookup (A, AAAA, MX, TXT, NS, CNAME)
check_sslSSL/TLS certificate and security header check
measure_performancePage load performance testing with multiple runs
analyze_headersHTTP header security analysis with scoring
whois_lookupDomain WHOIS and DNS provider information

Utility Tools

ToolDescription
echoConnection test tool
server_infoServer capabilities and version info

Quick Start

1. Install Dependencies

npm install

2. Local Development

npm run dev

The server will be available at http://localhost:8787.

3. Test the Server

# Test local server
npm run test -- --local

# Test with custom URL
npm run test -- --url https://your-server.workers.dev

# Test with API key
npm run test -- --api-key your-api-key

4. Deploy to Cloudflare

# Set your Cloudflare credentials
export CLOUDFLARE_API_TOKEN=your-token
export CLOUDFLARE_ACCOUNT_ID=your-account-id

# Deploy
npm run deploy

Authentication

The server supports optional API key authentication. When API_KEY is set, all /sse and /mcp endpoints require authentication.

Setting the API Key

# Using wrangler CLI
npm run secret:set
# Then enter your API key when prompted

# Or via wrangler directly
wrangler secret put API_KEY

Using the API Key

Include the key in the Authorization header:

curl -H "Authorization: Bearer your-api-key" https://your-server.workers.dev/mcp

Usage with Claude.ai

Claude.ai Web (Custom Connector)

  1. Go to Settings > Connectors
  2. Click Add custom connector
  3. Enter your server URL: https://scarmonit-mcp-server.<subdomain>.workers.dev/sse
  4. Complete the authentication flow (if API key is set)

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "scarmonit": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://your-server.workers.dev/sse"]
    }
  }
}

Claude Code

claude mcp add --transport http scarmonit https://your-server.workers.dev/mcp

API Examples

Health Check

curl https://your-server.workers.dev/health
{
  "status": "healthy",
  "timestamp": "2025-11-30T12:00:00.000Z"
}

Server Info

curl https://your-server.workers.dev/
{
  "name": "scarmonit-mcp-server",
  "version": "5.5.0",
  "tools": ["list_agents", "terminal_execute", "system_info", "get_cloudflare_stats", "check_site_health", ...],
  "endpoints": {
    "sse": "/sse",
    "mcp": "/mcp",
    "ws": "/agent/ws",
    "api": "/api/agents"
  },
  "authentication": "disabled"
}

MCP Tool Call (Echo)

curl -X POST https://your-server.workers.dev/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "echo",
      "arguments": { "message": "Hello MCP!" }
    }
  }'

List Available Tools

curl -X POST https://your-server.workers.dev/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'

Terminal Agent System

The server includes a powerful Terminal Agent system that allows you to connect remote machines and execute commands via MCP tools.

Architecture

┌─────────────────┐     WebSocket      ┌─────────────────────────┐
│  Terminal Agent │◄──────────────────►│  Cloudflare Worker      │
│  (Your Machine) │                    │  (Durable Object)       │
└─────────────────┘                    └───────────┬─────────────┘
                                                   │
                                                   │ MCP Protocol
                                                   ▼
                                       ┌─────────────────────────┐
                                       │  Claude / MCP Client    │
                                       └─────────────────────────┘

Connecting a Terminal Agent

Terminal agents connect via WebSocket to the /agent/ws endpoint. Here's a Node.js client example:

// terminal-agent-client.js
const WebSocket = require('ws');

const ws = new WebSocket('wss://your-server.workers.dev/agent/ws');

ws.on('open', () => {
  // Register the agent
  ws.send(JSON.stringify({
    type: 'agent:register',
    name: 'My Terminal Agent',
    capabilities: ['terminal_execute', 'system_info'],
    platform: process.platform,
    hostname: require('os').hostname(),
  }));
});

ws.on('message', async (data) => {
  const msg = JSON.parse(data);

  switch (msg.type) {
    case 'agent:registered':
      console.log(`Registered as: ${msg.agentId}`);
      break;

    case 'tool:execute':
      // Handle tool execution request
      if (msg.tool === 'terminal_execute') {
        const { exec } = require('child_process');
        exec(msg.args.command, { cwd: msg.args.cwd }, (error, stdout, stderr) => {
          ws.send(JSON.stringify({
            type: 'tool:result',
            requestId: msg.requestId,
            result: { stdout, stderr, exitCode: error?.code ?? 0 },
          }));
        });
      }
      break;

    case 'heartbeat:ack':
      // Heartbeat acknowledged
      break;
  }
});

// Send heartbeat every 30 seconds
setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'heartbeat' }));
  }
}, 30000);

Terminal Agent REST API

List Connected Agents
curl -H "Authorization: Bearer your-api-key" \
  https://your-server.workers.dev/api/agents
{
  "totalAgents": 1,
  "agents": [
    {
      "id": "agent-1234567890-abc123",
      "name": "My Terminal Agent",
      "capabilities": ["terminal_execute", "system_info"],
      "connectedAt": "2025-01-15T10:30:00.000Z",
      "lastSeen": "2025-01-15T10:35:00.000Z",
      "platform": "linux",
      "hostname": "my-server"
    }
  ],
  "timestamp": "2025-01-15T10:35:30.000Z"
}
Execute Command on Agent
curl -X POST -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  https://your-server.workers.dev/api/agents/agent-1234567890-abc123/execute \
  -d '{
    "tool": "terminal_execute",
    "args": {
      "command": "ls -la",
      "cwd": "/home/user"
    }
  }'
{
  "success": true,
  "result": {
    "stdout": "total 48\ndrwxr-xr-x 5 user user 4096 Jan 15 10:30 .\n...",
    "stderr": "",
    "exitCode": 0
  }
}

Using Terminal Tools via MCP

Once agents are connected, you can use the terminal tools through MCP:

# List connected agents
curl -X POST https://your-server.workers.dev/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "list_agents",
      "arguments": {}
    }
  }'

# Execute command on first available agent
curl -X POST https://your-server.workers.dev/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "terminal_execute",
      "arguments": {
        "command": "uname -a"
      }
    }
  }'

Security Considerations

⚠️ Important: The terminal agent system allows remote command execution. Ensure you:

  1. Always use API key authentication in production
  2. Validate and sanitize commands in your terminal agent client
  3. Use allowlists for permitted commands if possible
  4. Run agents with minimal privileges (non-root user, restricted shell)
  5. Monitor agent connections and command execution logs
  6. Use secure WebSocket (wss://) in production

Development

Project Structure

├── src/
│   ├── index.ts          # Main server implementation & MCP tools
│   └── terminal-agent.ts # Terminal Agent Durable Object
├── scripts/
│   └── test-server.mjs   # Test script
├── wrangler.toml         # Cloudflare Workers config
├── tsconfig.json         # TypeScript config
└── package.json

Available Scripts

ScriptDescription
npm run devStart local development server
npm run deployDeploy to Cloudflare Workers
npm run testRun test suite
npm run tailStream live logs from deployed worker
npm run typesGenerate TypeScript types for bindings
npm run secret:setSet the API_KEY secret

Adding a New Tool

this.server.tool(
  "tool_name",
  "Description of what the tool does",
  {
    param1: z.string().describe("Parameter description"),
    param2: z.number().optional().describe("Optional parameter"),
  },
  async ({ param1, param2 }) => {
    // Tool implementation
    return {
      content: [{
        type: "text",
        text: JSON.stringify({ result: "data" }, null, 2),
      }],
    };
  }
);

GitHub Actions

The repository includes a CI/CD workflow that:

  1. Type checks the TypeScript code on every push/PR
  2. Deploys to Cloudflare Workers on push to main or Scarmonit branches

Required Secrets

Set these in your GitHub repository settings:

  • CLOUDFLARE_API_TOKEN - Cloudflare API token with Workers permissions
  • CLOUDFLARE_ACCOUNT_ID - Your Cloudflare account ID
  • CLOUDFLARE_SUBDOMAIN (optional) - Your workers.dev subdomain for health checks

License

MIT