使用说明
Swarm Provenance MCP
⚠️ ALPHA SOFTWARE - PROOF OF CONCEPT This software is in Alpha stage and should be considered a Proof of Concept. Use for testing and experimentation only. Not recommended for production use.
⚠️ DATA PERSISTENCE WARNING Storage on Swarm is rented storage with limited time periods. The default configuration uses very short rental periods (approximately 1 day). Do not expect uploaded data to persist longer than the rental period. Data will become unavailable when the postage stamp expires.
⚠️ TESTNET NOTICE On-chain provenance features use Base Sepolia (testnet) by default. Testnet tokens have no monetary value and testnet state may be reset at any time. Do not rely on testnet anchoring for production data integrity. No warranties of any kind are provided.
A Model Context Protocol (MCP) server for managing Swarm postage stamps and provenance data storage through a centralized FastAPI gateway. Enables AI agents to upload provenance data to the decentralized Swarm network for immutable storage and retrieve it by reference.
Overview
This MCP server provides tools for AI agents to interact with Swarm postage stamps and provenance data storage, including purchasing and extending stamps, uploading provenance data to Swarm for immutable decentralized storage, and downloading data from the network by reference. It acts as a bridge between AI agents and the swarm_connect FastAPI gateway.
Provenance & Immutable Storage
This MCP server is specifically designed for provenance data use cases, leveraging Swarm's decentralized network to provide:
- Immutable Records: Once uploaded, data cannot be altered, ensuring integrity
- Decentralized Storage: No single point of failure or central authority
- Provenance Metadata: Support for structured provenance records with creator, timestamp, and lineage information
- Verifiable Authenticity: Cryptographic integrity verification for uploaded data
Features
- Purchase Stamps: Create new postage stamps with configurable duration and size
- Stamp Status: Get detailed information about specific stamps
- List Stamps: View all available postage stamps
- Extend Stamps: Extend the duration of existing stamps
- Data Upload: Upload data to Swarm network with stamp validation
- Data Download: Download data from Swarm network by reference
- Provenance Storage: Store data with provenance metadata for immutable, verifiable records
- Health Monitoring: Check gateway and Swarm network connectivity
- Chain Diagnostics (optional): Check on-chain wallet balance and RPC connectivity for provenance anchoring
- On-Chain Anchoring (optional): Register Swarm hashes on-chain for immutable provenance records
- Transformation Lineage (optional): Record and trace data transformations through on-chain state reads (v2) or event logs (v1)
- Merge Transformations (optional): Record N-to-1 merge transformations combining multiple source hashes into one
Installation
Prerequisites
- Python 3.10 or higher (use
python3command) - Internet connection (uses public gateway by default)
- Optional: Self-hosted
swarm_connectgateway service (see Gateway Options below)
Setup
- Clone the repository:
git clone https://github.com/datafund/swarm_provenance_MCP.git
cd swarm_provenance_mcp
- Create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install the package:
pip install -e .
- Configure environment variables:
mkdir -p ~/.config/swarm-provenance-mcp
cp .env.example ~/.config/swarm-provenance-mcp/.env
# Edit that file to configure your gateway URL and defaults
Docker
Run the MCP server in a container with no local dependencies.
Registry: The pre-built image is published to GitHub Container Registry only — always use the full
ghcr.io/prefix. It is not available on Docker Hub.
Quick start (pre-built image):
docker pull ghcr.io/datafund/swarm-provenance-mcp:latest
docker run -i --rm ghcr.io/datafund/swarm-provenance-mcp
Build from source:
docker build -t swarm-provenance-mcp .
docker run -i --rm swarm-provenance-mcp
With environment variables:
docker run -i --rm \
-e SWARM_GATEWAY_URL=https://provenance-gateway.datafund.io \
-e DEFAULT_STAMP_DURATION_HOURS=25 \
-e DEFAULT_STAMP_SIZE=small \
swarm-provenance-mcp
Docker Compose:
docker compose build
docker compose run --rm swarm-provenance-mcp
Compose takes its variables from ./.env next to docker-compose.yml (for ${VAR}
substitution and as the container's env_file) and passes them to the server as
environment variables. That is Compose's own file, separate from the server's env file
described under Configuration: the container never sees
~/.config/swarm-provenance-mcp/.env on the host.
| Variable | Description | Default |
|---|---|---|
SWARM_GATEWAY_URL |
Gateway endpoint URL | https://provenance-gateway.datafund.io |
DEFAULT_STAMP_DURATION_HOURS |
Default stamp duration in hours (min 24) | 25 |
DEFAULT_STAMP_SIZE |
Default stamp size: small, medium, or large |
small |
PAYMENT_MODE |
Gateway payment tier (free = 3 write req/min) |
free |
Configuration
Settings come from environment variables, or from an env file. The env file is never read from the working directory (whichever program launches the server controls that). It is read from, in order:
- the path in
SWARM_PROVENANCE_ENV_FILE, if set. It must be an absolute path (~/...is fine); start-up fails if it is relative or the file does not exist; - otherwise
~/.config/swarm-provenance-mcp/.env(or$XDG_CONFIG_HOME/swarm-provenance-mcp/.env), if it exists.
Real environment variables (for example an MCP client's "env" block) override the env file.
Unknown keys in the env file are ignored. If a .env in the working directory is found and
ignored, the server logs a warning at start-up.
-
SWARM_PROVENANCE_ENV_FILE: Explicit absolute path of the env file to load (see above) -
SWARM_GATEWAY_URL: URL of the swarm_connect FastAPI gateway (default:https://provenance-gateway.datafund.io) -
DEFAULT_STAMP_DURATION_HOURS: Default stamp duration in hours, minimum 24 (default:25) -
DEFAULT_STAMP_SIZE: Default stamp size —small,medium, orlarge(default:small) -
PAYMENT_MODE: Gateway payment tier (default:free— rate limited to 3 write requests/minute)
Chain Anchoring (Optional)
CHAIN_ENABLED: Enable on-chain provenance anchoring (default:false)CHAIN_NAME: Blockchain network —base-sepolia(testnet),base(mainnet), orlocalhost(local hardhat, chain 31337) (default:base-sepolia)PROVENANCE_WALLET_KEY: Private key for chain transactions (hex, with or without 0x prefix)CHAIN_RPC_URL: Custom RPC endpoint (uses chain preset if not set)CHAIN_RPC_URLS: Comma-separated fallback RPC URLs, tried in order afterCHAIN_RPC_URLCHAIN_CONTRACT: Custom DataProvenance contract address (uses chain preset if not set).CHAIN_CONTRACT_ADDRESSis accepted too;CHAIN_CONTRACTwins if both are setCHAIN_EXPLORER_URL: Custom block explorer URL (uses chain preset if not set)CHAIN_GAS_LIMIT: Explicit gas limit for chain transactions (skips estimation if set)CHAIN_MAX_FEE_GWEI: Fee cap per gas (maxFeePerGas). Fee fields are set explicitly and a write is refused when the current fee is above the cap (default:0.5on mainnet,10on testnets)CHAIN_SESSION_BUDGET_ETH: Worst-case spend allowed per server session; each transaction reservesgas limit x max feeplus the L1 data fee allowance, and is charged its actual cost (L2 gas plus the receipt'sl1Feeon Base) once mined (default:0.002on mainnet,0.05on testnets)CHAIN_L1_FEE_ALLOWANCE_ETH: L1 data fee reserved per transaction on top of L2 gas (default:0.000001, about 100x the ~1e-8 ETH measured on Base mainnet on 2026-10-21; L2 gas there was 1e-6 to 3e-5 ETH per transaction)CHAIN_MAX_TX_PER_SESSION: Chain transactions allowed per server session (default:20on mainnet,500on testnets)CHAIN_REQUIRE_CONFIRM: Require a confirmed quote on gas-spending tools. Withoutconfirm: trueand a matchingquote_idthey send nothing and return a quote of the exact action (arguments, fee cap, remaining budget) with aquote_id: an HMAC over the tool and its validated arguments under a per-process key, single use, valid 10 minutes (default: mainnet only — any chain id other than 84532, 11155111, 31337 or 1337 counts as mainnet)MAX_STAMP_DURATION_HOURS: Maximumduration_hoursforpurchase_stamp/extend_stamp(default:8760)
When chain is enabled, additional tools become available: chain_balance, chain_health, anchor_hash, verify_hash, get_provenance, record_transform, record_merge_transform, get_provenance_chain, set_storage_ref, lookup_by_storage_ref. Blockchain dependencies (web3, eth-account) are included in the default install. Read-only tools (verify_hash, get_provenance, get_provenance_chain, lookup_by_storage_ref, chain_health) work without a wallet key; write tools (anchor_hash, record_transform, record_merge_transform, set_storage_ref) and chain_balance require PROVENANCE_WALLET_KEY with a funded wallet.
Upgrading from a .env in the repository
Earlier versions read .env from the working directory, so the old setup was
cp .env.example .env in the repository plus "cwd": "/path/to/swarm_provenance_mcp"
in claude_desktop_config.json. That file is no longer read: after upgrading, the server
starts with the defaults (no wallet, CHAIN_ENABLED=false) and only logs a warning.
- Move the file:
mkdir -p ~/.config/swarm-provenance-mcp && mv .env ~/.config/swarm-provenance-mcp/.env(or under$XDG_CONFIG_HOMEif you set it), or keep it where it is and setSWARM_PROVENANCE_ENV_FILEto its absolute path in the client's"env"block. - The
"env"block inclaude_desktop_config.jsonis unaffected and still overrides the env file. "cwd"no longer has any effect on configuration. You can remove it.
Gateway Options
Public Gateway (Recommended)
The MCP server uses the public gateway hosted by DataFund by default at https://provenance-gateway.datafund.io. This gateway provides:
- High availability and reliability
- No setup or maintenance required
- Direct access to the Swarm network
- Free to use for development and testing
Self-Hosted Gateway
You can also run your own gateway instance for:
- Custom configurations
- Private or isolated environments
- Local development
To use a self-hosted gateway:
- Clone the gateway repository:
git clone https://github.com/datafund/swarm_connect - Follow the setup instructions in that repository
- Set
SWARM_GATEWAY_URL=http://localhost:8000in your env file (~/.config/swarm-provenance-mcp/.env) or environment
Usage
Running the MCP Server
swarm-provenance-mcp
Available Tools
purchase_stamp
Purchase a new postage stamp.
Parameters:
duration_hours(int): Duration in hours, minimum 24 (optional, uses default if not provided)size(string): Stamp size —"small","medium", or"large"(optional, uses default if not provided)depth(int): Explicit depth override, bypasses size (optional, advanced use only)label(string): Optional label for the stamp
Example:
{
"name": "purchase_stamp",
"arguments": {
"duration_hours": 48,
"size": "small",
"label": "my-test-stamp"
}
}
get_stamp_status
Get detailed information about a specific stamp.
Parameters:
stamp_id(string): The batch ID of the stamp
Example:
{
"name": "get_stamp_status",
"arguments": {
"stamp_id": "000de42079daebd58347bb38ce05bdc477701d93651d3bba318a9aee3fbd786a"
}
}
list_stamps
List all available postage stamps.
Parameters: None
Example:
{
"name": "list_stamps",
"arguments": {}
}
extend_stamp
Extend an existing stamp with additional duration.
Parameters:
stamp_id(string): The batch ID of the stamp to extendduration_hours(int): Additional duration in hours, minimum 24
Example:
{
"name": "extend_stamp",
"arguments": {
"stamp_id": "000de42079daebd58347bb38ce05bdc477701d93651d3bba318a9aee3fbd786a",
"duration_hours": 48
}
}
upload_data
Upload data to the Swarm network with stamp validation.
Parameters:
data(string): Data content to upload (max 4096 bytes)stamp_id(string): Postage stamp ID to use for uploadcontent_type(string): MIME type of the content (optional, default: "application/json")
Example:
{
"name": "upload_data",
"arguments": {
"data": "{\"message\": \"Hello Swarm!\"}",
"stamp_id": "000de42079daebd58347bb38ce05bdc477701d93651d3bba318a9aee3fbd786a",
"content_type": "application/json"
}
}
download_data
Download data from the Swarm network using a reference hash.
Parameters:
reference(string): Swarm reference hash of the data to download
Example:
{
"name": "download_data",
"arguments": {
"reference": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a"
}
}
check_stamp_health
Run a health check on a specific stamp. Returns whether uploads can proceed, plus any errors or warnings with actionable suggestions.
Parameters:
stamp_id(string): The batch ID of the stamp to check
Example:
{
"name": "check_stamp_health",
"arguments": {
"stamp_id": "000de42079daebd58347bb38ce05bdc477701d93651d3bba318a9aee3fbd786a"
}
}
get_wallet_info
Get the gateway node's wallet address and BZZ balance. Useful for checking if the node has sufficient funds. Note: this is a debugging/diagnostic tool and may be removed in future versions.
Parameters: None
Example:
{
"name": "get_wallet_info",
"arguments": {}
}
get_notary_info
Check whether the notary signing service is enabled and available on the gateway.
Parameters: None
Example:
{
"name": "get_notary_info",
"arguments": {}
}
health_check
Check gateway and Swarm network connectivity status. Returns an adaptive status including stamp availability, a ready flag indicating whether uploads can proceed, and recommendations for next steps.
Parameters: None
Example:
{
"name": "health_check",
"arguments": {}
}
chain_balance (optional — requires CHAIN_ENABLED=true and blockchain dependencies)
Check the on-chain wallet ETH balance used for provenance anchoring. Returns wallet address, balance, chain info, and actionable funding guidance when balance is low.
Parameters: None
Example:
{
"name": "chain_balance",
"arguments": {}
}
chain_health (optional — requires CHAIN_ENABLED=true and blockchain dependencies)
Test blockchain RPC connectivity for on-chain provenance. Returns connection status, chain name, chain ID, latest block number, and RPC response time. Does not require a wallet key.
Parameters: None
Example:
{
"name": "chain_health",
"arguments": {}
}
anchor_hash (optional — requires CHAIN_ENABLED=true and PROVENANCE_WALLET_KEY)
Register a Swarm reference hash on the blockchain, creating an immutable provenance record with owner, timestamp, and data type. Costs gas. If the hash is already registered, returns the existing record without error.
Parameters:
swarm_hash(string, required): 64-character hex Swarm reference hash to anchordata_type(string): Data type/category (default:swarm-provenance, max 64 chars)owner(string): Ethereum address to register as owner (defaults to wallet address; requires delegate authorization for other addresses)storage_ref(string): Optional 64-character hex storage reference to link bidirectionally. Enables reverse lookup vialookup_by_storage_ref
Example:
{
"name": "anchor_hash",
"arguments": {
"swarm_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a",
"data_type": "provenance-metadata"
}
}
verify_hash (optional — requires CHAIN_ENABLED=true)
Check whether a Swarm reference hash is registered on the blockchain. Returns verified status with basic provenance info (owner, timestamp, data type) if found. Read-only — no gas or wallet key required.
Parameters:
swarm_hash(string, required): 64-character hex Swarm reference hash to verify
Example:
{
"name": "verify_hash",
"arguments": {
"swarm_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a"
}
}
get_provenance (optional — requires CHAIN_ENABLED=true)
Retrieve the full on-chain provenance record for a Swarm reference hash. Returns owner, registration timestamp, data type, status, transformations, and accessors. Read-only — no gas or wallet key required.
Parameters:
swarm_hash(string, required): 64-character hex Swarm reference hash to look up
Example:
{
"name": "get_provenance",
"arguments": {
"swarm_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a"
}
}
record_transform (optional — requires CHAIN_ENABLED=true and PROVENANCE_WALLET_KEY)
Record a data transformation on-chain, linking the original data to its transformed version. Creates a verifiable lineage trail. The original hash must already be anchored. Costs gas. If the same (original → new) pair is already recorded, returns the existing link without spending gas (idempotent).
Parameters:
original_hash(string, required): 64-character hex Swarm reference of the original data (must be already anchored)new_hash(string, required): 64-character hex Swarm reference of the transformed datadescription(string): Description of the transformation (max 256 chars, e.g., "Anonymized PII")restrict_original(boolean): If true, set the original data status to RESTRICTED after recording the transformation (default: false)
Example:
{
"name": "record_transform",
"arguments": {
"original_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a",
"new_hash": "b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab",
"description": "Filtered for region EU",
"restrict_original": false
}
}
record_merge_transform (optional — requires CHAIN_ENABLED=true and PROVENANCE_WALLET_KEY)
Record an N-to-1 merge transformation on-chain, combining multiple source hashes into a single new hash. All source hashes must be already anchored. Costs gas. Requires a v2 contract (localhost or upgraded deployments).
Parameters:
source_hashes(array of strings, required): 2–50 source Swarm reference hashes to merge (each 64-character hex)new_hash(string, required): 64-character hex Swarm reference of the merged resultdescription(string): Description of the merge transformation (max 256 chars)new_data_type(string): Data type for the merged result (default:"merged", max 64 chars)
Example:
{
"name": "record_merge_transform",
"arguments": {
"source_hashes": [
"a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a",
"b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab"
],
"new_hash": "c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789abc",
"description": "Merged EU and US datasets",
"new_data_type": "merged-dataset"
}
}
get_provenance_chain (optional — requires CHAIN_ENABLED=true)
Follow the transformation lineage for a Swarm hash. On v2 contracts, uses state reads for fast traversal; on v1 contracts, walks through event logs. Shows how data evolved — from original to each derived version. Read-only — no gas or wallet key required.
Parameters:
swarm_hash(string, required): 64-character hex Swarm reference hash to trace lineage formax_depth(integer): Maximum depth to traverse (default: 10, range: 1–50)
Example:
{
"name": "get_provenance_chain",
"arguments": {
"swarm_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a",
"max_depth": 10
}
}
set_storage_ref (optional — requires CHAIN_ENABLED=true and PROVENANCE_WALLET_KEY)
Attach a Swarm storage reference to an existing on-chain record. Set-once: cannot be changed after first write. Owner-only. Useful after record_transform to link the transformed data's Swarm storage location.
Parameters:
data_hash(string, required): 64-character hex data hash of the existing on-chain recordstorage_ref(string, required): 64-character hex storage reference to link (e.g. Swarm reference)
Example:
{
"name": "set_storage_ref",
"arguments": {
"data_hash": "a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789a",
"storage_ref": "b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab"
}
}
lookup_by_storage_ref (optional — requires CHAIN_ENABLED=true)
Reverse lookup: find the on-chain provenance record by its Swarm storage reference. Returns the linked data hash and full provenance record if found. Read-only — no gas or wallet key required.
Parameters:
storage_ref(string, required): 64-character hex storage reference to look up
Example:
{
"name": "lookup_by_storage_ref",
"arguments": {
"storage_ref": "b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab"
}
}
Response Format
All tool responses include structured metadata to help agents chain operations efficiently:
Success Responses
Every successful response appends workflow hints:
_next: <recommended_tool> # The logical next tool to call
_related: <tool1>, <tool2> # Other relevant tools
Hints are contextual — for example, list_stamps suggests _next: upload_data when usable stamps exist, but _next: purchase_stamp when none are available.
Error Responses
Error responses include structured recovery information:
retryable: true|false # Whether retrying the same call may succeed
_next: <recovery_tool> # Tool to call for recovery
- retryable: true — transient errors (timeouts, rate limits, 502/503/504). Wait and retry.
- retryable: false — permanent errors (validation failures, unknown tools). Fix input and try a different approach.
Adaptive Health Check
The health_check tool returns additional fields:
ready: true|false # Whether the system is ready for uploads
_recommendations: # Actionable suggestions (only when issues exist)
- No stamps found — purchase one before uploading
_gateway: <url> (connected|unreachable)
MCP Prompts
The server provides workflow prompts that agents can invoke via prompts/list and prompts/get. These give step-by-step instructions for common tasks:
| Prompt | Description | Arguments |
|---|---|---|
provenance-upload |
Upload data to Swarm: health check, stamp selection, upload, verify | data (required), content_type (optional) |
provenance-verify |
Download and verify existing data by reference | reference (required) |
stamp-management |
Review stamp inventory, diagnose issues, recommend actions | none |
provenance-chain-workflow |
End-to-end on-chain provenance: store, anchor, and optionally record a transformation | data (required), transform_description (optional) |
MCP Resources
The server exposes on-demand knowledge resources that agents can load via resources/list and resources/read:
| Resource URI | MIME Type | Description |
|---|---|---|
provenance://skills |
text/markdown |
Provenance skills guide — concepts, critical rules, workflows, diagrams, and error recovery |
Docker
Building
docker build -t swarm-provenance-mcp .
To tag with a specific version:
docker build --build-arg VERSION=0.2.0 -t swarm-provenance-mcp:0.2.0 .
Running
The server communicates via stdio (no ports). Pass -i for interactive stdin:
docker run -i --rm swarm-provenance-mcp
Configure the gateway URL and other settings via environment variables:
docker run -i --rm \
-e SWARM_GATEWAY_URL=https://provenance-gateway.datafund.io \
-e DEFAULT_STAMP_SIZE=medium \
swarm-provenance-mcp
Claude Desktop with Docker
Add to your claude_desktop_config.json:
{
"mcpServers": {
"swarm-provenance": {
"command": "docker",
"args": ["run", "-i", "--rm", "swarm-provenance-mcp"]
}
}
}
Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ AI Agents │◄──►│ MCP Server │◄──►│ swarm_connect │
│ │ │ │ │ Gateway │
│ • Claude │ │ • Tool handlers │ │ │
│ • Other LLMs │ │ • Gateway client│ │ • Purchase API │
│ • Custom agents │ │ • Chain client │ │ • Status API │
└─────────────────┘ │ • Error handling│ │ • Extension API │
└────────┬────────┘ └─────────┬───────┘
│ │
┌────────▼────────┐ ┌─────────▼───────┐
│ Base Sepolia │ │ Swarm Network │
│ (DataProv. │ │ (Bee Node) │
│ Contract) │ └─────────────────┘
└─────────────────┘
Components
- MCP Server: Exposes tools via the Model Context Protocol
- Gateway Client: HTTP client for communicating with swarm_connect
- Chain Client (optional): On-chain provenance via DataProvenance smart contract on Base Sepolia
- Configuration: Environment-based settings management
- Error Handling: Comprehensive error handling and logging
Claude Desktop Integration
Setup Instructions
-
Install Claude Desktop: Download from claude.ai
-
Clone and set up this repository:
# Clone the repository
git clone https://github.com/datafund/swarm_provenance_MCP.git
# Navigate to the project directory
cd swarm_provenance_mcp
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install the package in development mode
pip install -e .
# Configure environment variables
mkdir -p ~/.config/swarm-provenance-mcp
cp .env.example ~/.config/swarm-provenance-mcp/.env
# Edit that file if you need to customize gateway URL or defaults
- Configure MCP Server: Add to Claude Desktop's configuration file:
macOS/Linux (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"swarm-provenance": {
"command": "/path/to/swarm_provenance_mcp/run.sh"
}
}
}
Windows (%APPDATA%\Claude\claude_desktop_config.json):
{
"mcpServers": {
"swarm-provenance": {
"command": "C:\\path\\to\\swarm_provenance_mcp\\venv\\Scripts\\python.exe",
"args": ["-m", "swarm_provenance_mcp.server"]
}
}
}
Note: Replace /path/to/swarm_provenance_mcp with the actual path where you cloned the repository.
The run.sh launcher (macOS/Linux) starts the server from the repo's venv, with the repo as working directory. The working directory does not affect configuration: settings come from the env file described above, and a .env in the repository is no longer read (see Upgrading from a .env in the repository; the server logs a warning if it finds one). If the venv stops working — typically after moving or renaming the repo directory — it rebuilds it automatically. Make it executable once with chmod +x run.sh.
The rebuild installs all dependencies and can take a few minutes, longer than an MCP client waits for the server on startup. If the first launch after a move times out, run ./run.sh < /dev/null once in a terminal to finish the rebuild, then restart the client. The Windows config above does not use the launcher yet; after moving the repo on Windows, recreate the venv manually.
Alternative (if package is installed): You can use "command": "swarm-provenance-mcp" instead after running pip install -e .
With on-chain provenance
To enable blockchain anchoring, add an "env" block to the config. You can use this instead of (or alongside) the env file at ~/.config/swarm-provenance-mcp/.env:
{
"mcpServers": {
"swarm-provenance": {
"command": "/path/to/swarm_provenance_mcp/run.sh",
"env": {
"CHAIN_ENABLED": "true",
"PROVENANCE_WALLET_KEY": "0x...your_private_key_here..."
}
}
}
}
Read-only chain tools (verify_hash, get_provenance, get_provenance_chain, lookup_by_storage_ref, chain_health) work without PROVENANCE_WALLET_KEY. Write tools (anchor_hash, record_transform, record_merge_transform, set_storage_ref) and chain_balance require a funded wallet — see Chain Anchoring for details.
Docker-based
Use Docker for a zero-install experience — no Python, venv, or pip required:
{
"mcpServers": {
"swarm-provenance": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-e", "SWARM_GATEWAY_URL=https://provenance-gateway.datafund.io",
"ghcr.io/datafund/swarm-provenance-mcp"
]
}
}
}
To enable chain anchoring with Docker, add the chain env vars:
{
"mcpServers": {
"swarm-provenance": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-e", "SWARM_GATEWAY_URL=https://provenance-gateway.datafund.io",
"-e", "CHAIN_ENABLED=true",
"-e", "PROVENANCE_WALLET_KEY=0x...your_private_key_here...",
"ghcr.io/datafund/swarm-provenance-mcp"
]
}
}
}
Docker Desktop MCP Toolkit: If you use Docker Desktop with MCP Toolkit support, the server can be discovered automatically from the Docker MCP catalog.
- Restart Claude Desktop and verify the connection.
Getting Started
After setup, try these prompts in Claude Desktop to verify everything works:
Check connectivity:
"Run a health check on the Swarm gateway"
Expected: a status showing healthy, gateway URL, and response time. If chain is enabled, you'll also see RPC connectivity and wallet balance info.
List stamps:
"List all available Swarm stamps"
Expected: a list of postage stamps with batch IDs, or a message that no stamps exist yet (with a suggestion to purchase one).
Full upload workflow:
"Upload the text 'Hello Swarm!' to the Swarm network"
Claude will walk through: purchasing a stamp, waiting for it to propagate, uploading the data, and returning the Swarm reference hash.
Verify on-chain (if chain enabled):
"Anchor the uploaded hash on-chain and verify it"
Claude will register the hash on the blockchain and confirm the provenance record.
Troubleshooting Setup
If Claude Desktop doesn't show the Swarm tools:
- Check the config file path is correct for your OS
- Verify the
commandpath points torun.shin your clone (macOS/Linux), or to the Python executable inside your venv (Windows) - Check Claude Desktop logs: Help > Show Logs (look for MCP connection errors)
- Test manually: run
./run.sh(orswarm-provenance-mcp) in your terminal — it should start without errors and wait for MCP input. Launcher messages, including a venv rebuild, go to stderr
Development
Testing
# Install development dependencies
pip install -e .[dev]
# Run tests
pytest
# Run with coverage
pytest --cov=swarm_provenance_mcp
Docker Testing
Requires Docker daemon to be running:
# Run all Docker tests (builds image, tests MCP protocol, tool calls)
pytest tests/test_docker.py -v -m docker
# Verify manually
docker build -t swarm-provenance-mcp .
docker run -i --rm swarm-provenance-mcp # starts, waits for MCP input
docker run -i --rm -e SWARM_GATEWAY_URL=https://provenance-gateway.datafund.io swarm-provenance-mcp # env override
Code Quality
# Format code
black swarm_provenance_mcp/
# Lint code
ruff check swarm_provenance_mcp/
Editor settings
The repository commits no editor hooks, MCP servers or auto-approve settings. Shared editor settings take effect on every contributor's machine, so keep your own in per-developer configuration:
.claude/settings.local.jsonfor project hooks and permissions. It is gitignored, and so is any.claude/*.local.json.~/.claude/settings.jsonfor settings that apply to all your projects.claude mcp add --scope localor--scope userfor MCP servers, instead of a committed.mcp.json.
These files count as committed editor settings: .claude/**/*.json except *.local.json, .mcp.json, .cursor/mcp.json and .cursor/hooks.json. They must not contain:
- A
hooks,mcpServers,statusLineorapiKeyHelperkey. Each one runs a command or connects to an MCP server. - A non-empty
permissions.allow. - An
enableAllProjectMcpServersorenabledMcpjsonServerskey. - A
permissions.defaultModeother than"default".
tests/test_editor_settings.py enforces these rules.
Dependencies
-
Core Dependencies:
mcp>=1.26,<2: Model Context Protocol framework (the server is written for mcp 1.x)requests>=2.31.0,<3: HTTP client for gateway communicationpydantic>=2.0.0,<3andpydantic-settings>=2.0,<3: Data validation and settingspython-dotenv>=1.0.0,<2: Environment configurationweb3>=7,<8: Ethereum blockchain interaction for on-chain provenanceeth-account>=0.13,<0.14: Wallet and transaction signing for chain anchoringeth-utils>=5,<6: Hashing helpers (keccak) used directly by the chain module
Upper bounds are deliberate. Raise one only together with a passing test run against the new version.
-
Development Dependencies:
pytest: Testing frameworkpytest-asyncio: Async testing supportpytest-mock: Mocking utilitiesblack: Code formattingruff: Linting
Integration with AI Agents
This MCP server is designed to work with AI agents that support the Model Context Protocol. Agents can use the provided tools to:
- Manage stamp inventory: Purchase and extend stamps as needed
- Monitor usage: Check stamp status and utilization
- Optimize costs: List stamps to find the most suitable ones for tasks
- Store provenance data: Upload data with provenance metadata to immutable decentralized storage
- Verify data integrity: Retrieve and verify immutable records from Swarm network
- Data lifecycle management: Handle complete provenance workflows from creation to verification
- Track data lineage: Record transformations and trace the full provenance chain of derived data
- Automate workflows: Integrate stamp management and data storage into larger AI workflows
Troubleshooting
Common Issues
- Connection errors: Ensure the swarm_connect gateway is running and accessible
- Authentication errors: Check that the gateway doesn't require authentication
- Invalid stamp IDs: Verify stamp IDs are valid batch IDs from the Swarm network
- Timeout errors: Increase timeout values if operations are taking too long
- Chain: "wallet key not configured": Set
PROVENANCE_WALLET_KEYin the MCP client's"env"block or in the env file (~/.config/swarm-provenance-mcp/.env, see Configuration) for write operations (anchor_hash,record_transform,set_storage_ref). Read-only tools work without it. - Chain: "insufficient funds": Fund your wallet with testnet ETH (Base Sepolia faucet) or bridge ETH to Base mainnet. Run
chain_balancefor guidance. - Chain: "already registered": The hash is already anchored on-chain. Use
get_provenanceto view the existing record. - Chain: "transformation already recorded": The
(original → new)link already exists on-chain. No gas spent — useget_provenance_chainto verify the lineage. - Chain: "too few/many sources":
record_merge_transformrequires 2–50 source hashes. Adjust thesource_hashesarray accordingly.
Logging
The server logs important events and errors. To increase logging verbosity:
import logging
logging.getLogger("swarm_provenance_mcp").setLevel(logging.DEBUG)
License
MIT License - see LICENSE file for details.
