/ Каталог / Песочница / Cloudflare API
● Официальный cloudflare 🔑 Нужен свой ключ

Cloudflare API

автор cloudflare · cloudflare/mcp

Manage Cloudflare DNS, zones, WAF, analytics, and Workers from Claude — with scoped API tokens and a dry-run habit.

Cloudflare's API MCP turns the full Cloudflare REST API into tools: zones, DNS records, page rules, firewall rules, analytics, SSL, Workers, R2, KV, and more. Use a scoped API token (not a Global API Key) and treat writes like infrastructure changes — preview, apply, verify.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

cloudflare-api.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "cloudflare-api": {
      "command": "npx",
      "args": [
        "-y",
        "@cloudflare/mcp"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "cloudflare-api": {
      "command": "npx",
      "args": [
        "-y",
        "@cloudflare/mcp"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "cloudflare-api": {
      "command": "npx",
      "args": [
        "-y",
        "@cloudflare/mcp"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "cloudflare-api": {
      "command": "npx",
      "args": [
        "-y",
        "@cloudflare/mcp"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "cloudflare-api",
      "command": "npx",
      "args": [
        "-y",
        "@cloudflare/mcp"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "cloudflare-api": {
      "command": {
        "path": "npx",
        "args": [
          "-y",
          "@cloudflare/mcp"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add cloudflare-api -- npx -y @cloudflare/mcp

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: Cloudflare API

Audit DNS records across every zone for drift

👤 Platform / SRE teams ⏱ ~25 min intermediate

Когда использовать: You own 40 zones and want to know which have weird TTLs, missing SPF/DMARC, or dangling CNAMEs.

Предварительные требования
  • API token with Zone:Zone:Read, Zone:DNS:Read — Cloudflare dashboard → My Profile → API Tokens → Create
Поток
  1. List zones and count records per type
    List all zones in my account. For each, count records by type (A, CNAME, TXT, MX).✓ Скопировано
    → Inventory matrix
  2. Check email-auth hygiene
    For each zone used for email, check presence of SPF (TXT containing 'v=spf1'), DMARC TXT at _dmarc, and DKIM selector TXT records. Flag missing.✓ Скопировано
    → Email-auth gap report
  3. Find dangling CNAMEs
    For each CNAME in every zone, resolve the target. Flag NXDOMAIN or SERVFAIL as dangling.✓ Скопировано
    → List of risky CNAMEs

Итог: A zone-by-zone DNS hygiene report you can hand to the team that owns each domain.

Подводные камни
  • Dangling CNAMEs are subdomain-takeover risks — Any NXDOMAIN CNAME gets escalated immediately — delete or fix
Сочетать с: filesystem

Add or update a DNS record with a preview/apply workflow

👤 Anyone about to make a DNS change they're nervous about ⏱ ~10 min beginner

Когда использовать: Switching mail provider, adding a new CNAME for a service — high-stakes DNS changes.

Предварительные требования
  • Token with Zone:DNS:Edit on the target zone — Scope token to only the one zone you're changing
Поток
  1. Show current state
    For zone <zone>, show every record for name '<name>' and type <type>. Proxied status and TTL.✓ Скопировано
    → Current record state
  2. Propose the change, don't apply
    Propose a patch: <describe change>. Show the exact API call and the before/after. Do NOT execute yet.✓ Скопировано
    → Preview diff
  3. Apply after confirmation
    I confirm. Apply the change. Then read back the record to confirm. Also flush cache for the impacted name.✓ Скопировано
    → Record updated + cache purged + verification read

Итог: A DNS change with a review step and post-change verification — no surprises.

Подводные камни
  • Proxied (orange-cloud) CNAME to a mail server breaks email — Always proxied:false for MX, SPF-related CNAMEs, and non-HTTP records

Deploy an emergency rate-limit during a traffic spike

👤 SRE responding to an L7 DDoS or runaway client ⏱ ~15 min advanced

Когда использовать: Traffic is spiking and Origin is struggling. You need to dampen it in minutes.

Предварительные требования
  • Token with Zone:Zone WAF:Edit on the zone — Dedicated incident-response token kept in a password manager
Поток
  1. Identify the pattern
    Pull last hour analytics for zone <zone>. Top 10 paths, top user agents, top countries by request count. Highlight anomalies.✓ Скопировано
    → Anomaly candidates
  2. Create a rate-limit rule
    Create a WAF rate-limit rule: 60 req/min per IP on path /<hot path>, action: challenge. Log match count after 2 minutes.✓ Скопировано
    → Rule created + matches streaming
  3. Roll back when safe
    Once origin health is green for 30 min, disable (not delete) the rule. Leave a description tagged 'incident-<id>' for audit.✓ Скопировано
    → Rule disabled; audit entry kept

Итог: Attack mitigated with a rule you can re-enable or refine — no permanent config drift.

Подводные камни
  • Blanket block by country nukes legit users — Always start with Challenge or JS-Challenge, not Block; observe then tighten
Сочетать с: sentry

Purge Cloudflare cache for specific URLs after a deploy

👤 Frontend devs shipping static asset updates ⏱ ~10 min beginner

Когда использовать: Post-deploy: CSS/JS hashes changed, you want users to get the new version immediately.

Поток
  1. List files to purge
    My build changed these URLs: [list]. Confirm each is cached at CF edge (HEAD + cf-cache-status).✓ Скопировано
    → Current cache hit/miss per URL
  2. Purge by URL
    Purge exactly those URLs on zone <zone>. Do NOT do purge-everything.✓ Скопировано
    → Purge job accepted
  3. Verify fresh fetch
    After 10 seconds, HEAD each URL again — cf-cache-status should be MISS or REVALIDATED.✓ Скопировано
    → Fresh cache state

Итог: Targeted cache bust, no accidental full-zone purge (which kills your origin on reload).

Подводные камни
  • Purge-everything sends a thundering-herd to origin — Never call purge_all unless you've warmed an alternative path; purge-by-url is almost always enough
Сочетать с: github

Seed Workers KV from a local JSON file

👤 Engineers deploying a Workers-based API ⏱ ~15 min intermediate

Когда использовать: You maintain config/feature-flag data in KV and want to sync from a local source of truth.

Предварительные требования
  • Token with Workers KV Storage: Edit — Scope to the specific namespace id
Поток
  1. Read the local source
    Read /config/kv.json. Validate it as {key: value} object.✓ Скопировано
    → Parsed config
  2. Diff against current KV
    List keys in namespace <id>. Compute adds / updates / deletes vs my local file.✓ Скопировано
    → Change plan
  3. Apply via bulk write
    Use bulk write for the changes. Deletes only if I confirm — show which keys would be deleted first.✓ Скопировано
    → Bulk write ok; deletes reviewed

Итог: KV namespace reconciled to your source file, atomically enough.

Подводные камни
  • KV eventual consistency means readers may still see old values for ~60s — If you need strong consistency, use D1 or Durable Objects instead
Сочетать с: filesystem

Weekly traffic and threat summary from Cloudflare Analytics

👤 Product / growth + security ⏱ ~20 min intermediate

Когда использовать: Friday digest: what's our traffic pattern, what threats did we block?

Поток
  1. Pull totals
    For zone <zone> last 7 days: total requests, bandwidth, threats blocked, top 10 countries.✓ Скопировано
    → Headline numbers
  2. Top paths and referrers
    Top 20 paths by requests; top 10 referrers. Highlight changes vs previous week.✓ Скопировано
    → Growth/regression table
  3. Firewall events summary
    Top firewall rule triggers in the last 7 days. Any rules never triggered — candidates for cleanup.✓ Скопировано
    → Ruleset health report

Итог: One-page weekly with traffic, threats, and rule health.

Подводные камни
  • Free plan analytics are sampled — For precise data, use Logpush / GraphQL Analytics API with a Pro+ plan
Сочетать с: notion

Комбинации

Сочетайте с другими MCP — эффект x10

cloudflare-api + github

On merge to main, purge cache for deployed asset URLs

PR #342 merged; its diff changed /static/app.a1b2.js. Purge that URL on zone <zone>, verify with HEAD.✓ Скопировано
cloudflare-api + sentry

Correlate a Sentry traffic spike with firewall event data

Sentry shows 5xx spike at 14:02. Pull CF analytics for 14:00-14:05 for the same zone; correlate with firewall events.✓ Скопировано
cloudflare-api + filesystem

Sync a local zone-config file into Cloudflare (GitOps-lite)

Read /dns/mydomain.yaml; reconcile against current zone state; apply safely with review.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
list_zones Discover zones in the account free
list_dns_records zone_id, type?, name? Before any DNS edit — inspect current free
create_dns_record / update_dns_record / delete_dns_record zone_id, record DNS mutations (require Edit token) free
purge_cache zone_id, files?|tags?|hosts?|everything? Cache bust after deploy free
list_firewall_rules / create_firewall_rule zone_id, ... Incident response / hardening free
analytics_dashboard zone_id, since, until Traffic reports free
kv_list / kv_get / kv_put / kv_bulk namespace_id, key/value Workers KV ops metered beyond free tier
deploy_worker script name, script content, bindings? Ship a Worker free up to limits

Стоимость и лимиты

Во что обходится

Квота API
1200 requests per 5 minutes per user (Cloudflare global rate limit)
Токенов на вызов
DNS listing: 200–1000 tokens per page. Analytics: up to 3000.
Деньги
API free. Paid for Workers paid/KV beyond free tier; plans start Free / Pro $20/mo / Business $200/mo.
Совет
Prefer listing + filtering server-side (type, name) over client-side to save tokens and pagination.

Безопасность

Права, секреты, радиус поражения

Минимальные скоупы: Zone:Zone:Read Zone:DNS:Read (add :Edit only for specific zones that need writes)
Хранение учётных данных: CLOUDFLARE_API_TOKEN in env — never the Global API Key
Исходящий трафик: All calls to api.cloudflare.com
Никогда не давайте: Global API Key (full account control) Account:Access:Edit without account-level review

Устранение неполадок

Частые ошибки и исправления

10000 Authentication error

Token invalid or lacks required permission. Recreate with the specific zone + permission.

Проверить: curl -H 'Authorization: Bearer $CLOUDFLARE_API_TOKEN' https://api.cloudflare.com/client/v4/user/tokens/verify
81057 Record already exists

A record with that name+type+content already exists. Update the existing one by id, don't create.

Purge-by-URL returns success but cache still hits

URL must match exactly including query string ordering. Also check cf-cache-status — 'DYNAMIC' means it wasn't cached anyway.

Rate limited (429)

Hit Cloudflare's global API rate limit. Back off, batch, or split workload over multiple tokens for different workflows.

Альтернативы

Cloudflare API в сравнении

АльтернативаКогда использоватьКомпромисс
Cloudflare official MCP (other)You prefer Cloudflare's documentation/Workers-observability-focused MCPNarrower API surface
Route 53 MCPYou're on AWS and want Route53 DNSDifferent ecosystem; no CDN/WAF baked in

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills