# How to Set Up the Headroom MCP Server for External MCP Clients

> Learn to set up the Headroom MCP server for external clients using `headroom mcp serve`. Integrate AI coding assistants like Claude Code, Cursor, and Codex with Headroom's context engineering.

- Repository: [Tejas Chopra/headroom](https://github.com/chopratejas/headroom)
- Tags: how-to-guide
- Published: 2026-06-14

---

**You can run Headroom's MCP server via `headroom mcp serve` to expose compression and retrieval tools over stdio, enabling external AI coding assistants like Claude Code, Cursor, and Codex to integrate with Headroom's context-engineering capabilities.**

Headroom ships with a full **Model Context Protocol (MCP)** implementation that allows external clients to access its compression, retrieval, and statistics capabilities through the standard MCP stdio transport. This guide covers the complete setup process—from installation and CLI usage to programmatic integration—based on the actual source code in the `chopratejas/headroom` repository.

## Installation and Prerequisites

Before starting the server, you must install Headroom with the MCP extras to pull in the required SDK dependencies.

```bash
pip install "headroom-ai[mcp]"

```

The MCP SDK is imported in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) (lines 48-56), and the server will raise a clear `ImportError` if the package is missing, prompting you to run `pip install mcp`.

## Starting the MCP Server

### Via the CLI (Recommended)

The simplest way to start the server is using the built-in CLI command:

```bash
headroom mcp serve

```

This command, implemented in [`headroom/cli/mcp.py`](https://github.com/chopratejas/headroom/blob/main/headroom/cli/mcp.py) (lines 325-352), creates a `HeadroomMCPServer` instance via `create_ccr_mcp_server()` and starts the stdio transport loop. The server reads tool invocations from stdin and writes JSON responses to stdout, blocking until the process terminates.

### Programmatically from Python

You can also instantiate the server directly in your own scripts:

```python
import asyncio
from headroom.ccr.mcp_server import create_ccr_mcp_server

async def main() -> None:
    server = create_ccr_mcp_server()  # Uses default proxy URL

    await server.run_stdio()          # Blocks on stdio transport

if __name__ == "__main__":
    asyncio.run(main())

```

This mirrors the CLI implementation exactly, calling the same `create_ccr_mcp_server()` factory function defined in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) (lines 890-904).

## Core Architecture and Components

The MCP server architecture consists of several tightly integrated components:

- **`HeadroomMCPServer`** – The main server class defined in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) that registers tool handlers in `_setup_handlers()` (lines 84-100) and manages the stdio event loop via `run_stdio()`.
- **`create_ccr_mcp_server()`** – A factory function that returns a configured server instance with optional proxy URL settings.
- **Proxy fallback** – When `HEADROOM_PROXY_URL` is set (defaulting to `http://127.0.0.1:8787`), the server delegates retrieval of missing hashes to the Headroom proxy via `_retrieve_via_proxy()` (lines 58-73).
- **Shared stats** – All MCP instances write telemetry to a session-scoped JSONL file managed by `_append_shared_event()` and `_read_shared_events()` (lines 79-92).

## Connecting External MCP Clients

Any MCP-compatible client can connect to Headroom using the stdio transport. Below is a complete Python example using the official `mcp` client library to interact with the server as an external process.

```python
import subprocess
import json
from mcp.client import Client  # pip install mcp

# Launch the Headroom MCP server as a subprocess

proc = subprocess.Popen(
    ["headroom", "mcp", "serve"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True,
)

# Wrap the process streams with the MCP client

client = Client(proc.stdout, proc.stdin)

# Call the compress tool

payload = {"content": "def very_long_function():\n    # ... many lines ..."}

response = client.call_tool("headroom_compress", payload)
result = json.loads(response[0].text)

print(f"Compressed hash: {result['hash']}")
print(f"Tokens saved: {result['tokens_saved']}")

```

## Available MCP Tools

The server exposes three core tools by default, with an optional fourth:

1. **`headroom_compress`** – Accepts content and returns a hash identifier along with token savings statistics.
2. **`headroom_retrieve`** – Accepts a hash and returns the original decompressed content, with automatic fallback to the proxy if the hash is not in local memory.
3. **`headroom_stats`** – Returns session-wide usage statistics as human-readable text or JSON.
4. **`headroom_read`** (optional) – Exposed only when `HEADROOM_MCP_READ` is set to `on`, `true`, or `1`.

Tool registration occurs in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) during server initialization, ensuring the capability list is advertised to connecting clients immediately upon handshake.

## Configuration Options

The server behavior is controlled via environment variables read at import time in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) (lines 78-84):

| Variable | Purpose | Default |
|----------|---------|---------|
| `HEADROOM_PROXY_URL` | URL of the Headroom proxy for fallback retrieval | `http://127.0.0.1:8787` |
| `HEADROOM_MCP_READ` | Enables the optional `headroom_read` tool when set to `on`/`true`/`1` | `off` |

To register the server with Claude Code specifically, use the install subcommand:

```bash
headroom mcp install

```

This writes a TOML configuration block into Claude's settings file, pointing to the `headroom mcp serve` executable.

## Summary

- Install the MCP extras with `pip install "headroom-ai[mcp]"` to satisfy the SDK dependency.
- Start the server using `headroom mcp serve` or programmatically via `create_ccr_mcp_server().run_stdio()`.
- External clients communicate over stdio using any MCP-compatible library, with tools registered in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py).
- Configure proxy fallback via `HEADROOM_PROXY_URL` and enable the read tool via `HEADROOM_MCP_READ`.
- The server automatically handles compression, retrieval (with proxy fallback), and shared statistics collection across all connected clients.

## Frequently Asked Questions

### How do I connect the Headroom MCP server to Claude Code?

Run `headroom mcp install` from your terminal. This command writes the necessary configuration to Claude Code's settings file, pointing it to the `headroom mcp serve` command. Once installed, Claude Code will automatically spawn the server process and communicate with it over stdio when you invoke Headroom-powered tools.

### What happens if the Headroom proxy is not running?

The MCP server operates in a **stand-alone mode** by default, using an in-memory database for content storage. If `HEADROOM_PROXY_URL` is set but the proxy is unreachable, the server will attempt proxy fallback via `_retrieve_via_proxy()` and gracefully fall back to local storage if the request fails, ensuring continuous operation without external dependencies.

### Can I use the MCP server without installing the full Headroom package?

No, you need the complete `headroom-ai` package with MCP extras. The server implementation in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py) depends on core Headroom modules for compression logic and statistics aggregation. However, once installed, you can run the server independently without activating other Headroom components like the proxy or IDE extensions.

### Which MCP transport does Headroom use?

Headroom exclusively uses the **stdio transport** (`run_stdio()`) as implemented in [`headroom/ccr/mcp_server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/ccr/mcp_server.py). This design choice ensures compatibility with AI coding assistants that expect to spawn MCP servers as subprocesses and communicate via stdin/stdout pipes, rather than over HTTP or WebSocket connections.