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.
Keys: ← → move · o overview · n notes · f fullscreen · p print to PDF. Hostnames and IDs in this deck are placeholders.
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.
The big picture
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.
Four things run on the edge host
| Piece | Public name (placeholder) | Role | Auth in front |
|---|---|---|---|
| MCP server | mcp.example.com/mcp | Exposes 5 read-only tools over Streamable HTTP, stateless | Access (Managed OAuth for people, Service Auth for services) + JWT check in the app |
| Chat UI | mcp-chat.example.com | Open WebUI: natural-language interface; calls the model and the MCP tools | Access, email-only policy + its own login |
| Inspector | mcp-inspector.example.com | Official MCP Inspector for calling tools by hand and debugging | Access, email-only policy |
| Firewall rules | (host) | Containers cannot reach the LAN or host services | systemd 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.
One question, end to end
"List my zones and give me the three highest-risk findings."
list_cloudflare_zones, then get_security_posture and inspect_dns_security for each zone.Five tools, two phases
| Tool | Input | What it returns |
|---|---|---|
list_cloudflare_zones | none | Only authorized zones: name, id, account, status, plan |
inspect_dns_security | zone | DNS records (IPs masked on unproxied A/AAAA) + DNSSEC; findings: unproxied origins, no CAA, DNSSEC off |
get_security_posture | zone | TLS/SSL and core settings: SSL mode, minimum TLS, HTTPS rewrites, security level… |
inspect_waf_rules phase 2 | zone | Managed rules, overrides, exceptions, custom rules, rate limiting. Flags broad skip rules, weakened overrides, log-only rules |
analyze_waf_events phase 2 | zone, hours, host? | Events by action/source, top rules and targets, countries/ASNs, timeline. Flags possible false positives and spikes |
limitations list. The model can only report what the data supports.Findings carry severity and confidence
Confidence
Severity
critical high medium low informational
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/…"]
}
Nine independent layers
Two ways through Access
People: Managed OAuth
- Client calls the MCP URL, gets a redirect plus
www-authenticatemetadata. - Access acts as the OAuth 2.1 authorization server; user logs in with the identity provider.
- Access injects
Cf-Access-Jwt-Assertionon every allowed request. - The MCP server verifies that JWT before doing anything.
No OAuth code lives in the MCP server.
Services: Service Token
- Chat UI and Inspector call the MCP URL with
CF-Access-Client-Id/Secretheaders. - A policy with action Service Auth (not Allow) matches the token.
- Access issues the same kind of JWT; the server verifies it.
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-USERandINPUT - 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
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-securitypreloaded 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
content: null. Several Workers AI models reject it (HTTP 400, error 5006: "'string' not in 'null'"). Pick a compatible model.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
Permissions: Zone WAF Read, Zone Analytics Read. Without them the tools report unavailable instead of failing.
A WAF false positive, diagnosed from the logs
- Symptom: every chat message fails with
Unexpected token '<', "<!DOCTYPE"… is not valid JSON. - Clue: the request never reached the host; the response header was
cf-mitigated: challenge(a challenge page returned to a background request). - 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.
- Cause: Open WebUI's request body carries
{{USER_NAME}}-style placeholders, which look like template injection. - 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. - Now:
analyze_waf_eventsreports this same pattern as a possible false positive, andinspect_waf_rulesshows the scoped exception.
How it was built, in order
- Discover the host: OS, architecture, Docker, free ports, existing services
- TypeScript MCP server: zones, DNS and posture tools; Zod, rate limit, timeouts
- Hardened Docker image and compose; validate on the real ARM64 hardware
- Access JWT verification in the app; HTTP mode refuses to start without it
- Tunnel route + Access app (Managed OAuth) for the MCP hostname
- Multi-account support and a name-based zone allowlist
- Inspector container behind its own Access app, Service Token to the MCP server
- Host firewall + systemd unit to isolate the UI containers
- Open WebUI + Workers AI; preload MCP connection and model filters
- Find and fix the WAF false positive and the null-content model issue
- Phase 2:
inspect_waf_rulesandanalyze_waf_events - This deck, the runbook and the lessons, committed to git
Lessons learned · connectivity and auth
| Symptom | Cause | Fix |
|---|---|---|
| 404 "Server not found" on one zone from curl; fine from a browser | Corporate 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 login | DNS-rebinding guard only allows listed hostnames | Add the hostname to HTTP_ALLOWED_HOSTS, recreate the container |
Crash loop ERR_INVALID_URL | Team domain given without https:// | Config now normalizes it |
| Service Token request redirected (302) to login | Policy action was Allow, not Service Auth | Change the action to Service Auth |
| 401 calling the LAN address directly | Expected: no Access JWT on that path | Use the public URL; /health stays open |
Lessons learned · chat, models and config
| Symptom | Cause | Fix |
|---|---|---|
| Chat error "Unexpected token '<'" | Managed WAF rule challenged {{ }} placeholders | Scoped skip rule for that one rule, host and /api/ |
| Workers AI 400, error 5006, after a tool call | Model rejects content: null | Use a compatible model (15 of 23 pass) |
| Model API key from the environment ignored | Open WebUI saves settings to its database on first start; the database wins over env vars | Edit in the admin UI, or update the config table (back it up first) |
| 403 error 1010 when testing by script | Cloudflare blocks Python's default urllib User-Agent | Send another User-Agent; the app's own client is accepted |
| Model calls a built-in tool instead of ours | MCP tool not enabled for the chat | Enable via +, or attach it to a model preset and turn built-ins off |
| Example file silently missing from a commit | .gitignore pattern *.env.* matched it | Renamed to secrets.template; check git ls-files |
A live API token in a tracked file
What happened
- The live read-only API token had been committed in
.env.exampleand 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
.envwas 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
catorgrepenv files unfiltered; compare hashes; keep secrets out of examples and comments. - After rotation, delete the old token and confirm it returns 401.
A 10-minute live demo
- Show the guardrails. Open the MCP URL without credentials: redirected to login. Call it with a bad zone: rejected by the allowlist.
- Inspector. Connect, list tools, call
list_cloudflare_zonesand read the raw JSON. - Chat. Enable the tool and ask the sweep question; open the "Explored" panel to show the tool calls.
- 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.
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).
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
- Create a user token: Zone, Zone Settings, DNS, SSL Read, plus Zone WAF Read and Zone Analytics Read; both accounts; expiry.
- Update
.envon the host (never print it), recreate the container. - Check the zone list still returns all zones.
- 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
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)
| Doc | Covers |
|---|---|
README.md | Architecture, tools, security model, troubleshooting |
docs/cloudflare-token.md | Exact token permissions per phase |
docs/cloudflare-access-setup.md | Access + Managed OAuth setup |
docs/inspector.md | Inspector deployment and firewall |
docs/chat-ui.md | Chat UI, models, gotchas, prompts |
FUTURE_UPDATES.md | Backlog, decisions, incident log |
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
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.