Cloudflare Security MCP
Technical walkthrough

An AI agent that reviews your Cloudflare security posture

A read-only MCP server, a hardened chat interface and a WAF analysis toolkit, built and run end to end on a home-lab single-board computer, behind Cloudflare Access.

MCP · Streamable HTTP Cloudflare Access + Tunnel Read-only by construction Workers AI Open WebUI 114 automated tests

Keys: ← → move · o overview · n notes · f fullscreen · p print to PDF. Hostnames and IDs in this deck are placeholders.

Why

The point is analysis, not API connectivity

Show, don't tell

Demonstrate how an agent can reason over a real Cloudflare configuration and produce findings a security engineer would trust.

Evidence first

Every finding carries severity, confidence and the exact evidence. No evidence, no finding. Unreadable data is reported as unavailable, never assumed insecure.

Read-only, deny by default

The server cannot change Cloudflare. Accounts and zones must be explicitly authorized. Secrets never reach the model.

5
MCP tools
13
zones · 2 accounts
9
independent security layers
114
automated tests
Architecture

The big picture

You browser · MCP client CLOUDFLARE EDGE WAF · managed rules+ scoped exceptions Cloudflare AccessManaged OAuth · Service Auth Tunnel ingressno inbound ports opened Workers AIOpenAI-compatible APImodel with tool calling cloudflaredtunnel host EDGE HOST · single-board computer · Docker MCP server :30335 read-only tools · TypeScriptverifies the Access JWT itself Chat UI :3040Open WebUI · MCP connectionpreloaded with a Service Token Inspector :6274MCP Inspector · test clientread-only config containers: non-root · no capabilities egress firewall: no LAN, no host services Cloudflare APIsREST + GraphQLread-only token HTTPS model calls tools via Access GET

Solid orange: the path of a user request. Dashed: server-side calls made by the chat UI. The MCP server is reached the same way by every client: through Access.

Components

Four things run on the edge host

PiecePublic name (placeholder)RoleAuth in front
MCP servermcp.example.com/mcpExposes 5 read-only tools over Streamable HTTP, statelessAccess (Managed OAuth for people, Service Auth for services) + JWT check in the app
Chat UImcp-chat.example.comOpen WebUI: natural-language interface; calls the model and the MCP toolsAccess, email-only policy + its own login
Inspectormcp-inspector.example.comOfficial MCP Inspector for calling tools by hand and debuggingAccess, email-only policy
Firewall rules(host)Containers cannot reach the LAN or host servicessystemd unit re-applies at boot

Not on the device

No LLM. Inference is done by Workers AI. The MCP server is independent of the model: any MCP-compatible client can use it.

Repeatable

Everything is in git: source, tests, compose files, firewall script, docs. Secrets live only in git-ignored files on the host.

Workflow

One question, end to end

"List my zones and give me the three highest-risk findings."

1 · BrowserOpens the chat hostname. WAF checks the request, Access asks for login, the tunnel forwards it to the chat container.
2 · Chat UISends the conversation and the tool list to the model on Workers AI.
3 · ModelDecides to call list_cloudflare_zones, then get_security_posture and inspect_dns_security for each zone.
4 · Chat UI → MCPEach tool call goes to the public MCP URL with Service Token headers, through Access and the tunnel.
5 · MCP serverVerifies the Access JWT and the Host header, applies the zone allowlist, rate limit and timeout, then calls Cloudflare read-only.
6 · Cloudflare APIReturns zone settings, DNS records, rulesets or GraphQL aggregates. Findings are computed with evidence and confidence.
7 · Model → YouSummarizes: a ranked list with affected zones, impact and fixes. Fixes are done by a human in the dashboard.
MCP server

Five tools, two phases

ToolInputWhat it returns
list_cloudflare_zonesnoneOnly authorized zones: name, id, account, status, plan
inspect_dns_securityzoneDNS records (IPs masked on unproxied A/AAAA) + DNSSEC; findings: unproxied origins, no CAA, DNSSEC off
get_security_posturezoneTLS/SSL and core settings: SSL mode, minimum TLS, HTTPS rewrites, security level…
inspect_waf_rules phase 2zoneManaged rules, overrides, exceptions, custom rules, rate limiting. Flags broad skip rules, weakened overrides, log-only rules
analyze_waf_events phase 2zone, hours, host?Events by action/source, top rules and targets, countries/ASNs, timeline. Flags possible false positives and spikes
Design choice. Tools return structured JSON with a limitations list. The model can only report what the data supports.
Trust

Findings carry severity and confidence

Confidence

✓confirmed · directly observed in an authoritative API responsefact
~recommendation · best practice, not evidence of a flawadvice
?unavailable · could not be evaluated (permission, plan)unknown

Severity

critical high medium low informational

Never fabricate. A missing rule is a recommendation, not a confirmed weakness, because protection may exist by default or at account level.

