Cloudflare WAF MCP Server
Provides tools to manage Cloudflare WAF: list accounts, zones, rulesets, and security events; create, update, delete, and toggle custom WAF rules; query attack analytics; and suggest protective rules based on observed attack patterns.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Cloudflare WAF MCP Server
A reference implementation of a Model Context Protocol (MCP) server for managing Cloudflare Web Application Firewall (WAF) rules. Built on Cloudflare Workers with Durable Objects for stateful session management.
This project demonstrates how to build MCP servers that give AI assistants secure, authenticated access to cloud infrastructure APIs.
Not Production Ready: This is a reference implementation for educational purposes only. It has not been audited for security vulnerabilities and should not be deployed to production environments without thorough review and hardening.
Learning Resource: This repository serves as an educational example for developers building their own MCP servers. See the Architecture and Extending the Server sections for implementation patterns.
Features
Read Operations: List accounts, zones, rulesets, and security events
Write Operations: Create, update, delete, and toggle WAF rules
Analytics: Query security events, attack summaries, and top attacked paths
AI-Powered Suggestions: Analyze attack patterns and suggest protective rules
Built-in Prompts: Pre-configured workflows for common WAF operations
Secure Authentication: API token-based auth with per-user isolation via Durable Objects
Related MCP server: Check Point CloudGuard WAF MCP Server
Architecture
┌─────────────────────────────────────────────────────────────────────┐
│ Claude Desktop / MCP Client │
└─────────────────────────────────────────────────────────────────────┘
│
│ MCP Protocol (SSE/HTTP)
▼
┌─────────────────────────────────────────────────────────────────────┐
│ Cloudflare Workers Edge │
│ ┌───────────────────────────────────────────────────────────────┐ │
│ │ WAF MCP Server │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Tools │ │ Prompts │ │ Resources │ │ │
│ │ │ - read ops │ │ - audit │ │ - waf://overview │ │ │
│ │ │ - write ops │ │ - builder │ │ - waf://guidance │ │ │
│ │ │ - analytics │ │ - incident │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌───────────┴───────────┐ │
│ ▼ ▼ │
│ ┌─────────────────────────┐ ┌─────────────────────────────────┐ │
│ │ Durable Object │ │ Cloudflare API v4 │ │
│ │ (Session & Auth State) │ │ (REST + GraphQL Analytics) │ │
│ └─────────────────────────┘ └─────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘Key Components
Component | Purpose | Implementation |
MCP Server | Protocol handling, tool/prompt/resource registration |
|
Durable Object | Per-user session state, token storage |
|
Cloudflare API Client | REST and GraphQL API calls |
|
Tools | Executable actions (read/write/analytics) |
|
Prompts | Guided workflow templates |
|
Resources | Static context and documentation |
|
Quick Start
Prerequisites
Node.js 18+
A Cloudflare account
1. Clone and Install
git clone https://github.com/Gryczka/cloudflare-basic-waf-mcp-sample.git
cd cloudflare-basic-waf-mcp-sample
npm install2. Create a Cloudflare API Token
Go to the Cloudflare Dashboard
Navigate to My Profile > API Tokens
Click Create Token
Create a custom token with these permissions:
Resource | Permission | Required For |
Account Settings | Read | Listing accounts |
Zone | Read | Listing zones and zone details |
Firewall Services | Edit | Reading and writing WAF rules |
Analytics | Read | Security events and attack data |
User Details | Read | Token validation |
3. Run Locally
npm run devThe server starts at http://localhost:8788. Visit the root URL to see setup instructions.
4. Test with MCP Inspector
npx @modelcontextprotocol/inspector@latestEnter http://localhost:8788/mcp as the endpoint and provide your API token when prompted.
5. Connect with Claude Desktop
Add to your Claude Desktop configuration:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"cloudflare-waf": {
"command": "npx",
"args": ["mcp-remote", "http://localhost:8788/mcp"]
}
}
}6. Deploy to Production
# Set your account ID
export CLOUDFLARE_ACCOUNT_ID="your-account-id"
npm run deployThen update your Claude Desktop config to use the production URL:
https://waf-mcp-server.<your-subdomain>.workers.dev/mcpAvailable Tools
Read Operations
Tool | Description |
| List all Cloudflare accounts you have access to |
| List zones (domains) in an account |
| Get detailed information about a specific zone |
| List custom WAF rules for a zone |
| List managed WAF rulesets (OWASP, Cloudflare Managed, etc.) |
| Get a specific ruleset with all its rules |
| List all rulesets across all phases |
| List account-level rulesets (Enterprise) |
Write Operations
Tool | Description |
| Create a new custom WAF rule |
| Update an existing rule's expression, action, or status |
| Delete a custom rule |
| Quickly enable or disable a rule |
Analytics
Tool | Description |
| Query recent security events (blocks, challenges, etc.) |
| Get aggregated attack data by action, source, and country |
| Identify the most frequently attacked URL paths |
| Analyze patterns and suggest protective rules |
Built-in Prompts
The server includes pre-configured prompts for common WAF workflows. Prompts provide guided, multi-step interactions for complex tasks.
Prompt | Description | Use Case |
| Comprehensive security posture review | Regular security assessments |
| Interactive rule creation workflow | Creating rules for specific threats |
| Attack investigation and mitigation | Active incident handling |
| Best practices and coverage review | Security compliance audits |
Using Prompts
In Claude Desktop, you can invoke prompts directly:
Use the security_audit prompt to review my zone example.comOr prompts may be suggested contextually based on your conversation.
Example Conversations
Security Audit
User: Audit the security posture of my main website
Claude: I'll perform a comprehensive security audit of your zone.
[Uses list_custom_rules, list_managed_rulesets, get_security_events]
Security Audit Summary for example.com:
Current Protection:
✓ 12 custom rules active
✓ Cloudflare Managed Ruleset deployed
✓ OWASP Core Ruleset enabled
Recent Activity (24h):
- 1,247 requests blocked
- 89 challenges issued
- Top threat: SQL injection attempts (43%)
Recommendations:
1. Add rate limiting for /api/* endpoints (high traffic, no protection)
2. Enable Bot Management for login pages
3. Consider geo-blocking for countries with no legitimate trafficCreating a Protective Rule
User: Block all traffic from country X to our admin panel
Claude: I'll create a custom WAF rule for that protection.
[Uses create_custom_rule tool]
Created rule successfully:
- Name: Block Country X Admin Access
- Expression: (ip.geoip.country eq "XX") and (http.request.uri.path contains "/admin")
- Action: Block
- Status: Enabled
The rule is now active. All requests from country X to /admin/* paths will be blocked.
Would you like me to also add logging for this rule to monitor blocked attempts?Incident Response
User: We're seeing a spike in 403 errors, investigate
Claude: I'll analyze recent security events to understand the pattern.
[Uses get_security_events, get_attack_summary, get_top_attacked_paths]
Incident Analysis:
Attack Pattern Detected:
- 2,847 requests blocked in the last hour (10x normal)
- Source: 73% from AS12345 (Example Hosting Provider)
- Target: /api/v1/users endpoint
- Signature: Credential stuffing attack (multiple failed auth attempts)
Immediate Actions Available:
1. Create rate limiting rule for /api/v1/users
2. Block the specific ASN temporarily
3. Enable managed challenge for suspicious requests
Shall I implement any of these mitigations?Project Structure
cloudflare-basic-waf-mcp-sample/
├── src/
│ ├── index.ts # Entry point, routing, Durable Object definition
│ ├── cloudflare-api.ts # Cloudflare API client (REST + GraphQL)
│ ├── validation.ts # Zod schemas for input validation
│ ├── tools/
│ │ ├── waf-read.ts # Read operation tools
│ │ ├── waf-write.ts # Write operation tools
│ │ └── waf-analytics.ts # Analytics and events tools
│ ├── prompts/
│ │ └── index.ts # MCP prompts for guided workflows
│ └── resources/
│ └── index.ts # MCP resources for context
├── docs/
│ └── use-cases.md # Real-world usage examples
├── .github/
│ └── workflows/ci.yml # GitHub Actions CI
├── wrangler.jsonc # Cloudflare Workers configuration
├── tsconfig.json # TypeScript configuration
├── LICENSE # MIT license
└── package.jsonExtending the Server
This project is designed as a learning resource. Here's how to extend it:
Adding a New Tool
Tools are the primary way MCP servers expose functionality. Each tool has a name, description, input schema, and handler.
// src/tools/my-tools.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { CloudflareApi } from "../cloudflare-api";
export function registerMyTools(server: McpServer, getApi: () => CloudflareApi) {
server.tool(
"my_custom_tool", // Tool name
"Description shown to the AI assistant", // Description
{
zoneId: z.string().describe("The zone ID"), // Input schema with Zod
option: z.boolean().optional(),
},
async ({ zoneId, option }) => { // Handler function
const api = getApi();
const result = await api.someMethod(zoneId);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}],
};
},
);
}Then register in src/index.ts:
import { registerMyTools } from "./tools/my-tools";
// In WafMCP.init():
registerMyTools(this.server, getApi);Adding a New Prompt
Prompts are templates for guided workflows. They can include arguments and return structured conversation starters.
// src/prompts/index.ts
server.prompt(
"my_workflow",
"Guided workflow for specific task",
{
zone: z.string().describe("Zone to analyze"),
depth: z.enum(["quick", "thorough"]).optional(),
},
async ({ zone, depth = "quick" }) => ({
messages: [
{
role: "user",
content: {
type: "text",
text: `Perform a ${depth} analysis of zone ${zone}.
Start by listing current rules, then analyze recent events,
and provide recommendations.`,
},
},
],
}),
);Adding a New Resource
Resources provide static or dynamic context that the AI can reference.
// src/resources/index.ts
server.resource(
"waf://expression-syntax",
"Cloudflare WAF expression syntax reference",
async () => ({
contents: [{
uri: "waf://expression-syntax",
mimeType: "text/markdown",
text: `# WAF Expression Syntax
## Fields
- \`ip.src\` - Client IP address
- \`http.request.uri.path\` - Request path
- \`http.user_agent\` - User agent string
...`,
}],
}),
);Security Considerations
Authentication Model
Per-user isolation: Each authenticated user gets their own Durable Object instance
Token validation: API tokens validated against Cloudflare
/userendpoint before useNo stored secrets: The server itself stores no secrets; users provide their own tokens
Securing the MCP Endpoint in Production (Recommended)
By default, the /mcp endpoint is publicly accessible. While users can only access data their API token permits, you may want to restrict who can connect to your MCP server entirely.
Cloudflare Access is the recommended solution for production deployments. It adds identity-based authentication before users can reach your MCP endpoint.
Setting Up Cloudflare Access
Navigate to Zero Trust Dashboard
Go to Cloudflare Zero Trust
Select your account
Create an Access Application
Go to Access > Applications
Click Add an application
Select Self-hosted
Configure the Application
Application name: WAF MCP Server Session duration: 24 hours (or your preference) Application domain: - Subdomain: waf-mcp-server (your worker subdomain) - Domain: <your-account>.workers.dev - Path: /mcpCreate an Access Policy
Define who can access your MCP server:
Policy Type
Example Configuration
Email
Allow specific emails (
you@company.com)Email Domain
Allow your organization (
@company.com)GitHub Organization
Allow org members
Google Workspace
Allow workspace users
Service Token
For programmatic access
Example policy for personal use:
Policy name: Personal Access Action: Allow Include: - Selector: Emails - Value: your-email@example.comConfigure MCP Client for Access
When connecting through Cloudflare Access, you'll need to authenticate first. For Claude Desktop with
mcp-remote:{ "mcpServers": { "cloudflare-waf": { "command": "npx", "args": [ "mcp-remote", "https://waf-mcp-server.<account>.workers.dev/mcp" ] } } }The first connection will open a browser for Access authentication. After authenticating, your session is cached.
For Service Token authentication (headless/automated):
# Create a service token in Zero Trust > Access > Service Auth # Then use the token headers in your client CF-Access-Client-Id: <service-token-id> CF-Access-Client-Secret: <service-token-secret>
Alternative: Cloudflare Tunnel with Access
For more advanced setups, you can run the MCP server locally and expose it through a Cloudflare Tunnel with Access policies:
# Install cloudflared
brew install cloudflared # or appropriate installer
# Create a tunnel
cloudflared tunnel create waf-mcp
# Configure tunnel (in ~/.cloudflared/config.yml)
tunnel: <tunnel-id>
credentials-file: ~/.cloudflared/<tunnel-id>.json
ingress:
- hostname: waf-mcp.yourdomain.com
service: http://localhost:8788
- service: http_status:404
# Run the tunnel
cloudflared tunnel run waf-mcpThen apply Access policies to waf-mcp.yourdomain.com in the Zero Trust dashboard.
Access + API Token: Defense in Depth
With Cloudflare Access enabled, your MCP server has two layers of authentication:
Cloudflare Access: Verifies the user's identity before reaching the endpoint
API Token: Validates the user has Cloudflare API permissions for the requested operations
This provides defense in depth—even if someone bypasses Access, they still need a valid API token to access any data.
Input Validation
All inputs are validated using Zod schemas with:
Regex patterns for Cloudflare IDs (32-character hex strings)
Length limits on string fields
Enum restrictions for action types
Error Handling
Error messages are sanitized to prevent information disclosure:
Bearer tokens are redacted
Long hex strings (IDs) are redacted
Email addresses and IPs are redacted
Messages are truncated to 200 characters
Security Headers
The info page includes security headers:
X-Content-Type-Options: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockContent-Security-Policy
Development
Commands
npm run dev # Start local development server (port 8788)
npm run deploy # Deploy to Cloudflare Workers
npm run type-check # Run TypeScript type checking
npm run cf-typegen # Generate Cloudflare Workers typesTesting Locally
Start the dev server:
npm run devUse MCP Inspector:
npx @modelcontextprotocol/inspector@latestConnect to
http://localhost:8788/mcpProvide your Cloudflare API token when prompted
Code Style
The project uses Prettier for formatting:
npx prettier --write .License
This project is licensed under the MIT License - see the LICENSE file for details.
Resources
Related Projects
cloudflare/agents - Build AI agents on Cloudflare
cloudflare/mcp-server-cloudflare - General Cloudflare MCP server
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
MCP gateway with runtime security policy, tool-call-level control, and audit of agent actions.
MCP gateway: one connection for your AI apps, with tool policies, PII redaction and audit logs.
Zero-secret MCP gateway for AI agents: risk-scored, audited calls with human-in-the-loop approval.
An MCP gateway for teams deploying AI tools at scale to employee-facing and headless agents.
Related MCP Servers
- AlicenseBqualityCmaintenanceEnables AI assistants to query and analyze Imperva Cloud WAF configurations through natural language, supporting retrieval of sites, domains, policies, and rules.48Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to manage Check Point CloudGuard WAF configuration through natural language, including assets, profiles, practices, and policy.1Apache 2.0
- AlicenseNot gradedqualityCmaintenanceEnables AI assistants to manage Magento 2 / Adobe Commerce products, stock, orders, and customers through 12 read/write MCP tools with secure, audited access.AGPL 3.0
- AlicenseAqualityBmaintenanceEnables AI assistants to perform authorized web security assessments through MCP tools and a guided review prompt, including passive and full scans, WAF detection, remediation fixes, report export, triage, scan comparison, and proof-of-control verification.1250 PyPI5MIT