# Using Swarm MCP for Storing Context in AI Models: Implementation Guide

> Learn how to use Swarm MCP to store AI model context on Swarm's decentralized network. Achieve reproducible inference with immutable content addresses and guaranteed retrieval.

- Repository: [Ethersphere/awesome-swarm](https://github.com/ethersphere/awesome-swarm)
- Tags: how-to-guide
- Published: 2026-03-01

---

**Swarm MCP (Model Context Protocol) is a lightweight HTTP server that enables AI applications to persist prompt-and-response context on the Swarm decentralized storage network, generating immutable content addresses (Swarm hashes) that guarantee retrieval of the exact same data for reproducible inference.**

Swarm MCP bridges large language model workflows with decentralized storage by wrapping the Bee client HTTP API into a semantic layer for model context. As listed in the [ethersphere/awesome-swarm](https://github.com/ethersphere/awesome-swarm) repository, this tool allows developers to offload session state to content-addressable storage, eliminating the need for centralized databases in AI pipelines.

## How Swarm MCP Works with Bee Storage

Swarm MCP operates as a thin abstraction over a locally-running **Bee node** (the Swarm client). All data is stored as immutable Swarm chunks via Bee’s **`/bytes`** endpoint (`POST /bytes`), which returns a unique Swarm hash that serves as the canonical reference for the uploaded content.

### The MCP API Surface

The server exposes a minimal HTTP API that adds semantic meaning for AI context management:

- **`POST /context`** – Accepts a JSON payload (e.g., `{ "sessionId": "...", "messages": [...] }`), serializes the data to raw bytes, and forwards it to the Bee node. The response contains the Swarm hash (a `bzz://` URL) that uniquely identifies that context snapshot.
- **`GET /context/:hash`** – Retrieves raw bytes from Bee using `GET /bytes/:hash`, deserializes the JSON, and returns the original context object.

Because Swarm is content-addressable, every modification produces a new hash, enabling immutable versioning. You can maintain a complete history of context snapshots simply by storing the returned hashes in a relational database or key-value store.

### Security and Configuration

Data is encrypted before transmission to the Bee node. In [`config/default.json`](https://github.com/ethersphere/awesome-swarm/blob/main/config/default.json), you can configure a user-provided symmetric key; only holders of this key can decrypt retrieved context, while the Swarm network only stores opaque ciphertext.

## Storing and Retrieving AI Context

### Uploading Conversation History via cURL

To store a conversation thread, serialize your messages as JSON and POST to the MCP server:

```bash

# Prepare JSON payload

payload='{
  "sessionId":"abc123",
  "messages":[
    {"role":"system","content":"You are a helpful assistant."},
    {"role":"user","content":"Explain Swarm MCP."}
  ]
}'

# Upload to MCP – it forwards to Bee and returns a Swarm hash

hash=$(curl -s -X POST https://mcp.example.com/context \
        -H "Content-Type: application/json" \
        -d "$payload" | jq -r .hash)

echo "Context stored at Swarm hash: $hash"

```

### Fetching Stored Context

Retrieve the exact same data using the hash returned during storage:

```bash
curl -s https://mcp.example.com/context/$hash \
     -H "Accept: application/json" | jq .

```

### Programmatic Integration with bee-js

For Node.js applications, combine the MCP HTTP interface with the `@ethersphere/bee-js` library:

```javascript
import { Bee } from '@ethersphere/bee-js'

const bee = new Bee('http://localhost:1633')   // local Bee node
const mcpUrl = 'https://mcp.example.com'

async function storeContext(sessionId, messages) {
  const payload = { sessionId, messages }
  const res = await fetch(`${mcpUrl}/context`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  })
  const { hash } = await res.json()
  return hash
}

async function loadContext(hash) {
  const res = await fetch(`${mcpUrl}/context/${hash}`)
  return await res.json()
}

// Example usage
const hash = await storeContext('run‑42', [{ role: 'user', content: 'Hello' }])
const ctx  = await loadContext(hash)
console.log('Recovered context:', ctx)

```

## Core Source Files

According to the [ethersphere/swarm-mcp](https://github.com/ethersphere/swarm-mcp) source code, three files implement the end-to-end persistence flow:

- **[`server.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/server.ts)** – The Express-based HTTP server that wires the `/context` endpoints to the underlying Bee client calls.
- **[`routes/context.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/routes/context.ts)** – Defines request/response schemas, validates JSON structure, and handles serialization before forwarding raw bytes to Bee.
- **[`config/default.json`](https://github.com/ethersphere/awesome-swarm/blob/main/config/default.json)** – Stores runtime configuration including the Bee node URL (`http://localhost:1633` by default) and optional encryption parameters.

## Key Benefits for AI Workflows

- **Stateless inference servers**: Offload context persistence to Swarm, allowing servers to restart without losing session state or requiring sticky sessions.
- **Multi-node orchestration**: In Kubernetes or Docker Swarm environments, any pod can retrieve identical context using the hash, enabling true horizontal scalability.
- **Regulatory auditability**: Immutable hashes provide a cryptographically verifiable audit trail of exactly which data was used for a specific inference, critical for compliance.
- **Cost-effective long-term storage**: Swarm’s incentivized storage model offers predictable, low-cost retention compared to centralized cloud databases.

## Summary

- **Swarm MCP** acts as a semantic bridge between AI applications and the Swarm network, exposing `POST /context` and `GET /context/:hash` endpoints.
- Data is stored via the Bee **POST /bytes** endpoint, ensuring content-addressability and immutability.
- All context is encrypted before reaching the Swarm network, with keys managed via [`config/default.json`](https://github.com/ethersphere/awesome-swarm/blob/main/config/default.json).
- The implementation relies on three core files: [`server.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/server.ts), [`routes/context.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/routes/context.ts), and [`config/default.json`](https://github.com/ethersphere/awesome-swarm/blob/main/config/default.json).
- Swarm hashes enable reproducible AI inference, versioned context history, and stateless server architectures.

## Frequently Asked Questions

### How does Swarm MCP differ from using the Bee API directly?

Swarm MCP adds a semantic layer specifically for AI model context, handling JSON serialization, encryption, and session management conventions that the raw Bee `/bytes` endpoint does not provide. While Bee stores opaque byte arrays, MCP structures the data as conversation histories with dedicated routes in [`routes/context.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/routes/context.ts).

### Can Swarm MCP handle encryption for sensitive AI training data?

Yes. Before forwarding bytes to the Bee node, MCP encrypts payloads using a symmetric key configured in [`config/default.json`](https://github.com/ethersphere/awesome-swarm/blob/main/config/default.json). The Swarm network only stores the encrypted ciphertext, and only parties possessing the original key can decrypt the data retrieved via `GET /context/:hash`.

### Why are Swarm hashes ideal for reproducible AI inference?

Swarm hashes are **content-addressable**, meaning the hash is cryptographically derived from the data itself. This guarantees that retrieving a specific hash always yields the exact same bytes, eliminating drift in training or inference contexts and providing tamper-proof audit trails for regulatory compliance.

### Which Bee endpoint does MCP use for raw byte storage?

Internally, [`server.ts`](https://github.com/ethersphere/awesome-swarm/blob/main/server.ts) forwards all serialized context payloads to the Bee node’s **`POST /bytes`** endpoint. Bee then splits the data into immutable chunks and returns the root hash, which MCP surfaces to the client as the canonical reference for that context snapshot.