Skip to main content
Glama
cloud-drive-mcp
by kzarzycki
README.md
# cloud-drive-mcp

Scoped, version-checked **Streamable HTTP** (and `stdio`) Model Context Protocol server for **Google Drive**, **OneDrive**, and **SharePoint**.

## Why

Cloud drive sync clients and raw Drive API calls are unsafe for concurrent AI agents:

- **Silent overwrites:** Google Drive v3 ignores HTTP `If-Match` headers and overwrites concurrent edits silently with no conflict copy.
- **Over-broad OAuth access:** Generic Drive MCP servers expose your entire Drive instead of one workspace folder.
- **Expiring OAuth tokens in cloud sandboxes:** Agent environments that inject static proxy headers cannot refresh 1-hour OAuth access tokens.

`cloud-drive-mcp` puts a thin, root-jailed server in front of a single cloud folder:

- **Strict root-folder jail:** Every path is relative to one configured folder ID/path; `..` and absolute paths are rejected.
- **Per-path write lock + optimistic concurrency:** Every `write_file`, `patch_file`, and `delete_file` requires `expected_version` (`headRevisionId:sha256` on Google Drive; native `If-Match: <eTag>` on Microsoft Graph).
- **Contention-free logging:** `append_event` writes immutable, uniquely named event files.
- **Trash-only deletes:** `delete_file` moves files to Trash after verifying `expected_version`.
- **Two interchangeable backends:** Switch between Google Drive (`STORAGE_BACKEND=gdrive`) and Microsoft OneDrive / SharePoint (`STORAGE_BACKEND=graph`) via environment variables.

---

## 5-Minute Setup (Google Drive + Docker)

**Requirements:** Node.js 24+ (for the one-time OAuth helper) and Docker (or just Node.js 24+ to run directly).

### 1. Create a dedicated Google OAuth Desktop client

