# How to Connect Cloudflare R2 to AI Agents via MCP Server

A Cloudflare R2 MCP server connects AI agents directly to Cloudflare S3-compatible R2 object storage for reading, listing, and querying files without egress fees. While zero egress costs make R2 ideal for storing unstructured documents, direct bucket traversal can exhaust agent context windows through unindexed file downloads. Deploying an intelligent workspace layer enables hybrid semantic search across bucket contents, retrieving targeted excerpts instead of streaming raw files.

Source: https://fast.io/resources/cloudflare-r2-mcp-server/
Author: [Tom Langridge](https://fast.io/authors/tom-langridge/)
Last reviewed: 2026-09-22

## Why Autonomous Agents Struggle with Direct Object Storage Access

When an autonomous AI agent connects directly to Cloudflare R2 through raw object storage tools, a single unguided query can flood the model's context window. An agent tasked with finding an updated API spec or inspecting error logs inside a storage bucket will often download entire multi-megabyte objects into prompt memory, consuming thousands of tokens on unindexed bytes before locating the relevant answer.

A Cloudflare R2 MCP server is an implementation of the Model Context Protocol that connects AI agents directly to Cloudflare S3-compatible R2 object storage for reading, listing, and querying files without egress fees. The Model Context Protocol (MCP) defines an open standard for large language models to interact with external storage systems, APIs, and runtime environments through structured tool calling. For engineers building autonomous coding agents, research assistants, and data extraction pipelines, connecting agents to Cloudflare R2 allows models to read configuration archives, inspect training datasets, and persist generated outputs directly into cloud storage.

Cloudflare R2 provides an attractive storage layer because it eliminates AWS-style egress fees for agent object retrieval. Reading gigabytes of model checkpoints, documentation archives, or application logs incurs zero bandwidth penalty when files exit Cloudflare's network. However, raw object storage was engineered for programmatic throughput and binary persistence rather than the prompt constraints of modern language models. Language models operate with strict context window limits and sequential attention budgets. Ingesting raw bucket payloads without an intermediary indexing layer quickly leads to context bloat, sluggish inference, and truncated system instructions.

The gap between raw connector retrieval and indexed retrieval is measured rather than assumed. Fast.io publishes a [head to head benchmark of agent file work](https://fast.io/benchmarks/) in which one agent runs an identical multi-document task against the same corpus held in Fast.io and in each of the major cloud storage providers, recording completion time, tool calls, token consumption and cost. Fast.io completed the task fastest and at the lowest cost of the storage layers tested.

Connecting AI agents to Cloudflare R2 effectively requires understanding the native MCP tools provided across the Cloudflare ecosystem, the architectural limits of flat key-value object stores, and the indexing strategies that protect prompt context.

## Cloudflare R2 MCP Server Architecture and Connection Options

Connecting an AI agent to Cloudflare R2 involves establishing an authenticated bridge between your MCP client (such as Claude Code, Cursor, or Devin Desktop, formerly Windsurf) and Cloudflare's infrastructure. Developers can choose between two distinct integration approaches depending on their operational scope.

### Option 1: The Cloudflare API MCP Server (Code Mode)

Cloudflare maintains an official hosted MCP server accessible over Streamable HTTP at `https://mcp.cloudflare.com/mcp`. Rather than declaring thousands of individual tool definitions for every Cloudflare product endpoint, this server uses the Code Mode search-and-execute pattern.

Under Code Mode, the MCP server registers two core primitives with the client: `search()` and `execute()`. When an agent needs to manipulate R2 resources, it uses `search()` to locate typed representations of Cloudflare's OpenAPI specification, writes a minimal JavaScript snippet to invoke the target endpoints, and executes the snippet inside an isolated sandbox. This approach keeps tool definitions compact and avoids context window bloat while granting the agent access to Cloudflare R2, DNS, Workers, and KV.

### Option 2: Dedicated S3-Compatible MCP Toolsets

Because Cloudflare R2 is fully compatible with the Amazon S3 API, developers can also run dedicated object storage MCP servers locally via `stdio` or through hosted middleware platforms like Pipedream. These servers expose discrete tools specifically mapped to object storage operations:

* **`r2_list_buckets`**: Enumerates existing storage buckets within the designated Cloudflare account.
* **`r2_list_objects`**: Queries objects within a specific bucket, accepting prefix, delimiter, and pagination cursor arguments.
* **`r2_get_object`**: Retrieves the object payload, content headers, last-modified timestamp, and metadata for a specified key.
* **`r2_put_object`**: Writes binary or text data to a designated bucket path.
* **`r2_delete_object`**: Removes a designated key from the storage bucket.

### Authentication and API Token Setup

Connecting to Cloudflare R2 requires creating an API token with appropriate permissions in the Cloudflare dashboard:

1. Log in to the Cloudflare dashboard and navigate to **R2** > **Manage R2 API Tokens**.
2. Click **Create API Token**.
3. Set token permissions. For read-only research agents, select **Object Read-Only**. For agents generating files, summaries, or dataset exports, select **Object Read & Write**.
4. Note your **Account ID**, **Access Key ID**, **Secret Access Key**, and the S3 API endpoint URL formatted as `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`.

## Three Practical Bottlenecks in Direct R2 Bucket Queries

While connecting an AI agent to an R2 MCP server is straightforward, running autonomous workflows against raw buckets reveals three structural hurdles that basic tutorials do not address.

### 1. Virtual Prefix Traversal in Flat Object Namespaces

Cloudflare R2 does not contain physical folders or directory hierarchies. Buckets are flat key-value stores where forward slashes (`/`) in object keys simulate virtual directory trees (for example, `reports/q3/financial-summary.pdf`).

When an AI agent searches for a file in a deeply nested hierarchy, it cannot issue a native recursive filesystem query. Instead, the model must invoke `list_objects` repeatedly:

* The agent calls `list_objects` at the root with a delimiter to identify top-level prefixes.
* It inspects the returned prefixes, selects a candidate path, and issues a follow-up call with the new prefix.
* If a prefix contains large numbers of objects, the agent must parse pagination continuation tokens and reissue calls.

This sequential traversal forces the agent through multiple tool-calling loops. The model burns input tokens parsing path strings before finding the target file.

### 2. Context Window Dilution from Raw File Ingestion

Once an agent locates a file in R2, calling `r2_get_object` pulls the entire raw object payload into the prompt context. If an engineer asks an agent to retrieve an uptime commitment from an enterprise agreement or parse incident data from system logs stored in R2, a direct connector streams the entire multi-megabyte log export or lengthy specification PDF into prompt context.

Dumping raw files into prompt memory creates severe operational defects:

* Irrelevant text, serialized data, and formatting code consume token allowances, displacing earlier conversation history and instructions.
* Inference latency increases because the model must compute attention across thousands of irrelevant tokens.
* If the file exceeds the context window, the tool call fails outright or triggers aggressive middle-out truncation that cuts out critical answers.

### 3. Class A and Class B Operation Accumulation

Cloudflare R2 does not charge egress fees, but it does meter storage operations:

* **Class A Operations**: Mutating actions such as `PutObject`, `ListBuckets`, and `ListObjects` incur request charges once bucket usage exceeds the included monthly allowance.
* **Class B Operations**: Read actions such as `GetObject` and `HeadObject` incur per-request charges across high-volume pipelines.

An autonomous agent executing unconstrained crawl loops across large buckets issues hundreds of Class A listing requests and Class B read checks during a single reasoning session. Without local caching or pre-indexing, repetitive agent exploration generates unnecessary operational requests and network latency.

## Pre-Indexed Workspaces for Context-Efficient Agent Retrieval

To overcome virtual path crawling and context bloat, engineering teams place an intelligent workspace layer between Cloudflare R2 and their autonomous AI agents. Rather than replacing Cloudflare R2, teams keep their primary object storage intact and sync target documentation, specifications, and data dumps into an intelligent Fast.io workspace.

### The 4-Step Configuration Workflow

1. **Maintain Cloudflare R2 as Primary Storage**: Keep your primary data lake, application logs, and model artifacts securely in Cloudflare R2 without altering existing cloud infrastructure.
2. **Sync Target Directories to Fast.io**: Connect folders into an isolated Fast.io workspace (one-way or two-way, on a schedule or on demand; Google Drive imports today with sync coming soon; never real-time).
3. **Automatic Pre-Indexing via Intelligence Mode**: When documents enter the workspace, Intelligence Mode parses, chunks, and indexes them immediately. Text extraction and OCR handle PDFs, markdown files, spreadsheets, and scanned documents, building hybrid vector and full-text keyword indexes.
4. **Query Precise Passages over Remote MCP**: The agent connects to Fast.io's remote MCP endpoint at `https://mcp.fast.io/mcp/key` using a scoped API key. The agent executes hybrid search queries to pull targeted paragraph excerpts with source citations, keeping prompt context lean.

### Passage-Level Excerpt Retrieval vs. Full-Object Pulls

The decisive advantage of an indexed workspace is passage-level retrieval. When an agent queries a lengthy operational manual or complex technical specification, it does not download the complete file into prompt context. The agent issues a search query through Fast.io's consolidated MCP tools:

* The workspace search engine evaluates keyword matches and semantic meaning across the indexed corpus.
* The MCP tool returns only the two or three relevant paragraphs containing the exact answer, accompanied by file names, page numbers, and snippet metadata.
* The agent's prompt context remains uncluttered, preserving token budgets for reasoning, coding, and decision-making.

### Structured Document Extraction with Metadata Views

For tabular datasets, legal agreements, receipts, and invoices stored in Cloudflare R2, teams use [Metadata Views](/product/document-data-extraction/) to convert unstructured documents into queryable database tables.

Users describe the target fields in plain English, and the system generates a typed schema across seven data types: Text, Integer, Decimal, Boolean, URL, JSON, and Date & Time. The workspace extracts values automatically without requiring brittle regex patterns or template definitions:

* **Financial Records**: Extract invoice numbers, vendor names, issue dates, and total amounts into structured columns.
* **Vendor Contracts**: Pull expiration dates, renewal terms, liability caps, and counterparty entities.
* **Technical Assets**: Index software versions, hardware configurations, and log severity levels.

AI agents query Metadata Views directly over MCP to retrieve filtered, typed records without reading raw source files.

## Step-by-Step Configuration for Claude Code, Cursor, and Desktop Agents

Configuring AI agents to connect to Cloudflare R2 and remote indexed workspaces requires adding the appropriate endpoints to your MCP client configuration file.

### Step 1: Configure Cloudflare API MCP Server

For direct Cloudflare infrastructure management, add the official remote Streamable HTTP server to your client configuration.

In Claude Desktop (`claude_desktop_config.json`) or Cursor (`mcpServers` setting):

```json
{
  "mcpServers": {
    "cloudflare": {
      "url": "https://mcp.cloudflare.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_CLOUDFLARE_API_TOKEN"
      }
    }
  }
}
```

When running Claude Code in the terminal, you can install the official Cloudflare skill bundle directly:

```bash
/plugin marketplace add cloudflare/skills
```

### Step 2: Configure Dedicated S3-Compatible R2 Tools

If you prefer standard S3 primitives for direct object reads and writes, configure an S3-compatible MCP bridge pointing to your R2 bucket endpoint:

```json
{
  "mcpServers": {
    "cloudflare-r2": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-s3"],
      "env": {
        "AWS_ACCESS_KEY_ID": "YOUR_R2_ACCESS_KEY_ID",
        "AWS_SECRET_ACCESS_KEY": "YOUR_R2_SECRET_ACCESS_KEY",
        "AWS_REGION": "auto",
        "AWS_ENDPOINT_URL_S3": "https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com"
      }
    }
  }
}
```

### Step 3: Register Fast.io Remote MCP for Pre-Indexed Search

For tasks requiring semantic document search, Metadata Views extraction, and multi-agent coordination without local daemon overhead, register Fast.io's remote MCP server. Fast.io exposes Streamable HTTP at `/mcp` and legacy SSE at `/sse`.

Every organization starts with a 14-day free trial, which requires a credit card. Creating an account on Fast.io is free; doing real work requires an organization on a paid subscription. Paid subscription tiers on [Fast.io pricing](/pricing/) include Starter, Business, and Enterprise plans.

Add the remote endpoint to your client configuration:

```json
{
  "mcpServers": {
    "fastio": {
      "url": "https://mcp.fast.io/mcp/key",
      "headers": {
        "Authorization": "Bearer YOUR_FASTIO_API_KEY"
      }
    }
  }
}
```

With this configuration, your agent uses direct R2 tools when it needs to write raw bucket backups, and queries Fast.io when it needs to analyze, search, or extract answers from complex documentation sets.

## Multi-Agent Coordination and Governance Across Shared Buckets

In production systems, multiple autonomous agents often work concurrently alongside human developers. When multiple agents read, analyze, and update shared files, teams need safeguards against conflicting writes and silent regressions.

### Per-File Version History

When an agent modifies an existing file or writes an updated dataset, uncoordinated overwrites can destroy critical information. Fast.io maintains complete per-file version history for every document in a workspace. If a coding agent produces an invalid configuration file or truncates an analytical summary, human operators or supervisor agents can inspect earlier revisions and restore prior states immediately.

### Append-Only Audit Logging

Security and operational governance require knowing exactly which agent touched which file. Fast.io provides an immutable, append-only audit log that records every workspace interaction:

* **User and Agent Identification**: Every search query, document download, file creation, and metadata extraction records the specific agent identity or human user key.
* **Timestamped Operations**: Operations are logged sequentially with precise timestamps, tracking file access patterns across multi-agent workflows.
* **Non-Repudiation**: Logs cannot be modified or deleted by agents, providing an auditable trail for compliance reviews and prompt debugging.

### Agent-to-Human Ownership Transfer

External contractors, system integrators, and autonomous setup agents frequently configure storage environments on behalf of client teams. In Fast.io, an agent can create an organization, configure workspace folders, set up R2 sync, define Metadata Views schemas, and test prompts. Once setup is complete, the agent transfers organization ownership to a human stakeholder through a secure claim link while retaining administrative access to continue automated tasks.

## Frequently asked questions

### How do I connect Cloudflare R2 to an MCP client?

You can connect Cloudflare R2 to an MCP client by using the official Cloudflare API MCP server at `https://mcp.cloudflare.com/mcp` over Streamable HTTP, or by configuring an S3-compatible MCP server with your R2 Account ID, Access Key ID, and Secret Access Key. Adding the server endpoint and authorization headers to your client configuration file allows agents like Claude Code and Cursor to list buckets, query objects, and upload files.

### Can Claude Code access Cloudflare R2 buckets?

Yes. Claude Code can access Cloudflare R2 buckets either by installing the official Cloudflare skills plugin via `/plugin marketplace add cloudflare/skills` or by registering Cloudflare's remote MCP server in its settings. Claude Code can then search and execute R2 API operations or inspect pre-indexed files synced to a workspace.

### What is the difference between S3 and Cloudflare R2 for AI agent storage?

The main difference is pricing structure. Cloudflare R2 provides an S3-compatible API but eliminates data transfer egress fees, making it significantly more cost-effective for AI agents frequently reading large datasets or model weights. However, both services share the architectural limitation of flat key-value object stores, requiring indexing layers to prevent prompt token bloat during agent queries.

### How do I prevent agents from blowing context limits on large Cloudflare R2 objects?

Avoid downloading entire raw objects into prompt memory through direct `GetObject` tool calls. Instead, sync target bucket directories into an intelligent workspace where documents are parsed, chunked, and indexed with hybrid search. Agents retrieve targeted paragraph excerpts and citations through MCP search tools, preserving token budgets for reasoning.

### What tools does the Cloudflare API MCP server expose for R2?

Rather than exposing separate individual tools for every endpoint, the Cloudflare API MCP server uses Code Mode with `search()` and `execute()` tools. The agent searches Cloudflare's OpenAPI specification for R2 operations (such as listing buckets or managing objects) and executes JavaScript calls against the API in an isolated runtime environment.

### How does a pre-indexed workspace differ from a raw R2 MCP connector?

A raw R2 MCP connector interacts directly with object storage APIs, performing unindexed file downloads and sequential prefix listings. A pre-indexed workspace processes files upon arrival, applying text extraction, optical character recognition, and hybrid semantic search so agents retrieve precise answers and metadata rather than streaming multi-megabyte files into prompt context.

## Sources

- [Cloudflare Docs: R2 Pricing](https://developers.cloudflare.com/r2/pricing/) — Cloudflare R2 does not charge data transfer fees for egressing objects to the Internet.
- [Cloudflare Docs: Cloudflare's own MCP servers](https://developers.cloudflare.com/agents/model-context-protocol/mcp-servers-for-cloudflare/) — Cloudflare runs managed remote MCP servers that connect AI clients to account services using the Model Context Protocol.

## About Fast.io

Fast.io provides shared workspaces where people and AI agents work on the same files, with built-in semantic search and citation-backed chat over what they hold. Agents reach it through a remote MCP server at https://mcp.fast.io/mcp, a REST API at https://api.fast.io/current/, and a command line client published on npm as @vividengine/fastio-cli.