Example (shortened)

{
  "id": "tls-min-version-weak",
  "title": "Minimum TLS version allows outdated protocol (1.0)",
  "severity": "high",
  "confidence": "confirmed",
  "evidence": ["min_tls_version = 1.0"],
  "recommendation": "Raise to 1.2 or higher"
}

Heuristic findings are labeled as hints

{
  "id": "waf-possible-false-positive",
  "confidence": "recommendation",
  "evidence": ["Generic Rules - Template
    Injection - 2: 5 x managed_challenge,
    mostly POST app.example.com/api/…"]
}
Security

Nine independent layers

1Cloudflare Access in front of every hostname; Managed OAuth for people, Service Auth for machinesedge
2JWT verification in the app: signature via the team JWKS, issuer and audience checked; HTTP mode refuses to start without itapp
3Host / Origin guard against DNS rebinding: only listed hostnames acceptedapp
4Deny-by-default allowlist: authorized accounts and zone names/IDs, enforced in codescope
5Read-only client: GETs plus one POST to GraphQL analytics that refuses anything but plain queries; query text is never client-suppliedscope
6Input validation and guardrails: Zod schemas, per-tool rate limit, hard timeout, errors collapsed to safe messages, secrets redacted from logsapp
7Least-privilege tokens: read-only Cloudflare token; a separate Workers AI token for the chat; Service Token only for Accesscreds
8Container hardening: digest-pinned images, non-root, no capabilities, resource limits, no Docker socket or host mountshost
9Egress firewall: chat and Inspector containers cannot reach the LAN or host services; DNS via public resolvershost
Identity

Two ways through Access

People: Managed OAuth

  1. Client calls the MCP URL, gets a redirect plus www-authenticate metadata.
  2. Access acts as the OAuth 2.1 authorization server; user logs in with the identity provider.
  3. Access injects Cf-Access-Jwt-Assertion on every allowed request.
  4. The MCP server verifies that JWT before doing anything.

No OAuth code lives in the MCP server.

Services: Service Token

  1. Chat UI and Inspector call the MCP URL with CF-Access-Client-Id/Secret headers.
  2. A policy with action Service Auth (not Allow) matches the token.
  3. Access issues the same kind of JWT; the server verifies it.
Gotcha. An Allow policy with a service-token selector still demands an identity login, so token-only requests are redirected (302) to the login page.
Infrastructure

A single-board computer, Docker, one tunnel

Host

  • ARM64 board, always on
  • Docker Engine + Compose
  • Deploys by rsync + docker compose build/up
  • Previous image tagged for rollback

Networking

  • Existing Cloudflare Tunnel, connector on another host
  • One hostname route per service
  • Ports published on the LAN for the connector; unauthenticated MCP calls are rejected with 401
  • Each UI container on its own bridge network

Firewall (host)

  • Rules in DOCKER-USER and INPUT
  • Container → private networks: dropped
  • Container → host services: dropped
  • systemd unit re-applies at boot
  • Optional: restrict inbound to the connector host only

Compose conventions

image: …@sha256:…            # pinned by digest
cap_drop: [ALL]               security_opt: [no-new-privileges:true]
deploy.resources.limits: cpus / memory / pids
dns: [1.1.1.1, 1.0.0.1]       # embedded DNS would otherwise query the blocked LAN resolvers
secrets in secrets.env (0600, git-ignored), never in compose or env examples
Chat interface

Open WebUI + Workers AI open source

Why Open WebUI

  • Native MCP (Streamable HTTP) with custom headers
  • OpenAI-compatible model connections (here: Workers AI)
  • Model presets, multi-user roles, knowledge bases, notes, channels, voice
  • Functions/pipelines and a code interpreter (switched off here)

How it is wired

  • Two model connections (one per account), one user API token with only Workers AI permission
  • MCP connection cloudflare-security preloaded with the Service Token headers
  • Sign-ups closed after the first admin

Models that survive the tool loop

Tested on 23 Workers AI models that advertise function calling: 15 pass.

glm-5.3 glm-4.7-flash gemma-4-26b nemotron-3-120b kimi-k2.6 deepseek-v4-flash mistral-small-3.1

llama-3.3-70b gpt-oss-120b/20b qwen3-30b granite-4.0

Why some fail. After a tool call, Open WebUI sends the assistant message with content: null. Several Workers AI models reject it (HTTP 400, error 5006: "'string' not in 'null'"). Pick a compatible model.
Phase 2

WAF analysis: configuration and events

inspect_waf_rules · what is configured

  • Rulesets API: managed, custom, rate limiting, bot rules
  • Skip rules classified: all traffic high · unscoped medium · scoped info
  • Overrides that disable or log-only managed rules
  • Log-only and disabled custom rules; missing custom / rate-limit rules (as advice)
  • IPs in expressions replaced by <ip>

analyze_waf_events · what happened

  • GraphQL firewallEventsAdaptiveGroups, 1 to 720 hours, optional host filter
  • Actions, sources, top rules with main target, countries and ASNs, hourly timeline
  • No client IPs returned
  • Hints: false-positive candidates, spikes, dominant network, log-mode volume
Tuning lesson. The WAF attack score only describes payload attacks. A first version flagged a crawler-blocking rule as a false positive because its attack score was "clean". The hint now applies only to payload-attack managed rules (injection, XSS, SQLi…).

Permissions: Zone WAF Read, Zone Analytics Read. Without them the tools report unavailable instead of failing.

Case study

A WAF false positive, diagnosed from the logs

  1. Symptom: every chat message fails with Unexpected token '<', "<!DOCTYPE"… is not valid JSON.
  2. Clue: the request never reached the host; the response header was cf-mitigated: challenge (a challenge page returned to a background request).
  3. Ray ID → Security Events: "Managed Challenge" by the Cloudflare Managed Ruleset, rule Generic Rules - Template Injection - 2. Attack score 86 ("not an exploit"), bot score 99.
  4. Cause: Open WebUI's request body carries {{USER_NAME}}-style placeholders, which look like template injection.
  5. Fix: a managed-rules exception that skips only that rule, only for the chat hostname and /api/. Access already restricts the host to one person.
  6. Now: analyze_waf_events reports this same pattern as a possible false positive, and inspect_waf_rules shows the scoped exception.
Journey

How it was built, in order

  1. Discover the host: OS, architecture, Docker, free ports, existing services
  2. TypeScript MCP server: zones, DNS and posture tools; Zod, rate limit, timeouts
  3. Hardened Docker image and compose; validate on the real ARM64 hardware
  4. Access JWT verification in the app; HTTP mode refuses to start without it
  5. Tunnel route + Access app (Managed OAuth) for the MCP hostname
  6. Multi-account support and a name-based zone allowlist
  7. Inspector container behind its own Access app, Service Token to the MCP server
  8. Host firewall + systemd unit to isolate the UI containers
  9. Open WebUI + Workers AI; preload MCP connection and model filters
  10. Find and fix the WAF false positive and the null-content model issue
  11. Phase 2: inspect_waf_rules and analyze_waf_events
  12. This deck, the runbook and the lessons, committed to git
Troubleshooting

Lessons learned · connectivity and auth

SymptomCauseFix
404 "Server not found" on one zone from curl; fine from a browserCorporate WARP/Gateway on the test laptop treated non-browser clients differently for that zone (root cause not fully established). Earlier "edge bug" diagnoses were wrong.Test from a browser or a non-corporate network before blaming the edge; a new hostname on another zone avoided it
Invalid Host: … after loginDNS-rebinding guard only allows listed hostnamesAdd the hostname to HTTP_ALLOWED_HOSTS, recreate the container
Crash loop ERR_INVALID_URLTeam domain given without https://Config now normalizes it
Service Token request redirected (302) to loginPolicy action was Allow, not Service AuthChange the action to Service Auth
401 calling the LAN address directlyExpected: no Access JWT on that pathUse the public URL; /health stays open
Troubleshooting

Lessons learned · chat, models and config

SymptomCauseFix
Chat error "Unexpected token '<'"Managed WAF rule challenged {{ }} placeholdersScoped skip rule for that one rule, host and /api/
Workers AI 400, error 5006, after a tool callModel rejects content: nullUse a compatible model (15 of 23 pass)
Model API key from the environment ignoredOpen WebUI saves settings to its database on first start; the database wins over env varsEdit in the admin UI, or update the config table (back it up first)
403 error 1010 when testing by scriptCloudflare blocks Python's default urllib User-AgentSend another User-Agent; the app's own client is accepted
Model calls a built-in tool instead of oursMCP tool not enabled for the chatEnable via +, or attach it to a model preset and turn built-ins off
Example file silently missing from a commit.gitignore pattern *.env.* matched itRenamed to secrets.template; check git ls-files
Incident

A live API token in a tracked file

What happened

  • The live read-only API token had been committed in .env.example and pushed to the private git server.
  • Found by comparing hashes of the example file and the deployed .env, never by printing values.
  • An earlier incident: a token pasted into a comment in .env was printed once by a diagnostic command.

Response and rules

  • Token removed from the working tree; incident logged; rotation tracked as an open item.
  • New token: user-owned (spans both accounts), read-only, with expiry; separate token for Workers AI.
  • Never cat or grep env files unfiltered; compare hashes; keep secrets out of examples and comments.
  • After rotation, delete the old token and confirm it returns 401.
Removing a secret from the latest commit is not enough. It stays in history; the real fix is to revoke the credential. History rewriting is optional hygiene after revocation.
Demo

A 10-minute live demo

  1. Show the guardrails. Open the MCP URL without credentials: redirected to login. Call it with a bad zone: rejected by the allowlist.
  2. Inspector. Connect, list tools, call list_cloudflare_zones and read the raw JSON.
  3. Chat. Enable the tool and ask the sweep question; open the "Explored" panel to show the tool calls.
  4. WAF story. Ask for events on the chat host and the false-positive hint; then inspect the WAF rules.

Prompts

List my zones and give me the three
highest-risk security findings across them.

Analyze the security events of <zone> for
host <chat-host> over the last 24 hours.
Are any of them false positives?

Inspect the WAF rules of <zone>. Which skip
rules or overrides weaken protection?

For <zone>, what is blocked most, from
where, and is there a traffic spike?

Prefer one zone per WAF question; a zone with ~80 rules returns about 30 KB.

Results

What a sweep of 13 zones surfaced

SSL/TLS mode "Flexible"

high confirmed

4 zones. Traffic to the origin is plain HTTP. Caveat: may not apply to zones without a proxied origin; the posture tool is not yet DNS-aware.

Minimum TLS 1.0 / 1.1

high confirmed

11 of 13 zones. Quick, low-risk setting change to 1.2.

DNSSEC not active

medium confirmed

12 of 13 zones. Enable and publish the DS record at the registrar (read the steps first: a wrong DS breaks resolution).

Read the model's summary as a lead. It is written from real tool data, but check the evidence in the tool output before acting. The server only reads; fixes are made by a person in the dashboard.
Operations

Runbook · deploy, verify, roll back, rotate

Deploy the MCP server

rsync -a --exclude='.env*' --exclude='inspector/' \
  --exclude='chat/' ./ edge:/opt/mcp-server/
ssh edge 'cd /opt/mcp-server \
  && docker tag app:local app:prev \
  && docker compose build \
  && docker compose up -d'

Verify through the public path

curl -sS -X POST https://mcp.example.com/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -H "CF-Access-Client-Id: $ID" \
  -H "CF-Access-Client-Secret: $SECRET" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize",
       "params":{"protocolVersion":"2025-06-18",
       "capabilities":{},"clientInfo":
       {"name":"check","version":"0"}}}'

