Skip to main content
Glama
Greta221

cf-mcp-traffic

by Greta221
README.md
# cf-mcp-traffic

A local stdio MCP server that exposes Cloudflare HTTP traffic and firewall analytics to Claude Code. Query traffic by 20+ dimensions, drill into individual actors, and score suspicion against a documented rulebook. Includes a deterministic scorer so it can run without Claude. Local-only, not deployed.

## What it exposes

Four MCP tools plus a helper:

- **`list_known_domains`** — the zones configured in your `domains.json`
- **`traffic_summary`** — aggregated bucket counts from `httpRequestsAdaptiveGroups`, grouped by up to 3 of ~20 dimensions (ASN, path, IP, JA4, country, status, bot_score_bucket, time_hour, etc.)
- **`firewall_events`** — same shape but on WAF / rate-limit / bot-management / custom-rule actions, with rule descriptions
- **`requests_for`** — sampled per-request drilldown, filtered by IP / JA4 / ASN / path / UA / status
- **`score_actor`** — runs the deterministic scorer against a pre-aggregated `ActorSignals` bundle

The scoring logic lives in `src/lib/scoring.ts`. It's a pure function — no I/O, no globals, importable from any TS runtime.

## Prerequisites

- [Bun](https://bun.sh) installed locally
- A Cloudflare API token with `Account Analytics:Read` + `Zone Analytics:Read` on every zone you want to query. Generate at [https://dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens).

## Setup

### 1. Clone and install

```
git clone git@github.com:Greta221/cf-mcp-traffic.git
cd cf-mcp-traffic
bun install
```

### 2. Create your data directory

The server reads all account-specific config from a local directory pointed at by the `CF_MCP_TRAFFIC_DATA_DIR` env var. Nothing account-specific ships with the code.

```
mkdir -p ~/.cf-mcp-traffic-data
```

Populate two files inside it:

**`.env`** — your credentials:

```
CF_API_TOKEN=your_token_here
CF_ACCOUNT_ID=your_account_id_here
```

**`domains.json`** — a flat map from domain name to its Cloudflare zone tag:

```
{
  "example.com": "your_zone_tag_here",
  "another-example.com": "another_zone_tag"
}
```

Zone tags come from the Cloudflare dashboard: **Zone overview → API → Zone ID**.

### 3. Wire it into Claude Code

Add the server to `~/.claude.json` (or the project-local `.mcp.json`):

```json
{
  "mcpServers": {
    "cf-traffic": {
      "type": "stdio",
      "command": "bun",
      "args": ["run", "/absolute/path/to/cf-mcp-traffic/src/index.ts"],
      "env": {
        "CF_MCP_TRAFFIC_DATA_DIR": "/absolute/path/to/your/.cf-mcp-traffic-data"
      }
    }
  }
}
```

Restart Claude Code. The `cf-traffic` server should appear in `/mcp`.

## Optional: watch list, trust list, site patterns

Two markdown files and one JSON, all in your data directory. Only needed if you use the `/triage-traffic` runbook (see below) or the `score_actor` tool with trust penalties.

- **`watch-list.md`** — actors observed misbehaving but not severe enough to block. Log the actor, the reason, and the trigger for revisiting.
- **`trust-list.md`** — known-good sources (payment webhooks, internal infra, verified crawlers). Membership drives negative penalties on scored actors.
- **`site-patterns.json`** — your account's API hosts, application URL patterns, sensitive POST endpoints. Drives several signals. Expected keys:

```json
{
  "api_hosts": ["api.example.com"],
  "api_path_prefixes": ["/api/", "/v1/"],
  "html_paths": ["/", "/profile"],
  "asset_path_prefixes": ["/static/", "/assets/"],
  "asset_file_extensions": [".css", ".js", ".png"],
  "sensitive_post_paths": ["/login", "/checkout/pay"]
}
```

None of these files are required to boot the server. Signals that depend on missing files simply don't fire.

## Running the scorer without Claude

The scorer is a pure function. Import and call it:

```ts
import { scoreActor } from "./src/lib/scoring";
import type { ActorSignals } from "./src/lib/types";

const input: ActorSignals = {
  identifier_type: "ip",
  identifier: "1.2.3.4",
  // ...populate the remaining fields from your own aggregations
};

const result = scoreActor(input);
console.log(result.score, result.reasons);
```

Signal names, weights, and thresholds are in `src/lib/constants.ts`. Input and output types are in `src/lib/types.ts`.

## The scoring rulebook

The scoring policy (how signals fire, what they mean, how trust penalties work, worked examples) lives at `.claude/commands/triage-traffic.md`. It's a slash command Claude Code reads — you can invoke it with `/triage-traffic` inside Claude, or read it as documentation for the scoring model.

The rulebook and the code are kept in sync: rulebook signal names match the `SIGNAL` constants in `src/lib/constants.ts`.

## Development

```
bun run test       # vitest, single run
bun run test:watch
bun run check      # biome lint + format check
```

## Design notes

- Stdio MCP server, not a Worker. Runs locally on demand when Claude invokes a tool.
- `requests_for` returns sampled data (~1% on busy zones). Never use it for path or host counts — always use `traffic_summary` aggregations for those.
- The `score_actor` tool takes a pre-computed `ActorSignals` object. Aggregating the signals from raw traffic queries is the caller's job (Claude does this in-session by reading the rulebook and calling the query tools).