Skip to main content
Glama
blockchain-pattern-mcp
by olk
README.md
# blockchain-pattern-mcp

[![CI](https://img.shields.io/github/actions/workflow/status/olk/blockchain-pattern-mcp/ci.yml?branch=main)](https://github.com/olk/blockchain-pattern-mcp/actions)
[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

An MCP (Model Context Protocol) server that provides blockchain design expertise to AI coding agents. Given a requirements string and a domain, it analyses the problem, selects matching blockchain patterns (from 109 built-in patterns), generates a concrete design with components, relationships, API contracts, data models, and event contracts, and evaluates it against eight quality attributes (security, cost efficiency, scalability, decentralization, composability, liquidity, simplicity, privacy).

---

## Table of Contents

- [⚡ Quickstart](#-quickstart)
- [Install via AI Agent](#install-via-ai-agent)
- [🔌 Connect Your Agent](#-connect-your-agent)
  - [Claude Code](#claude-code)
  - [OpenCode](#opencode)
  - [Codex CLI](#codex-cli)
- [🧑‍🏫 SKILL for AI Agents](#-skill-for-ai-agents)
- [🧪 Use the Tools](#-use-the-tools)
  - [Design your first system](#design-your-first-system)
  - [Explore the pattern catalog](#explore-the-pattern-catalog)
- [🛠️ Tools at a Glance](#️-tools-at-a-glance)
- [📖 Pattern Catalog](#-pattern-catalog)
- [Working Together with design-pattern-mcp-local](#working-together-with-design-pattern-mcp-local)
- [Install Alternatives](#install-alternatives)
  - [Docker (manual)](#docker-manual)
  - [Local Development (uv)](#local-development-uv)
- [Configuration](#configuration)
- [Structured Reasoning (shannonthinking / code-reasoning)](#structured-reasoning-shannonthinking--code-reasoning)
- [Extending with Custom Patterns](#extending-with-custom-patterns)
- [Long-running tools & timeouts](#long-running-tools--timeouts)
- [Troubleshooting](#troubleshooting)
- [Building & Development](#building--development)
- [Publishing](#publishing)
- [systemd Service (Linux)](#systemd-service-linux)
- [License](#license)

---

## ⚡ Quickstart

```bash
# 1. Clone
git clone https://github.com/olk/blockchain-pattern-mcp.git && cd blockchain-pattern-mcp

# 2. Add your API key
export GENERATOR_API_KEY=your_key_here

# 3. Start (Docker builds + starts everything)
docker compose -f docker/docker-compose.yml up --build

# 4. Demo (analyze-only: fast. For the full design: make client-design)
make client-analyze
```

Server starts on **streamable-http** at `http://localhost:8823/mcp` (dev compose host port; systemd uses 8813). Then connect your agent below.

---

## Install via AI Agent

To have an AI coding agent install the Docker stack from prebuilt images (no local build), point it at **[INSTALL.md](INSTALL.md)** — the non-interactive agent runbook (copy-paste commands, expected outputs, verification probes).

```text
Clone this repo, then follow INSTALL.md Path A (compose stack, port 8823).
My generator API key is: sk-...
```

Pick one path in `INSTALL.md`:

- **Path A — Compose stack** (`:8823`): evaluating / developing, no sudo needed. Own TEI sidecar copies.
- **Path B — systemd stack** (`:8813`): persistent host service, starts at boot, needs `sudo`. Uses the shared `pattern-tei-infra` TEI stack.

The agent needs a repo clone, Docker ≥ v2.20 with group membership, ~18 GB free, an `OPENCODE_API_KEY` (or another provider per `INSTALL.md#switching-the-generator-llm`), and linux/amd64 (on arm64 it builds locally via `make docker-build-all`). After install, continue with [Connect Your Agent](#-connect-your-agent) below.

---

## 🔌 Connect Your Agent

### Claude Code

```bash
# Install (one-time)
uv pip install -e .

# Run as stdio subprocess — pass API key via env
claude mcp add blockchain-pattern \
  -e GENERATOR_API_KEY=your_key \
  -e GENERATOR_PROVIDER=openai \
  -- blockchain-pattern-mcp --transport stdio
```

Or add to your project for the whole team:

```bash
claude mcp add --scope project blockchain-pattern \
  -e GENERATOR_API_KEY=your_key \
  -- blockchain-pattern-mcp --transport stdio
```

### OpenCode

OpenCode uses HTTP transport. Start the server first, then configure opencode:

```bash
# Terminal 1: start the server
docker compose -f docker/docker-compose.yml up --build
# or locally:
uv run python -m src.main --port 8823

# Terminal 2: add to ~/.config/opencode/opencode.json
```

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "blockchain-pattern": {
      "type": "remote",
      "url": "http://localhost:8823/mcp"
    }
  }
}
```

> **Note:** `GENERATOR_API_KEY` is read from the server's config file (`~/.config/blockchain-pattern-mcp/config.json`), not from opencode's environment.

### Codex CLI

```bash
# Install (one-time)
uv pip install -e .
```

Add to `~/.codex/config.toml`:

```toml
[mcp_servers.blockchain-pattern]
command = "blockchain-pattern-mcp"
args = ["--transport", "stdio"]

[mcp_servers.blockchain-pattern.env]
GENERATOR_API_KEY = "your_key"
GENERATOR_PROVIDER = "openai"
```

Or via CLI:

```bash
codex mcp add blockchain-pattern \
  -e GENERATOR_API_KEY=your_key \
  -- blockchain-pattern-mcp --transport stdio
```

---

## 🧑‍🏫 SKILL for AI Agents

The SKILL in `skills/blockchain-pattern-mcp/` is written for **Oh My Pi (OMP)**, where this server's tools are reached as `xd://mcp__blockchain_pattern_*` devices and every MCP request is bounded by a deadline (`OMP_MCP_TIMEOUT_MS` → per-server `timeout` → 30 s). It teaches the agent which entry point fits that deadline, how to read the results, and the full workflow recipes.

```
skills/blockchain-pattern-mcp/
├── SKILL.md                 # OMP constraints, entry-point decision guide, device quick reference
└── references/
    ├── tools.md             # 11 tool signatures, output schemas, error codes, design-dict shape
    └── workflows.md         # 5 recipes, result interpretation, OMP troubleshooting
```

**Install for OMP** — copy the skill directory into the user skills root, or point `skills.customDirectories` at this repository's `skills/` directory in OMP's config:

```bash
cp -r skills/blockchain-pattern-mcp ~/.omp/agent/skills/
```

The skill then tells the agent:

- Which entry point fits both the deliverable and OMP's deadline: `analyze_blockchain` when a coding agent will write the implementation itself, the async job trio when the caller wants the design artifact, and one-shot `design_blockchain` only after raising the server's `timeout` (the analyse leg alone takes ~1 minute, evaluation ~3 minutes)
- How to phrase `requirements`, `domain`, and `style` as separate structured arguments
- How to interpret `final_quality_score`, `attempts > 1`, and `evaluation.recommendations`
- That `read mcp://pattern://…` is ambiguous while other pattern servers are connected, so the tool route (`get_blockchain_pattern`) is authoritative

The tool schemas, error codes and design-dict shape in `references/` are client-agnostic; only the deadline/device guidance is OMP-specific.

---

## Use the Tools

Pick the path by deliverable. A coding agent that will write the implementation itself calls `analyze_blockchain`: it returns the recommended style, selected pattern cards with requirements-weighted analysis scores, the selected patterns' aggregate 0–10 quality profile, and matched domains — guidance to code against, not a design. A caller that wants the design artifact calls `design_blockchain` (or the async job trio): it runs the same analyse leg, then generate → evaluate → refine, and returns components, relationships, API contracts, data models, event contracts, and the evaluation. `analyze_blockchain` is one lightweight LLM call (~1 minute); `design_blockchain` is 5–10 minutes.

All tools accept `requirements` (free text) and `domain` (e.g. `bridge`, `defi-trading`, `l2-scaling`, `wallet`) as arguments. The examples below show the exact tool call shape so you can use them in any MCP client or API consumer.

### Try each tool

In Claude Code (or any MCP client), paste the natural-language instruction:

```
Design a cross-chain token bridge between an L1 and an L2: lock tokens in an
escrow contract, mint a wrapped representation on the destination chain, use
relayers for attestations with a fraud-proof window, rate-limit each token,
and verify destination-chain state with a light client.
```

When the deliverable is the design, your agent calls `design_blockchain` internally. The server returns a full design: components (escrow contract, minter, relayer, light-client verifier, guardian), quality attribute scores (security: 8.1, decentralization: 7.2, …), and specific recommendations.

**Or call tools directly** from your agent:

```
Call analyze_blockchain with:
  requirements: "Cross-chain bridge with fraud proofs and rate-limited mints"
  domain: "bridge"

Call generate_blockchain with:
  requirements: "Lock-mint bridge with a fraud-proof challenge window"
  domain: "bridge"
  style: "lock-mint-bridge"
  selected_patterns: ["lock-mint-bridge", "optimistic-bridge"]

Call evaluate_blockchain with:
  blockchain: { ... paste a design dict here ... }
  criteria: "security, decentralization"

Call list_blockchain_patterns()  # all 109 patterns
Call list_blockchain_patterns(category="mev")  # filter by category
Call get_blockchain_pattern(name="zk-rollup")   # full pattern JSON
```

### Async job pattern: `submit_blockchain_design_job` + `get_blockchain_design_status`

ONLY for clients with short request timeouts (Cursor, Claude Desktop, TS-SDK). For design requests the default is `design_blockchain` with heartbeat defence. `submit_blockchain_design_job` returns a `job_id` immediately; poll `get_blockchain_design_status` until done:

```
# Step 1: start the job
Call submit_blockchain_design_job with:
  requirements: "Cross-chain bridge with fraud proofs and rate-limited mints"
  domain: "bridge"

# Step 2: poll every 10-30 seconds
Call get_blockchain_design_status with:
  job_id: "<job_id from step 1>"

# → status is "pending" | "running" | "completed" | "failed" | "cancelled"
# When status is "completed", the full design is in result.design
# When status is "failed", the error is in result.error
```

In Python (via the MCP HTTP API directly — see `examples/blockchain_client_async.py`):

```python
import asyncio, aiohttp

SERVER = "http://localhost:8823/mcp"
POLL_EVERY = 15  # seconds

async def main():
    async with aiohttp.ClientSession() as sess:
        # Start
        async with sess.post(SERVER, json={
            "jsonrpc": "2.0",
            "method": "tools/call",
            "params": {
                "name": "submit_blockchain_design_job",
                "arguments": {
                    "requirements": "Lock-mint bridge with fraud proofs",
                    "domain": "bridge",
                }
            },
            "id": 1
        }) as resp:
            job_id = (await resp.json())["result"]["content"][0]["data"]["job_id"]

        print(f"Job started: {job_id}")

        # Poll
        while True:
            await asyncio.sleep(POLL_EVERY)
            async with sess.post(SERVER, json={
                "jsonrpc": "2.0",
                "method": "tools/call",
                "params": {"name": "get_blockchain_design_status", "arguments": {"job_id": job_id}},
                "id": 2
            }) as resp:
                result = (await resp.json())["result"]["content"][0]["data"]
                print(f"  status={result['status']}")
                if result["status"] in ("completed", "failed", "cancelled"):
                    break

        print(result.get("result", result))  # full design when completed
```

See `examples/blockchain_client_async.py` for the complete runnable example (it also exercises `cancel_blockchain_design`). Run it with:

```bash
docker compose -f docker/docker-compose.yml up --build   # Terminal 1
make client-async                                       # Terminal 2
```

### Explore the pattern catalog

```
Call list_blockchain_patterns() with no filters to see all patterns.
```

Or get details on a specific pattern:

```
Show me details about the zk-rollup pattern.
```

---

## 🛠️ Tools at a Glance

| Tool | Description |
|---|---|
| `analyze_blockchain` | Path for coding agents that write their own code: recommended style, selected pattern cards with requirements-weighted analysis scores, the selected patterns' aggregate 0–10 quality profile, matched domains, requirement weights — no generated design. Gate on `is_fallback` and `style_fallback`: when either is true, do not code against `recommended_style`. *One lightweight LLM call (~1 min). Not idempotent.* |
| `generate_blockchain` | Generate a design from requirements, style and selected patterns. *Long-running (LLM call). Not idempotent.* |
| `evaluate_blockchain` | Score an existing design against quality attributes. *Long-running (LLM call). Not idempotent.* |
| `design_blockchain` | Full design artifact for callers that want the design: pipeline (analyse → generate → evaluate → refine, up to 3 attempts) returns components, relationships, API contracts, data models, event contracts, and the evaluation. *Long-running (5–10 min); use this unless your client has a short request timeout.* |
| `submit_blockchain_design_job` | Start a background design job and return a `job_id` immediately. **ONLY for clients with short request timeouts** (Cursor, Claude Desktop, TS-SDK). For other clients use `design_blockchain`. Poll `get_blockchain_design_status` every 10–30 s. |
| `get_blockchain_design_status` | Poll job status. Returns the current status, progress message, and the full design output when `completed`. |
| `cancel_blockchain_design` | Cancel a running job (best-effort; takes effect at the next pipeline stage boundary; may take up to one LLM call). |
| `list_blockchain_patterns` | List all 109 patterns; filter by `category` and/or `domain` |
| `get_blockchain_pattern` | Get full JSON for a specific pattern by name |

**Domain and Style are structured parameters** — pass them as separate tool arguments, not embedded in the requirements text.

Example prompts:

```
Design a cross-chain token bridge with fraud proofs, rate-limited mints and a
light-client verifier for L2 -> L1 withdrawals.
```

```
Design a DEX for an L2: concentrated liquidity positions, a router, and a
keeper network for rebalancing. Domain: defi-trading. Style: concentrated-liquidity.
```

```
Show me details about the erc4337 pattern.
```

```
Call design_blockchain with:
  requirements: "Constant-product AMM with TWAP oracle and reentrancy guards"
  domain: "defi-trading"
```

---

## 💬 Prompts

This server also exposes four user-invoked workflow prompts (slash commands
in MCP clients). Unlike tools, the LLM does not autonomously invoke prompts —
the user selects one and fills in its arguments. Each prompt encodes a tested
tool-orchestration recipe.

| Prompt | Args | What it does |
|---|---|---|
| `/design_blockchain_workflow` | requirements\* | Full analyze → generate → evaluate pipeline |
| `/explore_pattern_catalog` | `domain`, `category` | Live catalog discovery with embedded pattern names |
| `/evaluate_my_blockchain` | `focus` | Guide evaluation criteria + finding prioritisation |
| `/compare_blockchain_styles` | style_a\*, style_b\*, requirements\* | Two designs side-by-side; ~2× token cost |

\* = required argument

### Tool-only clients

Clients that only support the tools protocol (no native `prompts/list` or `prompts/get`) can access all four workflow prompts via the generated `list_prompts` and `get_prompt` tools, which route through the server's middleware chain exactly as native prompt calls do.

---

## 📖 Pattern Catalog

### Via MCP tools (recommended — works in all clients)

```
list_blockchain_patterns()                                     # all 109 patterns
list_blockchain_patterns(category="mev")                       # filter by category
list_blockchain_patterns(domain="l2-scaling")                  # filter by category/layer slug
get_blockchain_pattern(name="zk-rollup")                       # full pattern JSON
```

Valid `category` values: `account-abstraction`, `bridge`, `defi-primitive`, `defi-trading`, `developer-tooling`, `governance`, `identity`, `l2-scaling`, `lifecycle`, `mev`, `nft`, `oracle`, `privacy`, `security`, `storage`, `token-standard`.

Valid `domain` values are the 24-slug union of categories and chain-stack layers: `account-abstraction`, `bridge`, `consensus`, `data-availability`, `defi-primitive`, `defi-trading`, `developer-tooling`, `execution`, `governance`, `identity`, `l2-scaling`, `lifecycle`, `mempool`, `mev`, `networking`, `nft`, `oracle`, `privacy`, `scaling-l2`, `security`, `storage`, `token-standard`, `tooling`, `wallet`. A pattern matches when the slug equals its `category` **or** its `layer`.

### Via MCP resources

```
mcp_list_resources(server="blockchain-pattern")
mcp_read_resource(server="blockchain-pattern", uri="pattern://zk-rollup")
```

The server also serves `template://modular-blockchain-template` and `component://{type}` (derived from pattern participants).

> **Resource collision:** other pattern servers on the same host register the same `pattern://`, `template://` and `component://` schemes, and OMP resolves a resource URI by server order rather than by ownership. In mixed setups, prefer the tool route above.

### Pattern JSON structure

Each pattern includes: `name`, `aliases`, `category`, `layer`, `context`, `mechanism`, `invariants`, `participants` (`{role, responsibility}`), `benefits`, `tradeoffs`, `quality_attributes` (security/cost_efficiency/scalability/decentralization/composability/liquidity/simplicity/privacy, scores 1–10), `known_attacks`, `mitigations`, `audit_checklist`, `related_patterns`, `design_principles`, `best_practices`, `ecosystem`, `references`, `version`; optional `use_cases`, `avoid_when`, `anti_patterns`.

### All 109 patterns

The table below follows `pattern-validation-manifest.json` order, grouped by category. Layer is the chain-stack layer the pattern operates at.

#### account-abstraction (6)

| Pattern | Layer | What it solves |
|---|---|---|
| `erc4337` | execution | Externally owned accounts sign with one key, pay gas in ETH, and cannot batch, sponsor, or limit what they… |
| `meta-transactions-erc2771` | wallet | An EOA without ETH cannot call a contract, which excludes users who have not funded a wallet, users on chains… |
| `nonce-management` | execution | A single monotonically increasing `nonce` per sender does two jobs at once: it orders transactions and it prevents… |
| `paymaster-pattern` | execution | A native transaction must be signed by the payer and paid for by the payer in the gas token. |
| `session-keys-pattern` | wallet | A dApp that needs twenty signatures for twenty actions has two bad options: ask the user to sign every time… |
| `user-operations-erc4337` | execution | An Ethereum transaction binds the signer to the payer, to the gas token, and to a single call. |

#### bridge (7)

| Pattern | Layer | What it solves |
|---|---|---|
| `burn-mint-bridge` | bridge | A bridge has to move value between two chains that do not share a ledger, and there are exactly two things it can… |
| `ccip-messaging` | bridge | Chainlink CCIP is a message-passing layer built for sending data and tokens between chains without building… |
| `layerzero-omnichain` | bridge | A cross-chain application needs one contract per chain that share state — an omnichain fungible token whose supply… |
| `light-client-bridge` | bridge | Every bridge has to answer one question: who says the deposit happened on the source chain? |
| `lock-mint-bridge` | bridge | Lock-and-mint is the default bridge shape and the one almost every description of 'bridging' actually means: the… |
| `optimistic-bridge` | bridge | An optimistic rollup lets the base layer accept a state commitment it cannot cheaply check, so it must be able to… |
| `wormhole-messaging` | bridge | Two blockchains cannot verify each other's state, so nothing minted on chain B can be recognised as backed by… |

#### defi-primitive (14)

| Pattern | Layer | What it solves |
|---|---|---|
| `algorithmic-stablecoin` | defi-primitive | A pure algorithmic stablecoin (UST, IRON, Basis Cash, and their descendants) holds no exogenous reserve. |
| `auto-compounding` | defi-primitive | A depositor who must call `claim()` before earning is a depositor who will not leave the money parked. |
| `cdp-maker` | defi-primitive | A CDP is a per-borrower, independently-addressable debt position: a user locks collateral into a vault and draws a… |
| `erc4626-vault` | defi-primitive | Yield-bearing wrappers proliferated faster than any interface could standardise: lending markets, aggregators, and… |
| `flash-loan` | defi-primitive | A flash loan lets a borrower take an arbitrary amount of an asset with zero collateral, use it within a single… |
| `hybrid-stablecoin-frax` | defi-primitive | Frax answered the question pure algorithmic stablecoins (UST, IRON) kept answering badly: can you get capital… |
| `interest-rate-model` | defi-primitive | A lending market is one shared pool of depositors' liquidity. |
| `liquid-restaking-lrt` | defi-primitive | An LRT wraps a restaked ETH (or LST) position into a transferable, DeFi-composable token. |
| `liquidation-mechanism` | defi-primitive | Solvency thresholds are the easy half of over-collateralised design: computing a health factor below which a… |
| `native-restaking-eigenlayer` | defi-primitive | Native restaking repurposes staked ETH (or an LST) as economic security for services that have nothing to do with… |
| `over-collateralized-lending` | defi-primitive | Over-collateralised lending lets a borrower lock volatile collateral and draw a stable or lower-volatility asset… |
| `staking-rewards` | defi-primitive | Staking rewards distribute a fixed or rate-limited emission to depositors proportional to their staked balance and… |
| `streaming-payments-sablier` | defi-primitive | A streaming payment releases tokens to a recipient continuously over time, rather than in one lump at a fixed… |
| `ve-tokenomics` | defi-primitive | A DeFi protocol that mints inflationary emissions needs to decide where they go, and plain token governance fails… |

#### defi-trading (10)

| Pattern | Layer | What it solves |
|---|---|---|
| `bonding-curve-pattern` | defi-trading | A bonding curve replaces the LP-and-pool launch with a deterministic pricing function p(s) that maps the amount of… |
| `constant-product-amm` | defi-trading | The constant-product market maker replaces the order book with a pool that quotes unconditionally. |
| `concentrated-liquidity` | defi-trading | Uniswap v2 spreads each LP's capital uniformly across the entire price range (0, ∞), which means most of the… |
| `cow-protocol-pattern` | defi-trading | CoW Protocol (formerly Gnosis Protocol, contract GPv2) replaces the AMM's 'first come, first served' curve with a… |
| `flash-swap` | defi-trading | A flash swap is the AMM-native cousin of the flash loan, and it is not the same pattern: the borrowed asset is the… |
| `intent-solver-pattern` | defi-trading | The intent/solver pattern inverts who solves the routing problem. |
| `options-vault-ribbon` | defi-trading | An options vault (Ribbon's 'Theta Vault') pools deposits into a single, continuously-run European options-selling… |
| `perpetual-futures` | defi-trading | A perpetual future has no expiry, so it has no settlement to force it to converge on spot — and without… |
| `stable-swap-curve` | defi-trading | StableSwap answers a specific problem: x*y=k is the wrong curve for assets that should trade near 1:1. |
| `uniswapx-pattern` | defi-trading | UniswapX is a permissionless, auction-based swapping protocol where the swapper signs an order off-chain and never… |

#### developer-tooling (9)

| Pattern | Layer | What it solves |
|---|---|---|
| `calldata-storage` | execution | Persistent contract storage is the most expensive thing an EVM contract does: a zero-to-nonzero SSTORE on a cold… |
| `calldata-over-memory` | execution | An `external` Solidity function whose parameter is declared `memory` forces the ABI decoder to copy the entire… |
| `clone-factory-eip1167` | execution | A protocol needs thousands of independent, separately-owned instances of the same logic — per-user vaults, per-… |
| `create2-deterministic` | execution | Many protocols need an address they can reference before any contract exists there: a state channel's… |
| `multi-chain-deployment` | tooling | A protocol that serves twenty chains cannot ship twenty different addresses: every SDK, front-end, bridge UI,… |
| `rainbowkit-pattern` | wallet | Raw wallet connection is one of the highest-friction steps in a dApp. |
| `smart-contract-pattern` | execution | Deploying a contract costs gas proportional to its bytecode, and deployed code is immutable. |
| `storage-packing` | execution | The EVM reads and writes storage one 32-byte word at a time, and the Solidity compiler will pack several… |
| `walletconnect-protocol` | networking | Injected browser providers only work when the dApp and the wallet are in the same browser context. |

#### governance (7)

| Pattern | Layer | What it solves |
|---|---|---|
| `conviction-voting` | governance | A DAO must decide which of dozens of standing spending requests deserve treasury funds, and gathering a fresh… |
| `erc20-votes` | governance | On-chain governance needs a way to ask 'how much voting power did this account have at time T?', not 'how many… |
| `on-chain-governance` | governance | A protocol's parameters are not immutable: interest rates, collateral factors, fees, the contract itself. |
| `quadratic-voting` | governance | One-address-one-vote is trivially Sybil-attacked and one-token-one-vote lets whales decide everything, while a… |
| `rage-quit` | governance | A DAO holds pooled capital and makes decisions by vote. |
| `snapshot-governance` | governance | On-chain governance costs a transaction per action, which prices out exactly the low-stakes participation that… |
| `timelock` | governance | A DAO or multisig that can change a protocol's parameters, upgrade its contracts, or move its treasury the instant… |

#### identity (2)

| Pattern | Layer | What it solves |
|---|---|---|
| `erc3643-compliance` | token-standard | A utility token can be permissionless; a security token cannot. |
| `soulbound-token` | identity | Many real-world facts about a person or an organisation are not transferable: a degree, a professional licence, a… |

#### l2-scaling (8)

| Pattern | Layer | What it solves |
|---|---|---|
| `eip4844-blob` | data-availability | Rollups work by posting their transaction data to Ethereum so that anyone can re-execute the batch and, in an… |
| `optimistic-rollup` | scaling-l2 | Ethereum executes every transaction on every full node, so cost per transaction rises with congestion and rollups… |
| `plasma` | scaling-l2 | Plasma was the first general framework for moving computation off a blockchain while keeping the root chain as the… |
| `rollup-as-a-service` | scaling-l2 | A production rollup is not a smart contract. |
| `sidechain-validator` | scaling-l2 | A rollup derives its security from the settlement chain: it posts data and proofs there, and L1 enforces… |
| `state-channel` | scaling-l2 | Rollups amortise cost by batching; channels amortise it by not touching the chain at all. |
| `validium` | data-availability | A ZK-rollup posts its transaction data to L1 so that anyone can reconstruct the state, prove their balance, and… |
| `zk-rollup` | scaling-l2 | An optimistic rollup trusts the operator until someone disputes, which means a seven-day withdrawal delay and a… |

#### lifecycle (3)

| Pattern | Layer | What it solves |
|---|---|---|
| `green-blockchain-patterns` | consensus | A public blockchain's environmental footprint is almost entirely a property of *how blocks are agreed*, not of how… |
| `transaction-replacement` | mempool | A broadcast transaction is not a submission — it is a bid. |
| `transaction-status-tracking` | mempool | Broadcasting a transaction returns a hash and nothing else. |

#### mev (3)

| Pattern | Layer | What it solves |
|---|---|---|
| `flashbots-protect` | mev | MEV-Boost fixed the *proposer* side of extraction by inserting a builder auction; MEV-Share fixed the *searcher*… |
| `mev-share-pattern` | mev | Flashbots Protect protects a user's transaction from frontrunning by routing it privately, but the searcher who… |
| `mev-boost-pattern` | mev | Under PoS the block proposer is a randomly selected validator with no incentive or capacity to optimise block… |

#### nft (7)

| Pattern | Layer | What it solves |
|---|---|---|
| `carbon-credit-tokenization` | nft | Carbon credits live in off-chain registries (Verra, Gold Standard, ACR, Puro) and are unusable by DeFi until they… |
| `eip2981-royalties` | token-standard | Before ERC-2981 every NFT collection and every marketplace invented its own royalty mechanism, so royalties could… |
| `dynamic-nft` | nft | ERC-721 and ERC-1155 assume a token's metadata is essentially fixed: `tokenURI(id)` returns a URI whose JSON… |
| `erc6551-tba` | nft | An NFT is a passive deed: it can be held and transferred, but it cannot hold assets, sign anything, or interact… |
| `erc721-burnable` | nft | Many NFT designs need the holder — not the contract owner — to be able to destroy their own token: consumable… |
| `erc998-composable` | nft | ERC-721 gave every unit an owner address, and that single fact is what blocks the composable asset model: a… |
| `royalty-enforcement` | nft | EIP-2981 tells anyone what royalty a token claims, and nothing more. |

#### oracle (3)

| Pattern | Layer | What it solves |
|---|---|---|
| `on-chain-aggregation` | oracle | A DeFi protocol needs a price, a reserve total or a TWAP, and no single source can be trusted: one exchange can be… |
| `onchain-ai-inference` | oracle | A smart contract that needs a model's output — to price a prediction market, gate a carbon credit, score a… |
| `oracle-pattern` | oracle | The EVM cannot observe anything outside itself, so every protocol that needs a price, a reserve total, a weather… |

#### privacy (5)

| Pattern | Layer | What it solves |
|---|---|---|
| `fhe-pattern` | privacy | A contract that computes on secret inputs has no good options on a transparent EVM: store the value encrypted and… |
| `plonk-pattern` | execution | Groth16's practical dominance came at a price that is easy to forget because it is invisible in the proof object:… |
| `stealth-address-pattern` | privacy | Ethereum is fully transparent: sending to Alice publishes that Alice received it, and any observer can build a… |
| `zksnark-groth16` | execution | A ZK-rollup or a privacy protocol needs the prover to publish a small artefact that lets anyone verify a large… |
| `zkstark-pattern` | execution | A zk-SNARK buys compact proofs and fast verification at the price of a trusted setup — a secret whose leakage… |

#### security (10)

| Pattern | Layer | What it solves |
|---|---|---|
| `checks-effects-interactions` | security | The Checks-Effects-Interactions pattern organises every statement in a state-changing function into one of three… |
| `eip712-typed-data` | execution | Signing an opaque 32-byte hash is unforgeable but useless: a wallet cannot show the user what they are… |
| `merkle-whitelist` | execution | A token launch, a presale or an airdrop needs to restrict access to a specific list of addresses — but the list… |
| `multisig` | wallet | An EOA has exactly one key: lose it and the funds are gone; share it and a single compromise drains the account. |
| `ownable` | security | Ownable is the smallest possible privilege model for a smart contract: exactly one address may call a set of… |
| `pull-over-push` | execution | A contract that distributes value to many recipients has a choice: push (call out to each recipient during one… |
| `reentrancy-guard` | security | The EVM gives the callee of an external call full control of the remaining gas, and `msg.sender` changes with… |
| `reveal-mechanism` | execution | On a public chain, timing is a weapon. |
| `social-recovery-pattern` | wallet | A single key is the weakest link in self-custody: losing it loses everything, and hardware does not prevent a lost… |
| `unchecked-math` | execution | EVM arithmetic wraps silently: `uint8(255) + 1` is `0`, and a subtraction that should have failed returns a value… |

#### storage (6)

| Pattern | Layer | What it solves |
|---|---|---|
| `arweave-permanent` | storage | Arweave solves a problem Ethereum-style chains do not: data written today must still be retrievable in a hundred… |
| `data-timestamping` | storage | A legal, journalistic or compliance workflow needs to prove that a specific document, database row, git commit or… |
| `eternal-storage-pattern` | storage | Off-chain content storage — including the metadata behind essentially every NFT — has no guarantee at all: objects… |
| `ipfs-gateway-fallback` | storage | An NFT contract returns `ipfs://<CID>/metadata.json`, but the client that renders it is an ordinary HTTP consumer… |
| `ipfs-storage` | storage | A token or contract that needs to reference something larger than a word cannot store it on-chain, so it stores a… |
| `on-chain-metadata` | storage | An NFT's identity is a tokenId; everything a holder and a marketplace need to know about it — name, description,… |

#### token-standard (9)

| Pattern | Layer | What it solves |
|---|---|---|
| `erc1155` | token-standard | ERC-20 and ERC-721 both force one contract per token type, so a game with thousands of item types pays thousands… |
| `erc721-enumerable` | nft | ERC-721 can tell you who owns a token, but it cannot tell you which tokens exist or which ones an address holds —… |
| `erc721` | token-standard | You need an asset where every unit is individually distinguishable and individually transferable — a deed to a… |
| `erc721a` | nft | The OpenZeppelin reference ERC-721 writes one ownership slot per minted token, so a 10,000-token mint costs… |
| `real-estate-tokenization` | token-standard | Property is a legal claim recorded in a county registry and enforced by courts, not a cryptographic balance. |
| `rebase-mechanism` | token-standard | Rebasing flips the convention that every yield-bearing token inherits from ERC-20: the *balance* moves rather than… |
| `semi-fungible-tokens` | nft | Many collectible and ticketing products need more than one copy of the 'same' thing, and yet not as many as a… |
| `tokenization` | token-standard | An asset — a share, a bond, a unit of money, a piece of property, a commodity — exists as a record in some… |
| `tokenized-treasury-rwa` | token-standard | On-chain treasury management has a gap that stablecoins do not fill: a stablecoin preserves principal but earns… |

---

## Working Together with design-pattern-mcp-local

This server answers *which protocol shape to build* (the blockchain system design); the sibling [design-pattern-mcp-local](https://git.odvlh.xyz/olli/design-pattern-mcp-local) answers *how each unit inside it is coded* (design patterns). A **blockchain pattern** structures the whole protocol — its components, their relationships, and its API/data/event contracts (e.g. `optimistic-rollup`, `lock-mint-bridge`, `erc4337`, chosen from the 109-pattern catalog above). A **design pattern** solves one recurring implementation problem inside a single contract or service — its participants, interactions, and language-bound code (e.g. `observer`, `process-manager`, `circuit-breaker`, chosen from the sibling's 438-pattern catalog with 13 language bindings each).

Recommended order — protocol first, implementation second:

```
1. Call design_blockchain with:
     requirements: "Lock-mint bridge with fraud proofs and rate-limited mints"
     domain: "bridge"
   # → components (escrow contract, minter, relayer, verifier, guardian),
   #   relationships, API contracts, data models, event contracts

2. For each component with non-trivial internal logic, call the sibling's
   select_design_patterns with:
     description: "<component name + responsibilities + constraints from step 1>"
     language: "python"
   # → primary + supporting patterns, participants, implementation_steps,
   #   code_sketch with the bound language variant
```

Concrete handoff on the bridge example: this server emits the `lock-mint-bridge` design (escrow → attestation → mint, with a fraud-proof window and rate limits in the contracts). The relayer's retry and dedup path then goes to `select_design_patterns` ("idempotent attestation submission with backoff and a consumed-message store") — e.g. a `circuit-breaker` + `idempotent-consumer` design with participants, `implementation_steps`, and a Python `code_sketch` — which the protocol-level component contract references but never implements.

Run both servers side by side (dev host ports `:8823` blockchain, `:8822` design-pattern; systemd host ports `:8813` blockchain, `:8052` design-pattern). They are independent — either order works for exploration — but protocol-first keeps component boundaries stable while the design server fills in the internals.

## Install Alternatives

### Docker (manual)

```bash
# Build the image
make docker-build

# Run with your API key
OPENCODE_API_KEY=your_key docker compose -f docker/docker-compose.yml up -d
```

### Local Development (uv)

**Prerequisites:** Python 3.12+, [uv](https://github.com/astral-sh/uv)

```bash
# Install
make install

# Configure
cp config/config.json ~/.config/blockchain-pattern-mcp/config.json
# Edit ~/.config/blockchain-pattern-mcp/config.json and set your GENERATOR_API_KEY

# Run the server
uv run python -m src.main --transport stdio              # for Claude Code / Codex
uv run python -m src.main --port 8823                    # for OpenCode (HTTP)
```

Or use the installed console script (after `make install`):

```bash
blockchain-pattern-mcp --transport stdio
```

The TEI embedder (Qwen3-Embedding-0.6B) is required for domain-scoped pattern retrieval. Without it, the server falls back to the default pattern. Docker compose starts it automatically; local users must run it separately on port 8080.

The retrieval legs are built at server startup: BM25 always, the FAISS dense leg from the [embedding-index cache](#embedding-index-cache-dense-retrieval-snapshot) when a valid snapshot exists (otherwise embedded from scratch). Startup stays fail-fast — every start makes one probe embedding call, so a misconfigured or unreachable TEI sidecar aborts warmup rather than breaking the user's first design request. Docker compose's `service_healthy` dependency ordering guarantees TEI is ready before the app starts.

> **TEI startup:** both sidecar images (`docker/Dockerfile.tei-embed-gpu`, `docker/Dockerfile.tei-rerank-gpu`, with `-cpu` mates for GPU-less hosts) ship a self-built TEI router (v1.9.4 + unmerged [PR #884](https://github.com/huggingface/text-embeddings-inference/pull/884)) with `WARMUP_TOKENS=0` by default — this skips the synthetic warmup pass so containers become ready after weight load only. Override per sidecar via `TEI_WARMUP_TOKENS` / `TEI_RERANK_WARMUP_TOKENS` (positive N warms with N tokens instead; values > `MAX_BATCH_TOKENS` are rejected at startup).

**GPU TEI:** both sidecars are CUDA images (`cuda-1.9` base) with a self-built router built for sm_61 as the minimum — the GTX 1080 Ti (compute capability 6.1) sits below the stock image's 75 floor, so the router is compiled from the same TEI tag with the non-flash CUDA feature set and overwrites the stock binary. The embedded PTX JIT-compiles on newer cards, so the same image serves sm >= 61 (Ampere/Ada/Hopper/Blackwell); first model load on a newer card pays a one-time JIT compile, and sm_61 is the only hardware tested so far. Both serve safetensors weights through candle (no ONNX). `make docker-up-gpu` requires an NVIDIA GPU via the container toolkit (CDI reservation in `docker/docker-compose.yml`). GPU-less hosts use the CPU pair instead (`make docker-build-tei-cpu`, `make docker-up-cpu`) — same models, shared embedding-index snapshot. A stock upstream TEI image without [PR #884](https://github.com/huggingface/text-embeddings-inference/pull/884) silently ignores `WARMUP_TOKENS`.

**Already-running embedder/reranker:** when embedding and reranking endpoints already run on other servers, point the MCP server at them and skip the sidecars (`docker/docker-compose.hub.yml` starts the MCP server only and wires exactly this). The remote embedder must be TEI serving the same model — keep `EMBEDDER_PROVIDER=tei` and set `EMBEDDER_BASE_URL` to its OpenAI-compatible route (dev-compose convention: `http://<host>:8080/v1`; the `config.json` default is the bare `http://pattern-tei-embed:8080`). This server's embedder config has **no `model` field** (`src/patterns/embedder.py::build_embedder` sends an empty model name for the non-`tei` providers), so `openai` / `ollama` / `vllm` / `hosted_vllm` cannot address an arbitrary remote model without a code change. The reranker is **not** a LiteLLM client — it POSTs `{RERANKER_BASE_URL}/rerank` directly (default `http://pattern-tei-rerank:8080`, no `/v1`); provider/model syntax in the [LiteLLM embedding docs](https://docs.litellm.ai/docs/embedding/supported_embedding) applies to the embedder only. `EMBEDDER_API_KEY` is forwarded as the LiteLLM `api_key` (any non-empty string satisfies a no-auth TEI).

---

## Configuration

### config.json

The server reads `~/.config/blockchain-pattern-mcp/config.json` (override with `--config-path`):

```json
{
  "generator": {
    "provider": "openai",
    "config": {
      "model": "gpt-4o-mini",
      "base_url": "https://api.openai.com/v1",
      "api_key": "{env:GENERATOR_API_KEY}",
      "temperature": 0.1,
      "top_p": 1.0,
      "top_k": 20
    }
  },
  "embedder": {
    "provider": "tei",
    "config": {
      "base_url": "http://127.0.0.1:8080"
    }
  },
  "retrieval": {
    "bm25_top_k": 0,
    "dense_top_k": 0,
    "top_k_patterns": 5,
    "min_quality_score": 50.0
  },
  "pattern_directory": "~/.config/blockchain-pattern-mcp/pattern",
  "transport": "streamable-http",
  "host": "0.0.0.0",
  "port": 8050,
  "logging_level": "INFO",
  "logging_format": "json"
}
```

`{env:VAR:-default}` syntax expands environment variables at load time.

### Generator LLM (LlamaIndex LiteLLM)

The generator LLM is accessed through the **LlamaIndex LiteLLM integration** ([`llama-index-llms-litellm`](https://docs.llamaindex.ai/en/stable/examples/llm/litellm/)). All provider settings therefore follow **LiteLLM's model syntax**: `<provider>/<model>` (e.g. `openai/gpt-4o-mini`, `anthropic/claude-sonnet-4-5`, `openrouter/minimax/minimax-m2`).

The server composes the LiteLLM model string from your configuration as `generator.provider` + `generator.config.model`:

| Config / env | Example | Resulting LiteLLM model string |
|---|---|---|
| `provider: "openai"`, `model: "gpt-4o-mini"` | `GENERATOR_PROVIDER=openai`, `GENERATOR_MODEL=gpt-4o-mini` | `openai/gpt-4o-mini` |
| `provider: "anthropic"`, `model: "claude-sonnet-4-5"` | `GENERATOR_PROVIDER=anthropic`, `GENERATOR_MODEL=claude-sonnet-4-5` | `anthropic/claude-sonnet-4-5` |
| `provider: "openrouter"`, `model: "minimax/minimax-m2"` | `GENERATOR_PROVIDER=openrouter`, `GENERATOR_MODEL=minimax/minimax-m2` | `openrouter/minimax/minimax-m2` |

If the configured model already contains a provider prefix (e.g. `openai/gpt-4o-mini`), that prefix is stripped and replaced by the configured `provider`.

- **Provider list, model names, and the exact `<provider>/<model>` syntax:** [LiteLLM Providers documentation](https://docs.litellm.ai/docs/providers)
- Custom/OpenAI-compatible endpoints (proxies, vLLM, Ollama, …): set `GENERATOR_BASE_URL` (`generator.config.base_url`) — it is passed as the LiteLLM `api_base`
- `GENERATOR_API_KEY` is passed as the LiteLLM `api_key`; `temperature`, `top_p`, `top_k`, and `stream` map to the corresponding LiteLLM parameters

### Key environment variables

| Variable | Default | Description |
|---|---|---|
| `GENERATOR_API_KEY` | *(required)* | API key for your LLM provider (passed to LiteLLM as `api_key`) |
| `GENERATOR_PROVIDER` | `openai` | LiteLLM provider prefix: `openai`, `anthropic`, `openrouter`, … — see [LiteLLM Providers](https://docs.litellm.ai/docs/providers) |
| `GENERATOR_BASE_URL` | `https://api.openai.com/v1` | API base URL (passed to LiteLLM as `api_base`) |
| `GENERATOR_MODEL` | `gpt-4o-mini` | Model name; final model string is `<GENERATOR_PROVIDER>/<GENERATOR_MODEL>` (LiteLLM syntax) |
| `GENERATOR_TEMPERATURE` | `0.1` | Sampling temperature |
| `GENERATOR_TOP_P` | `1.0` | Top-p sampling |
| `GENERATOR_TOP_K` | `20` | Top-k sampling |
| `GENERATOR_STREAM` | `false` | Enable streaming responses |
| `EMBEDDER_PROVIDER` | `tei` | Embedder provider |
| `EMBEDDER_BASE_URL` | `http://127.0.0.1:8080` | TEI embedder URL |
| `EMBEDDER_BATCH_SIZE` | `16` | Embedding batch size |
| `EMBEDDER_QUERY_INSTRUCTION` | *(empty)* | Query instruction prefix |
| `EMBEDDER_TEXT_INSTRUCTION` | *(empty)* | Text instruction prefix |
| `EMBEDDING_CACHE` | image: `/var/cache/blockchain-pattern-mcp/embedding-index` · host: `~/.config/blockchain-pattern-mcp/embedding-index` | Dense-leg snapshot path: reloaded on restart (zero corpus re-embedding), rebuilt on any embedder/corpus/probe change. `0`/`false`/`off`/`no` disables. See [Embedding-index cache](#embedding-index-cache-dense-retrieval-snapshot) |
| `RETRIEVAL_BM25_TOP_K` | `0` | BM25 stage-1 recall cap (0=full corpus) |
| `RETRIEVAL_DENSE_TOP_K` | `0` | Dense stage-1 recall cap (0=full corpus) |
| `RETRIEVAL_DENSE_WEIGHT` | `0.7` | **Stage-1 fusion leg weight** on the dense leg. Pairs with `RETRIEVAL_BM25_WEIGHT`; both must be > 0 and sum to 1.0 (±1e-3, startup validation). Either weight < 0.05 logs a startup warning. Distinct from the Stage-2 selection blend weights (`RETRIEVAL_ANALYSIS_BLEND_WEIGHT` / `RETRIEVAL_FUSION_BLEND_WEIGHT`). Note: config keys unknown to an older image fail fast at startup. |
| `RETRIEVAL_BM25_WEIGHT` | `0.3` | **Stage-1 fusion leg weight** on the BM25 leg. See `RETRIEVAL_DENSE_WEIGHT`. |
| `RETRIEVAL_TOP_K_PATTERNS` | `5` | Number of patterns to select |
| `RETRIEVAL_MIN_FUSION_SCORE` | `0.0` | Relevance floor on the rank_fusion blend value (range [0, 2/60] ≈ [0, 0.033]). Default 0.0 (gate disabled). Values above the blend maximum are rejected at startup. |
| `RETRIEVAL_RERANK_TOP_N` | `10` | Rerank top N (slug-cut after CE) |
| `RETRIEVAL_USE_LEAN_WIRE_SCHEMA` | `false` | Use lean response schema |
| `RETRIEVAL_STYLE_SCORE_THRESHOLD` | `50.0` | Min analysis score for style recommendation |
| `REASONING_ENABLED` | `false` | Server-side reasoning MCP integration — **opt-in**, off by default (see [Structured Reasoning](#structured-reasoning-shannonthinking--code-reasoning)) |
| `REASONING_SPAWN_TIMEOUT_SECONDS` | `10` | Subprocess spawn timeout per reasoning tool |
| `REASONING_STEP_TIMEOUT_SECONDS` | `20` | Per-thought tool-call timeout |
| `REASONING_MAX_TOTAL_STEPS` | `8` | Hard cap on reasoning steps per phase |
| `REASONING_QUIET_STDERR` | `true` | Silence reasoning-subprocess stderr (ASCII progress boxes, `[info]` banners); set `false` to debug spawn failures |
| `REASONING_FAIL_FAST` | `true` | Fail server startup when a reasoning tool is unreachable |
| `REASONING_SHANNONTHINKING_CMD` | *(embedded)* | JSON list command for shannonthinking (e.g. `["npx","-y","server-shannon-thinking@latest"]`) |
| `REASONING_CODE_REASONING_CMD` | *(embedded)* | JSON list command for code-reasoning |
| `RETRIEVAL_ANALYSIS_BLEND_WEIGHT` | `0.7` | Weight on analysis score in blend |
| `RETRIEVAL_FUSION_BLEND_WEIGHT` | `0.3` | Weight on fusion score in blend |
| `RETRIEVAL_WEIGHT_SMOOTHING_ALPHA` | `0.7` | Weight smoothing alpha |
| `PIPELINE_TIMEOUT_SECONDS` | `1200` | Wall-clock budget (seconds) for one complete design run — all phases (analyze → generate → evaluate → refine) and every retry attempt. On expiry the run is cancelled and the tool call fails with `WorkflowTimeoutError`; the partial design is discarded. Raise it when `REASONING_ENABLED=true` on a slow provider, lower it to fail fast. Config key: `pipeline.timeout_seconds`. |
| `RETRIEVAL_VERBOSE_TIMING` | `false` | Log phase timings at INFO level |
| `RETRIEVAL_MAX_TRIES` | `3` | Max design loop attempts |
| `RETRIEVAL_MIN_QUALITY_SCORE` | `50.0` | Early-stop quality threshold |
| `RERANKER_BASE_URL` | *(default reranker URL)* | TEI reranker endpoint (host:port); model is fixed to `gte-reranker-modernbert-base` |
| `RERANKER_TIMEOUT` | `30.0` | Reranker timeout (seconds) |
| `RERANKER_MAX_BATCH_SIZE` | `48` | Max texts per TEI /rerank request; must be ≤ min(MAX_CLIENT_BATCH_SIZE, MAX_CONCURRENT_REQUESTS) of the reranker sidecar. HybridPatternRetriever chunks large pools automatically. |
| `PATTERN_DIRECTORY` | `/app/pattern` | Pattern files directory (the image bakes the 109-pattern catalogue there) |
| `BLOCKCHAIN_PATTERN_JOBS_DB` | `~/.config/blockchain-pattern-mcp/jobs.db` | SQLite path for async job trio. Override for test isolation |
| `TASKS_HEARTBEAT_ENABLED` | `true` | Emit progress notifications during long tool calls |
| `TASKS_HEARTBEAT_INTERVAL_SECONDS` | `30` | Heartbeat interval in seconds (keep below client idle timeout) |
| `VALIDATION_MAX_RETRIES` | `2` | Max self-healing retry attempts |
| `VALIDATION_RETRY_ON_FAIL` | `true` | Retry on validation failure |
| `TRANSPORT` | `streamable-http` | Transport mode: `stdio`, `streamable-http` |
| `HOST` | `0.0.0.0` | HTTP bind host |
| `PORT` | `8050` | HTTP bind port |
| `LOGGING_LEVEL` | `INFO` | Logging level |
| `LOGGING_FORMAT` | `json` | Logging format: `json`, `text` |
| `CONFIG_PATH` | `~/.config/blockchain-pattern-mcp/config.json` | Config file path |

### Embedding-index cache (dense retrieval snapshot)

The dense retrieval leg is one FAISS index over every catalogue domain slug
(24). Its embeddings are snapshotted to disk after a cold build and reloaded on
the next start, so a warm start costs **one probe embedding** instead of a full
corpus pass. BM25 is cheap and rebuilt every start.

- **Path**: `EMBEDDING_CACHE`. The image bakes
  `/var/cache/blockchain-pattern-mcp/embedding-index`; host runs (`uv`) use
  `~/.config/blockchain-pattern-mcp/embedding-index`.
- **Where the files live**: the logged path is the *in-container* view. Docker
  stores the named volume at `/var/lib/docker/volumes/<volume-name>/_data`
  (root-owned), so `/var/cache` on the host stays empty by design. Inspect
  without sudo: `docker exec <container> ls
  /var/cache/blockchain-pattern-mcp/embedding-index`, or
  `docker volume inspect -f '{{.Mountpoint}}' <volume-name>` for the host side.
- **Containers persist it in a named volume**
  (`blockchain-pattern-mcp-dev-embedding-index` /
  `blockchain-pattern-mcp-systemd-embedding-index`), so the snapshot survives
  image rebuilds, container recreation and `docker compose down`. Reset it with
  `docker compose down -v` or `docker volume rm <name>`; a bare `docker run`
  needs `-v blockchain-pattern-mcp-embedding-index:/var/cache/blockchain-pattern-mcp/embedding-index`.
- **Rebuilt automatically** when the embedding function changes (provider,
  `base_url`, resolved model name, query/text instruction prefixes), when the slug
  corpus changes, or when a probe vector shows a *different model behind an
  unchanged config* (e.g. a redeployed TEI sidecar). Log lines:
  `Embedding index cache hit: N slugs, 0 corpus embed calls (snapshot
  <cache-dir>)` / `Embedding index cache miss (<reason>); embedding corpus` /
  `Embedding index snapshot written: N slugs (path <cache-dir>)` — emitted
  immediately after the embedding pass, before any other startup step — and,
  with the cache switched off, `Embedding index cache disabled; embedding corpus`
  (never reported as a miss).
- **Single writer**: no locking — run one server process per cache directory.
  A failed snapshot write only logs a warning; the server runs cacheless and
  never fails the start.
- Operations notes (volumes, permissions, disable switch): [INSTALL.md](INSTALL.md#embedding-index-cache).

### CLI flags

| Flag | Description |
|---|---|
| `--transport {stdio,streamable-http}` | Override transport mode |
| `--host` | Override HTTP bind host (default: 0.0.0.0) |
| `--port` | Override HTTP port (default: 8050) |
| `--config-path` | Path to config file |
| `--health` | Run health check and exit |

---

## Structured Reasoning (shannonthinking / code-reasoning)

Before each LLM phase call (ANALYZE / GENERATE / EVALUATE / RETRY), the server
optionally runs a bounded **ThoughtGenerator loop**: it authors each reasoning
step with the generator's own LLM (LlamaIndex LiteLLM; one completion per
step) and submits it to the
[shannonthinking](https://github.com/olaservo/shannon-thinking) and/or
[code-reasoning](https://github.com/mettamatt/code-reasoning) MCP servers —
structured thinking scratchpads that validate, number, and record each step.
The resulting trace is injected into the phase prompt as a
`<reasoning_context>` block. Contract: **each thought = 1 LLM completion + 1
MCP tool call**, capped by `REASONING_MAX_TOTAL_STEPS` (default 8).

Key properties:

- **Embedded in Docker** — the `build-mcps` stage bakes both npm packages
  (`server-shannon-thinking@0.1.1`, `@mettamatt/code-reasoning@0.8.1`) into
  the image at `/usr/local/lib/node_modules/...`; the runtime invokes them
  directly via `node` (no network, no npx).
- **Auto-fallback to npx** outside Docker — when the embedded entry points
  are missing, the client falls back to `npx -y <pkg>` (first call downloads).
- **Process-per-call isolation** — each tool call runs in a fresh subprocess
  (`keep_alive=False`); nothing persists between calls.
- **Silent per-call degradation** — any spawn/timeout/tool failure logs a
  WARNING and the phase proceeds with a degraded in-prompt thinking scaffold
  (decompose → classify → calibrate → resolve → verify); it never raises.
- **Loud startup** — the lifespan health-check probes both tools and logs an
  ERROR (with resolution hints) if one is unreachable; set
  `REASONING_FAIL_FAST=true` to make startup fail instead.
- **Trace caching** — ANALYZE and GENERATE traces are computed once per
  design request and reused across design-loop attempts.

### Opting in / tuning

Reasoning is **disabled by default** in this port: it measured at ~55% of
end-to-end design latency for no selection-quality gain in the sibling's
Stage-0 benchmark. Enable it with `REASONING_ENABLED=true`.

```bash
export REASONING_ENABLED=true           # enable the reasoning MCP integration
export REASONING_FAIL_FAST=true         # refuse to start with broken MCPs
```

Local (non-Docker) development needs Node.js; either install the packages
globally (`npm install -g server-shannon-thinking @mettamatt/code-reasoning`)
or let the npx fallback download them on first use.

Latency note: a design run issues 14 reasoning tool calls (analyze 8, generate
3, evaluate 3) as serial subprocesses — minutes, not seconds. The trace cache
removes repeated ANALYZE/GENERATE work across design-loop attempts but not the
first pass.

Set `LOGGING_LEVEL=DEBUG` to capture the authored `thought` and tool response
for every per-step reasoning call. Docker/systemd stacks default to INFO;
export `LOGGING_LEVEL=DEBUG` before `make docker-up-gpu` (or `make docker-up-cpu`).

---

## Extending with Custom Patterns

Pattern files are loaded from the directory in `PATTERN_DIRECTORY` (the image
uses `/app/pattern`). Drop a JSON file alongside the 109 built-in patterns.

**Minimal pattern structure** (every required key from `docs/pattern-schema.json`):

```json
{
  "name": "my-custom-pattern",
  "aliases": ["my-pattern"],
  "category": "security",
  "layer": "execution",
  "context": "Describe when this pattern applies.",
  "mechanism": "Describe the mechanism that makes it work.",
  "invariants": ["Invariant that must always hold"],
  "participants": [
    {"role": "contract", "responsibility": "Enforces the invariant on-chain"}
  ],
  "benefits": ["Benefit 1"],
  "tradeoffs": ["Tradeoff 1"],
  "quality_attributes": {
    "security": 8,
    "cost_efficiency": 6,
    "scalability": 6,
    "decentralization": 7,
    "composability": 6,
    "liquidity": 5,
    "simplicity": 7,
    "privacy": 5
  },
  "known_attacks": ["Attack this pattern defends against"],
  "mitigations": ["How the pattern mitigates it"],
  "audit_checklist": ["What an auditor must verify"],
  "related_patterns": ["checks-effects-interactions"],
  "design_principles": ["Principle this pattern embodies"],
  "best_practices": ["Practice to follow"],
  "ecosystem": ["Reference implementation"],
  "references": ["https://example.org/spec"],
  "version": "1.0.0"
}
```

Required fields: `name`, `aliases`, `category`, `layer`, `context`, `mechanism`, `invariants`, `participants`, `benefits`, `tradeoffs`, `quality_attributes` (exactly the eight dims, 1–10), `known_attacks`, `mitigations`, `audit_checklist`, `related_patterns`, `design_principles`, `best_practices`, `ecosystem`, `references`, `version`. Optional: `use_cases`, `avoid_when`, `anti_patterns`.

Valid `category` values: `account-abstraction`, `bridge`, `defi-primitive`, `defi-trading`, `developer-tooling`, `governance`, `identity`, `l2-scaling`, `lifecycle`, `mev`, `nft`, `oracle`, `privacy`, `security`, `storage`, `token-standard`.

Valid `layer` values: `bridge`, `consensus`, `data-availability`, `defi-primitive`, `defi-trading`, `execution`, `governance`, `identity`, `mempool`, `mev`, `networking`, `nft`, `oracle`, `privacy`, `scaling-l2`, `security`, `storage`, `token-standard`, `tooling`, `wallet`.

Full JSON Schema with all enums: `docs/pattern-schema.json`. Validate the whole catalogue with `make verify-patterns`.

---

## Long-running tools & timeouts

`design_blockchain` runs a multi-stage LLM pipeline that **can take 5–10 minutes per call**. This is inherent to the workload, not a bug: the generator LLM must process a large input payload — the selected pattern definitions from the 109-pattern catalog, your requirements, and the full output of every previous stage — and produce a large, strictly structured JSON document (components, relationships, API contracts, data models, event contracts, quality scores) one token at a time. The `design_blockchain` pipeline repeats generate → evaluate up to three times, so a single call can comprise 9+ LLM round trips.

`analyze_blockchain` is not in that class: it is one lightweight LLM call (roughly a minute) that returns recommendations — style, pattern cards, the selected patterns' aggregate quality profile — not a design. It is the path for a coding agent that will write the implementation itself. `generate_blockchain` and `evaluate_blockchain` are single LLM round trips too, but each still runs for minutes.

### The timeout problem

MCP clients (AI coding agents, MCP SDKs) sit between the server and the LLM. Many of them implement a **client-side idle timeout**: if no data is received on the HTTP connection for some period (typically 30–120 seconds), the client aborts the request. The server is still working — the LLM is still generating — but the client closes the connection and reports a timeout error to the agent.

This is a client-side behaviour, not a server-side one. The server processes the full request correctly; the client simply gives up before the response arrives.

**Affected clients (hardcoded short timeouts):**

| Client | Timeout | Notes |
|---|---|---|
| Claude Desktop (TS-SDK) | 60 s | Hardcoded; does not reset on progress notifications |
| Cursor (TS-SDK) | 60 s | Same as Claude Desktop |
| Other TS-SDK based agents | varies | Most cap at 60–120 s |

These clients cannot be reconfigured to accept longer timeouts — the timeout is baked into the SDK.

**Clients covered by the heartbeat defence:**

| Client | Timeout | Defence |
|---|---|---|
| Claude Code | ~300 s | Heartbeat every 30 s resets idle timer |
| OpenCode | ~300 s | Heartbeat every 30 s resets idle timer |
| Codex CLI | ~300 s | Heartbeat every 30 s resets idle timer |
| Other HTTP-transport agents | varies | Most reset on any received data |

Works for these because their idle timers are reset by any incoming data — the heartbeat `progress` notifications sent from a parallel async task on the server are received by the client, resetting its clock.

### The heartbeat defence (applied by default)

Every long-running tool emits `progress` notifications from a parallel coroutine every 30 seconds (configurable via `TASKS_HEARTBEAT_INTERVAL_SECONDS`). As long as the client resets its idle timer on any received data, the request stays alive for the full duration of the pipeline.

> **TS-SDK clients (Claude Desktop, Cursor, etc.) do not reset their timeout on progress notifications.**

### The async job trio (for timeout-constrained clients)

For full control and compatibility with timeout-limited clients, three tools provide a durable job handle:

```
submit_blockchain_design_job(requirements, domain, override_style)  → job_id
get_blockchain_design_status(job_id)                                  → {status, result, error}
cancel_blockchain_design(job_id)                                      → {cancelled, status}
```

`submit_blockchain_design_job` returns a `job_id` in milliseconds. The pipeline runs in a background task. Poll `get_blockchain_design_status(job_id)` every 10–30 seconds. When status is `completed`, the full design is in the `result` field. Cancellation is best-effort — the job exits at the next pipeline stage boundary.

**This is the only fix that works for TS-SDK clients (Claude Desktop, Cursor).**

The job store is SQLite at `~/.config/blockchain-pattern-mcp/jobs.db` (configurable via `BLOCKCHAIN_PATTERN_JOBS_DB`).

### Bypassing client timeouts with a direct client

The example client in `examples/blockchain_client.py` is a **direct Python client** — it is not an MCP agent. It calls the server over HTTP through the FastMCP client without any client-side idle timeout: it makes a single blocking request and waits for the full response.

```bash
# Start the server (from project root)
docker compose -f docker/docker-compose.yml up --build

# In another terminal: fast analyze demo / full design demo (5-10 min)
make client-analyze        # analyze_blockchain only
make client-design         # design_blockchain, the long synchronous call
```

Both targets drive the same direct client (`--tool analyze|design`). `make client-design` demonstrates that the server **correctly completes** long requests — the timeout issue is purely a client-side problem. Host applications that wrap MCP (Claude Desktop, Cursor, …) impose their own timeouts; use the async job trio there.

## Troubleshooting

### Server starts but tools are not visible

1. Check the agent's MCP connection: Claude Code `/mcp`, OpenCode `opencode mcp list`, Codex `codex mcp list`
2. Verify the server process started: compose logs should show `MCPBlockchainServer initialized`
3. Confirm the TEI embedder is healthy: `curl http://127.0.0.1:8080/health` inside the container

### "Connection refused" or timeout errors

The server waits for the TEI embedder to become healthy:

```bash
docker compose -f docker/docker-compose.yml logs pattern-tei-embed
```

### LLM provider errors (502 / 401)

- Confirm `GENERATOR_API_KEY` is set and not expired
- Verify `GENERATOR_BASE_URL` matches your provider's endpoint
- If using a proxy, check reachability from inside the container

### Pattern JSON files not loading

- Files must have `.json` extension
- Required fields: the full required list in [Extending with Custom Patterns](#extending-with-custom-patterns)
- Validate against `docs/pattern-schema.json` (or run `make verify-patterns`)

---

## Building & Development

**Common make targets** (full reference: [docs/make_rules.md](docs/make_rules.md)):

| Target | Description |
|---|---|
| `make install` | Install package in editable mode with dev dependencies |
| `make check-lint` | Run ruff linting |
| `make check-static-typing` | Run mypy --strict type checking on src/ |
| `make check-all` | Run every check-* quality gate (lint, types, dead code, deps) |
| `make test-unit` | Run unit tests with uv (tests/unit/) |
| `make client-analyze` | Run the analyze-only MCP client demo (requires server running) |
| `make client-design` | Run the synchronous design_blockchain client demo (long-running; requires server running) |
| `make docker-build` | Build the MCP server Docker image |
| `make docker-build-all` | Build MCP server + GPU TEI pair + CPU TEI pair |
| `make docker-publish` | Push image to Docker Hub + GHCR (version + latest) |
| `make docker-up-gpu` | Build and start all services (CUDA pair, needs an NVIDIA GPU) |
| `make docker-up-cpu` | Build and start all services on the CPU pair (no GPU needed) |
| `make docker-down` | Stop all services |

**Development workflow:**

```bash
make install                      # First-time setup
uv run pre-commit install         # First-time setup: commit hook
make check-all                    # Before pushing (lint + types + dead code + deps)
make docker-build-all             # Build all images (first time and after code changes)
make docker-up-gpu                # Start services (docker-up-cpu on GPU-less hosts)
make docker-logs-follow           # Watch logs
make docker-down                  # Stop
```

---

## Publishing

All three images are published to two registries simultaneously:

| Image | Docker Hub | GHCR | Tags |
|---|---|---|---|
| MCP server | `olkowa/blockchain-pattern-mcp` | `ghcr.io/olk/blockchain-pattern-mcp` | `$(DOCKER_TAG)`, `latest` |
| TEI embedder | `olkowa/blockchain-pattern-tei-embed-gpu` | `ghcr.io/olk/blockchain-pattern-tei-embed-gpu` | `$(DOCKER_TAG)`, `latest` |
| TEI reranker | `olkowa/blockchain-pattern-tei-rerank-gpu` | `ghcr.io/olk/blockchain-pattern-tei-rerank-gpu` | `$(DOCKER_TAG)`, `latest` |

All three images share the same `$(DOCKER_TAG)` (the version from `pyproject.toml`), so `tei:1.0.0` always ships with `mcp:1.0.0`. Blob deduplication keeps re-tagging unchanged TEI images cheap.

> **Bandwidth note:** the TEI embedder image is ~7.3 GB (safetensors weights baked in; reranker ~6.7 GB). First push to each registry is ~7 GB upload. Subsequent pushes are incremental — only changed layers are transferred.

### Prerequisites

**Docker Hub** — already authenticated locally (`docker login`).

**GitHub Container Registry** — requires a [classic PAT](https://github.com/settings/tokens/new?scopes=write:packages) with `write:packages` scope. 2FA is not an issue — PATs bypass it. After login the token is discarded; the credential persists in `~/.docker/config.json` until you log out.

### Publish (one-time setup + per-session)

```bash
# 1. Login to GHCR (interactive — paste token at the password prompt)
docker login ghcr.io -u Olk

# 2. Build and push all three images (MCP + TEI embedder + TEI reranker)
#    The umbrella target builds the MCP image, tags it, pushes it, creates the git tag,
#    then builds and pushes each TEI image in sequence.
make docker-publish-all

# 3. Logout from GHCR immediately after publishing
#    (removes the ghcr.io credential from ~/.docker/config.json)
docker logout ghcr.io
```

On subsequent publishes repeat steps 1–3. If your PAT has expired, generate a new one at the link above.

### First push — set packages public (GHCR only)

GHCR packages default to **private**. After the first `make docker-publish-all`, flip all three packages to public:

| Package | Settings URL |
|---|---|
| MCP server | `https://github.com/users/Olk/packages/container/blockchain-pattern-mcp/settings` |
| TEI embedder | `https://github.com/users/Olk/packages/container/blockchain-pattern-tei-embed-gpu/settings` |
| TEI reranker | `https://github.com/users/Olk/packages/container/blockchain-pattern-tei-rerank-gpu/settings` |

Set each to **Public** and save.

### Partial failure recovery

If the push fails mid-way (e.g., GHCR auth was not configured), Docker Hub layers are already uploaded. After fixing auth, re-running `make docker-publish-all` is safe — each registry reports a cache hit for already-uploaded layers and completes the remaining push. For targeted retries, use `make docker-publish` (MCP server image only) or `make docker-publish-tei` (both GPU TEI images; the `-cpu` pair is never published).

---

## systemd Service (Linux)

The server can run as a systemd service on any systemd-based Linux host. It
starts the Docker Compose stack automatically at boot.

### File layout

The `systemd/` directory contains four files:

| File | Purpose |
|---|---|
| `systemd/blockchain-pattern-mcp.service` | The systemd unit |
| `systemd/docker-compose.yml` | Production compose variant (no `build:`, absolute paths) |
| `systemd/docker-compose.cpu.yml` | CPU lane overlay for GPU-less TEI infra hosts (see `systemd/README.md` "CPU lane") |
| `systemd/README.md` | Full runbook with install, verify, and troubleshooting |

The production compose file is a deployment variant of `docker/docker-compose.yml`:
it has no `build:` sections (images must be pre-built), uses absolute paths, and
lives under `/etc/blockchain-pattern-mcp/` on the host. The systemd-managed
project uses the distinct name `bcmcp-systemd` so it can coexist with the dev
compose if needed.

> **TEI sidecars are NOT defined in this stack** — the `pattern-tei-embed` embedder
> and `pattern-tei-rerank` reranker containers live in the shared
> [`pattern-tei-infra`](https://github.com/olk/pattern-tei-infra) stack.  This
> stack owns the `pattern-tei-shared` Docker network and exposes the sidecars at
> `http://pattern-tei-embed:8080/v1` (embedder) and `http://pattern-tei-rerank:8080`
> (reranker).  The systemd MCP stack joins that network and reaches them by
> those DNS names.
>
> **Prerequisite — one-time TEI infra setup:**
>
> ```bash
> # Clone the infra stack (if not already on the host)
> git clone https://github.com/olk/pattern-tei-infra.git ~/pattern-tei-infra
>
> # Install and enable the pattern-tei-infra systemd unit
> sudo install -m 644 ~/pattern-tei-infra/pattern-tei-infra.service \
>                 /etc/systemd/system/
> sudo systemctl daemon-reload
> sudo systemctl enable --now pattern-tei-infra.service
> # Wait ~2 min for the TEI sidecars to become healthy
> ```
>
> **Start `blockchain-pattern-mcp.service` only AFTER** `pattern-tei-infra.service`
> is `active (running)`. See
> [`pattern-tei-infra/README.md`](https://github.com/olk/pattern-tei-infra/README.md)
> for full details.

### Prerequisites

- systemd-based Linux host with Docker (`docker compose version`).
- `<user>` is in the `docker` group.
- Both images pre-built locally (`make docker-build-all` from the repo).
- **Shared TEI infra stack installed and enabled** (see tei-infra README).

### Install

```bash
# 0. Install + enable shared TEI infra (once)
sudo install -m 644 {HOME}/pattern-tei-infra/pattern-tei-infra.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now pattern-tei-infra.service

# 1. Build images (once)
make docker-build-all

# 2. Deploy /etc/blockchain-pattern-mcp/
sudo install -d /etc/blockchain-pattern-mcp/config
sudo install -m 644 systemd/docker-compose.yml /etc/blockchain-pattern-mcp/
sudo install -m 644 ~/.config/blockchain-pattern-mcp/config.json /etc/blockchain-pattern-mcp/config/

# 3. Create the .env file (root:docker 640) and edit it.
#     640 root:docker — not 600 root:root — so the systemd service
#     running as User=graemer (a member of the `docker` group) can read this
#     file when docker compose auto-loads it.  The `docker` group is
#     effectively privileged; this is the standard trade-off for non-root
#     systemd services that manage Docker containers.
sudo install -o root -g docker -m 640 /dev/null /etc/blockchain-pattern-mcp/.env
sudo $EDITOR /etc/blockchain-pattern-mcp/.env
# Contents:
#   OPENCODE_API_KEY=sk-...
#   COMPOSE_PROJECT_NAME=bcmcp-systemd
#   MCP_HOST_PORT=8813          # change to avoid port conflicts with other MCP servers

# 4. Install and enable the service.
sudo install -m 644 systemd/blockchain-pattern-mcp.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now blockchain-pattern-mcp.service
```

### Verify

`systemctl status` shows `active (exited)` within seconds, but the MCP
container takes **up to ~2 minutes** to become healthy (embeds 24 slug nodes
through TEI; `start_period: 120s`).
The unit does not wait for healthchecks.

```bash
systemctl status blockchain-pattern-mcp
journalctl -u blockchain-pattern-mcp -n 50
docker compose -p bcmcp-systemd -f /etc/blockchain-pattern-mcp/docker-compose.yml ps
docker inspect -f '{{.State.Health.Status}}' blockchain-pattern-mcp
```

`GET /health` on the HTTP port returns **404 by design** (FastMCP
streamable-http exposes no GET /health); the container healthcheck is a TCP
connect probe on container port 8050 — the server binds only after lifespan
warmup, so connect = fully ready.

### Day-to-day

```bash
sudo systemctl start|stop|restart|reload blockchain-pattern-mcp
journalctl -u blockchain-pattern-mcp -n 200 -f
docker compose -p bcmcp-systemd -f /etc/blockchain-pattern-mcp/docker-compose.yml logs -f
```

### Updating the stack

```bash
make docker-build-all                     # rebuild both images
sudo systemctl reload blockchain-pattern-mcp   # recreate containers
```

### Uninstall

```bash
sudo systemctl disable --now blockchain-pattern-mcp.service
sudo rm /etc/systemd/system/blockchain-pattern-mcp.service
sudo systemctl daemon-reload
sudo rm -rf /etc/blockchain-pattern-mcp
```

For full troubleshooting, networking details, and the coexistence guide, see
`systemd/README.md`.

---

## License

MIT License. See [LICENSE](LICENSE).