Roll back

docker tag app:prev app:local
docker compose up -d

Rotate the Cloudflare read-only token

  1. Create a user token: Zone, Zone Settings, DNS, SSL Read, plus Zone WAF Read and Zone Analytics Read; both accounts; expiry.
  2. Update .env on the host (never print it), recreate the container.
  3. Check the zone list still returns all zones.
  4. Delete the old token; confirm it returns 401.

Other

  • Firewall: systemctl restart mcp-inspector-firewall
  • Back up the chat database volume before editing settings
  • Chat/Inspector secrets stay in 0600 files on the host
Reference

Where everything lives

src/
  index.ts  server.ts          entry + tool registration
  config/   env.ts allowlist.ts
  clients/  cloudflare.ts      GET + one read-only GraphQL POST
  services/ posture.ts wafRules.ts wafEvents.ts
            zoneResolver.ts
  tools/    zones dns security wafRules wafEvents
  auth/     cloudflareAccess.ts accessGate.ts
  utils/    errors logger rateLimiter
tests/                         mirrors src/ (114 tests)
deploy/
  inspector/  compose, firewall script, systemd unit
  chat/       compose, secrets template
presentation/                  this deck (static)
DocCovers
README.mdArchitecture, tools, security model, troubleshooting
docs/cloudflare-token.mdExact token permissions per phase
docs/cloudflare-access-setup.mdAccess + Managed OAuth setup
docs/inspector.mdInspector deployment and firewall
docs/chat-ui.mdChat UI, models, gotchas, prompts
FUTURE_UPDATES.mdBacklog, decisions, incident log
Next

Roadmap and open items

Housekeeping

  • Rotate the read-only token; delete the old one
  • Retire the superseded hostname (route, DNS, Access app)
  • Push the local commits
  • Model preset: tool on by default, built-ins off

Product

  • DNS-aware SSL finding (fewer false positives on unused zones)
  • Auto-discover all zones in the allowed accounts (opt-in, deny list)
  • Bot-score hints for custom bot rules
  • analyze_api_exposure, audit_zero_trust, generate_risk_report
  • Fix the real findings: TLS minimum, DNSSEC, CAA, SSL mode
Possible later extensions (read-only first): hypervisor and firewall inventories, DNS filtering statistics, tunnel connectivity visibility.
Wrap-up

Read-only, evidence-based, and honest about uncertainty

An agent is only as trustworthy as its data, its scope and its guardrails. Those are the parts we built.

Questions? Start with FUTURE_UPDATES.md Deck: o overview · p print to PDF