1. Open [Google Cloud Console](https://console.cloud.google.com/) and pick (or create) a project.
2. Enable the **Google Drive API** (*APIs & Services → Library → Google Drive API → Enable*).
3. Configure the **OAuth consent screen** (*External*, add your own Google account under **Test users** — no Google verification needed for personal use).
4. Go to **APIs & Services → Credentials → + Create Credentials → OAuth client ID**:
   - Application type: **Desktop app** (e.g. `cloud-drive-mcp`).
   - Tick **"Use this client for an AI-powered agent"** if shown (recommended by Google for agent/MCP clients).
5. Click **Download JSON** (`client_secret_*.json`).

### 2. Authorize your Drive folder and generate `.env`

Open the Google Drive folder you want to expose in your browser and copy its URL (or just the ID after `/folders/`). Then run:

```bash
git clone https://github.com/kzarzycki/cloud-drive-mcp.git
cd cloud-drive-mcp
node scripts/gdrive-oauth.mjs ~/Downloads/client_secret_*.json
```

*(On a headless server, add `--manual` to paste the redirected `http://127.0.0.1:53683/callback?...` URL from another machine's browser.)*

The script opens a one-time Google consent URL, exchanges the code for a Drive-only refresh token, generates a random `MCP_AUTH_TOKEN`, and writes a mode-`0600` `.env` file without printing any secrets. Delete the downloaded `client_secret_*.json` afterward.

### 3. Start the server

With Docker Compose (hardened: read-only rootfs, non-root `node` user, bound to `127.0.0.1:8787`):

```bash
docker compose up -d
curl -fsS http://127.0.0.1:8787/health
# {"status":"ok","server":"cloud-drive-mcp"}
```

Or directly with Node 24 (no Docker):

```bash
npm ci --omit=dev
node --env-file=.env src/http.ts
```

### 4. Expose securely over HTTPS (self-hosted, privacy-first)

Keep your private files off third-party edge proxies by exposing `127.0.0.1:8787` directly from your own host:

- **Tailscale (easiest, private to your tailnet):**
  ```bash
  tailscale serve --bg --https=8787 http://127.0.0.1:8787
  ```
  Your endpoint is now `https://<your-host>.<your-tailnet>.ts.net:8787/mcp`.

- **Public HTTPS (e.g. Caddy with automatic Let's Encrypt TLS):**
  ```caddyfile
  mcp.example.com {
      reverse_proxy 127.0.0.1:8787
  }
  ```

### 5. Connect an MCP client

**Claude Code (remote Streamable HTTP):**

```bash
claude mcp add --transport http cloud-drive https://<your-host>:8787/mcp \
  --header "Authorization: Bearer <your-MCP_AUTH_TOKEN>"
```

**Generic MCP JSON config (Streamable HTTP):**

```json
{
  "mcpServers": {
    "cloud-drive": {
      "type": "http",
      "url": "https://<your-host>:8787/mcp",
      "headers": {
        "Authorization": "Bearer <your-MCP_AUTH_TOKEN>"
      }
    }
  }
}
```

**Local `stdio` (no HTTP server needed):**

```json
{
  "mcpServers": {
    "cloud-drive": {
      "command": "node",
      "args": ["--env-file=/path/to/cloud-drive-mcp/.env", "/path/to/cloud-drive-mcp/src/server.ts"]
    }
  }
}
```

---

## Microsoft OneDrive / SharePoint Setup (`STORAGE_BACKEND=graph`)

1. Register an app in Microsoft Entra ID with Microsoft Graph permissions (`Files.ReadWrite` for delegated refresh-token auth, or `Sites.Selected` for app-only SharePoint access).
2. Set the Graph variables in `.env` (see [`.env.example`](.env.example)):
   ```dotenv
   STORAGE_BACKEND=graph
   GRAPH_TENANT_ID=...
   GRAPH_CLIENT_ID=...
   GRAPH_CLIENT_SECRET=...
   GRAPH_REFRESH_TOKEN=... # optional; omit for client-credentials flow
   GRAPH_DRIVE_ID=...
   GRAPH_ROOT_PATH=Shared Documents/workspace
   MCP_AUTH_TOKEN=...
   ```
3. Start with `docker compose up -d`. All updates send HTTP `If-Match: <eTag>` natively so Microsoft Graph enforces stale-write rejection server-side (`412 Precondition Failed` → structured `CONFLICT`).

---

## Optional: Cloudflare Workers + Durable Objects

If you prefer a serverless deployment and are comfortable with Cloudflare terminating TLS and holding the OAuth refresh token, a Worker + Durable Object entrypoint (`src/worker.ts`) is included:

1. Copy `wrangler.jsonc.example` to `wrangler.jsonc` and set your route/custom domain.
2. Front the Worker with **Cloudflare Access** or set `MCP_AUTH_TOKEN` via `wrangler secret put MCP_AUTH_TOKEN`.
3. Set backend secrets via `wrangler secret put` (see [`.env.example`](.env.example)).
4. Deploy with `wrangler deploy`.

---

## Tools

| Tool | Purpose |
|---|---|
| `list_tree` | List files and folders under a relative path (`depth` 1–5). |
| `search_files` | Case-insensitive filename/path search scoped to the jailed workspace root. |
| `read_file` | Read UTF-8 text and return `{ content, version, size, modified_at }`. |
| `write_file` | Create (`expected_version: null`) or compare-and-swap overwrite under per-path lock. |
| `patch_file` | Replace a unique substring under per-path lock + `expected_version`. |
| `append_event` | Write an immutable `<dir>/<utc>-<prefix>-<rand6>.<ext>` event file. |
| `delete_file` | Move a file to Trash after verifying `expected_version`. |

---

## Desktop & Mobile Sync Note

Laptops and phones can keep syncing the same cloud folder natively alongside `cloud-drive-mcp` (Google Drive for Desktop, OneDrive, or FolderSync on Android). On macOS, pin the synced folder to **Available offline** (Drive for Desktop) or **Always keep on this device** (OneDrive) so Apple FileProvider does not leave remotely edited files as dataless placeholders (`EDEADLK` on CLI reads).

### Optional: YAML Configuration (`config.yaml`)

If you prefer YAML over environment variables for non-secret settings (recommended for configuration-as-code), copy [`config.example.yaml`](config.example.yaml) to `config.yaml` (auto-loaded from `./config.yaml` or `CONFIG_PATH=/path/to/config.yaml`). Keep secrets (`DRIVE_CLIENT_ID`, `DRIVE_CLIENT_SECRET`, `DRIVE_REFRESH_TOKEN`, `MCP_AUTH_TOKEN`) in `.env` or your secret manager; explicit environment variables always override YAML values.

### Optional: Detecting Non-MCP Blind Overwrites on Google Drive

Because Google Drive v3 ignores `If-Match`, an offline desktop or mobile edit that uploads *after* another edit can silently replace the head revision. Configure `overwriteWatch` in `config.yaml` (or `OVERWRITE_WATCH_*` env vars) to detect and recover those clashes automatically using Drive's global `changes.list` cursor (**1 API call per poll globally**):

- `mode: off` *(default)* | `log` *(structured JSON warning)* | `sidecar` *(warning + saves overwritten content to `<name>.conflict-<utc>.<ext>`)*
- `scope: mcp` *(default: watches recent MCP writes only; 0 API calls when idle)* | `all` *(watches all text files under `rootFolderId`, also catching non-MCP ↔ non-MCP overwrites such as Mac ↔ Android)*
- `intervalMs` *(default `60000`)*, `ttlMs` *(default `86400000`, 24h)*, `nonMcpWindowMs` *(default `600000`, 10m)*

Microsoft OneDrive/SharePoint already enforces `If-Match` natively and creates desktop conflict copies, so the watcher is only needed for Google Drive.

## Development

```bash
npm install
npm test
npm run typecheck
npm run check
```

## License

MIT