Skip to content

Use cf with coding agents

Coding agents can use cf to work with your Cloudflare account. Commands return JSON and describe their own inputs, so an agent can find and run the right command without prior knowledge of cf.

Set up cf for your agent

  1. Install cf globally so every agent session can run it:

    npm install --global cf

    Inside a project that installs cf as a dependency, the global command runs the project's copy.

  2. Sign in:

    cf auth login

    Sign-in opens a browser page where you approve access, so complete this step yourself. For agents that run without a person present, refer to Authenticate unattended agents.

  3. Tell your agent to prefer cf. Add this instruction to your user-level AGENTS.md, CLAUDE.md, or equivalent instructions file:

    AGENTS.mdmd
    When interacting with Cloudflare, use the `cf` CLI unless the project has a
    Wrangler configuration file.

    Projects that still use wrangler.jsonc or wrangler.toml keep working with Wrangler, while every other Cloudflare task goes through cf.

You can also ask your agent to do this setup for you:

Install the Cloudflare CLI with `npm install -g cf`. Then add this line to my
user-level AGENTS.md or CLAUDE.md file: "When interacting with Cloudflare, use
the cf CLI unless the project has a Wrangler configuration file."

Help your agent find commands

cf has more than 2,900 commands. Instead of reading help for every product, an agent can describe the task, inspect the best match, and then run it.

  1. Search for a command by describing the task:

    cf cli search "create D1 database"

    The search runs locally and needs no credentials. Put the task in quotes. cf cli search takes the whole task as one argument, and unquoted words after the first fail as unknown commands. It returns up to five matches as a JSON array, best match first. Each match has the command and a short summary. These are the first two matches for this search:

    [
      {
        "command": "cf d1 create",
        "summary": "Create D1 Database"
      },
      {
        "command": "cf d1 update",
        "summary": "Update D1 Database"
      }
    ]
  2. Inspect the API request of the chosen command:

    cf schema d1 create

    The JSON result describes the API request that the command sends: operationId, httpMethod, path, pathParams, queryParams, hasRequestBody, and requestBodyFields. Each parameter and body field lists its name, its type, and whether it is required. Body fields also include a description. cf schema covers generated API commands. For a command's arguments and options, or for a command such as cf deploy, run the command with --help.

    Path and query parameters use their API names, such as account_id. requestBodyFields lists the body fields that the command also accepts as options, under the option names. A field inside an object gets a combined name, such as read-replication-mode for read_replication.mode, and array fields show the type string. For some bodies, the list is incomplete or empty. For these commands, pass the complete body with --body, and check the API reference for its shape.

  3. Preview the request with --dry-run, then run the command without it:

    cf d1 create --name my-database --dry-run

Root and group --help output starts with a reminder for agents to use cf cli search first. A command's own --help shows its usage as plain text. If an agent types a command that does not exist, cf lists the closest matches.

Find Cloudflare documentation

You and your agent can use cf docs search to find guides, tutorials, and examples across Cloudflare products. The search uses live Cloudflare documentation and requires an Internet connection, but no Cloudflare login.

  1. Describe the task or ask a question:

    cf docs search "proxy a DNS record"

    Put the query in quotes. The command returns up to five ranked JSON results, each with a title, description, and url.

  2. Choose a result and fetch its URL with the Accept: text/markdown header to read the complete page as Markdown:

    curl -H "Accept: text/markdown" \
      https://developers.cloudflare.com/learning-paths/prevent-ddos-attacks/baseline/proxy-dns-records/

Use cf cli search to find commands and cf docs search to find documentation. Keep both kinds of search generic: do not include account IDs, domains, email addresses, tokens, or other identifying information.

Send agent feedback

Use cf feedback send to report Cloudflare problems your agent encounters. To ask your agent to look for blockers and workarounds across a repository, refer to Review an existing project.

Read command output

Results go to standard output as JSON. Messages, such as the selected zone, pagination metadata, and errors go to standard error. When standard output is not a terminal, it contains only the result, so an agent can parse it or filter it with jq without extra flags.

  • Lists print the page items as JSON on standard output (usually a JSON array, or an object wrapping the items for some endpoints) and return one page per call. Paging options differ between commands, so check the command's --help output.
  • Changes that return no data print nothing to standard output.
  • Raw content, such as an R2 object or an image from a Workers AI model, goes to standard output unchanged. Redirect it to a file.
  • JSON output is indented, whether or not standard output is a terminal. Colors are added only in a terminal.

A failed command exits with a non-zero status and prints the error to standard error.

Paginate list results

To keep standard output clean JSON for jq and scripts, paginated cf list commands print page items on standard output (stdout) and write API pagination metadata to standard error (stderr) as a single line prefixed with result_info::

result_info: {"page":1,"per_page":20,"count":20,"total_count":45,"total_pages":3}

Omit --quiet (-q) when reading pagination metadata, because --quiet suppresses the result_info: line. Do not merge stderr into stdout with 2>&1 when piping to jq or a JSON parser — capture stdout and stderr separately so the result_info: line and other messages do not break JSON parsing.

Cloudflare API endpoints do not all return the same result_info fields. Some endpoints include total_pages, while others (such as cf d1 list) return total_count and per_page — or only count or a cursor — without total_pages, and some omit result_info altogether. When scripting pagination, determine when to stop defensively:

  • Use total_pages when it is present in result_info.
  • When total_pages is absent but total_count and per_page are present, calculate the page count with ceiling division (Math.ceil(total_count / per_page)), or in jq: (.total_pages // (((.total_count + .per_page - 1) / .per_page) | floor)).
  • Stop if a page returns an empty list ([]), empty output, or fewer items than the page size (result_info.per_page, or the --per-page value you requested).
  • For cursor-based commands, pass the cursor value from result_info on the next call, and stop when cursor is absent or empty.

The following example captures stdout and stderr separately and paginates cf d1 list without assuming total_pages is present:

page=1
per_page=50

while :; do
  items_file=$(mktemp)
  err_file=$(mktemp)

  if ! cf d1 list --page "$page" --per-page "$per_page" >"$items_file" 2>"$err_file"; then
    cat "$err_file" >&2
    rm -f "$items_file" "$err_file"
    exit 1
  fi

  # Process page items from standard output
  jq -r '.[].name' "$items_file"

  count=$(jq 'length' "$items_file")
  count=${count:-0}
  result_info=$(sed -n 's/^result_info: //p' "$err_file" | tail -n 1)
  rm -f "$items_file" "$err_file"

  # Use total_pages when present, otherwise derive it from total_count and per_page
  total_pages=$(printf '%s' "$result_info" | jq -r '
    .total_pages // (
      if (.total_count != null and (.per_page // 0) > 0)
      then (((.total_count + .per_page - 1) / .per_page) | floor)
      else empty
      end
    )
  ')
  page_size=$(printf '%s' "$result_info" | jq -r '.per_page // empty')
  page_size=${page_size:-$per_page}

  if [ -n "$total_pages" ] && [ "$page" -ge "$total_pages" ]; then
    break
  fi
  if [ "$count" -eq 0 ] || [ "$count" -lt "$page_size" ]; then
    break
  fi

  page=$((page + 1))
done

Run commands safely

  • Preview changes. Add --dry-run to print the request as JSON without sending it. Dry runs need no credentials.
  • Check for aborted deletes. In a non-interactive session, a destructive command without --force prints Aborted. to standard error, makes no change, and exits with status 1.
  • Review --force before you allow it. On some commands, --force is also an API parameter. For example, cf workers delete --force also deletes a Worker that other Workers still reference.
  • Use local data where supported. --local works only for a few resources that local development provides, mainly KV keys, D1 databases through cf d1 raw, cf d1 migrations list, and cf d1 migrations apply, and R2 objects. Commands without a local equivalent, including cf d1 query, return an error instead of calling the Cloudflare API.

For local state, refer to Local resource data.

Control usage costs

Before your agent runs workloads on Cloudflare, consider setting spending limits or email alerts for Workers and Durable Objects. You can configure them with the cf CLI.

Each limit applies to the product across your account, not to an individual agent or project. Reaching a limit can interrupt other applications on the same account. Choose an email alert if you want notification without blocking usage.

Work in Wrangler projects

To migrate a project with an agent, ask it to:

  1. Preview the migration without writing files:

    cf migrate --dry-run
  2. Run the migration:

    cf migrate
  3. Resolve the TODO(@cloudflare) comments in the generated cloudflare.config.ts, and ask you about any choice it cannot make on its own. The build fails until every required item is resolved.

For the full process, refer to Migrate a Wrangler project.

Authenticate unattended agents

Agents that run without a person present, such as in continuous integration (CI), cannot complete cf auth login. Set CLOUDFLARE_API_TOKEN instead. The token takes priority over any stored login. For the variables, token permissions, and non-interactive behavior, refer to Use cf in CI.

To give an agent separate credentials for one project on your own machine, bind a named profile to the project directory. Refer to Use named profiles.

Inspect local resources

When cf dev runs inside a supported coding agent, the development server also prints the URL and main routes of the Local Explorer API. The agent can use this API to read and change the data in your Worker's local bindings, and to query local traces and logs.

  • Agent setup configures Cloudflare Skills and MCP servers for popular coding agents.
  • Use cf in CI covers API tokens and non-interactive behavior.

Was this helpful?