blockchain-pattern-mcp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
blockchain-pattern-mcp
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
Related MCP server: agentseed
β‘ Quickstart
# 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-analyzeServer 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 β the non-interactive agent runbook (copy-paste commands, expected outputs, verification probes).
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, needssudo. Uses the sharedpattern-tei-infraTEI 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 below.
π Connect Your Agent
Claude Code
# 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 stdioOr add to your project for the whole team:
claude mcp add --scope project blockchain-pattern \
-e GENERATOR_API_KEY=your_key \
-- blockchain-pattern-mcp --transport stdioOpenCode
OpenCode uses HTTP transport. Start the server first, then configure opencode:
# 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{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"blockchain-pattern": {
"type": "remote",
"url": "http://localhost:8823/mcp"
}
}
}Note:
GENERATOR_API_KEYis read from the server's config file (~/.config/blockchain-pattern-mcp/config.json), not from opencode's environment.
Codex CLI
# Install (one-time)
uv pip install -e .Add to ~/.codex/config.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:
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 troubleshootingInstall 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:
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_blockchainwhen a coding agent will write the implementation itself, the async job trio when the caller wants the design artifact, and one-shotdesign_blockchainonly after raising the server'stimeout(the analyse leg alone takes ~1 minute, evaluation ~3 minutes)How to phrase
requirements,domain, andstyleas separate structured argumentsHow to interpret
final_quality_score,attempts > 1, andevaluation.recommendationsThat
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 JSONAsync 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.errorIn Python (via the MCP HTTP API directly β see examples/blockchain_client_async.py):
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 completedSee examples/blockchain_client_async.py for the complete runnable example (it also exercises cancel_blockchain_design). Run it with:
docker compose -f docker/docker-compose.yml up --build # Terminal 1
make client-async # Terminal 2Explore 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 |
| 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 |
| Generate a design from requirements, style and selected patterns. Long-running (LLM call). Not idempotent. |
| Score an existing design against quality attributes. Long-running (LLM call). Not idempotent. |
| 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. |
| Start a background design job and return a |
| Poll job status. Returns the current status, progress message, and the full design output when |
| Cancel a running job (best-effort; takes effect at the next pipeline stage boundary; may take up to one LLM call). |
| List all 109 patterns; filter by |
| 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 |
| requirements* | Full analyze β generate β evaluate pipeline |
|
| Live catalog discovery with embedded pattern names |
|
| Guide evaluation criteria + finding prioritisation |
| 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 JSONValid 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://andcomponent://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 |
| execution | Externally owned accounts sign with one key, pay gas in ETH, and cannot batch, sponsor, or limit what they⦠|
| wallet | An EOA without ETH cannot call a contract, which excludes users who have not funded a wallet, users on chains⦠|
| execution | A single monotonically increasing |
| execution | A native transaction must be signed by the payer and paid for by the payer in the gas token. |
| wallet | A dApp that needs twenty signatures for twenty actions has two bad options: ask the user to sign every time⦠|
| 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 |
| bridge | A bridge has to move value between two chains that do not share a ledger, and there are exactly two things it can⦠|
| bridge | Chainlink CCIP is a message-passing layer built for sending data and tokens between chains without building⦠|
| bridge | A cross-chain application needs one contract per chain that share state β an omnichain fungible token whose supplyβ¦ |
| bridge | Every bridge has to answer one question: who says the deposit happened on the source chain? |
| bridge | Lock-and-mint is the default bridge shape and the one almost every description of 'bridging' actually means: the⦠|
| bridge | An optimistic rollup lets the base layer accept a state commitment it cannot cheaply check, so it must be able to⦠|
| 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 |
| defi-primitive | A pure algorithmic stablecoin (UST, IRON, Basis Cash, and their descendants) holds no exogenous reserve. |
| defi-primitive | A depositor who must call |
| defi-primitive | A CDP is a per-borrower, independently-addressable debt position: a user locks collateral into a vault and draws a⦠|
| defi-primitive | Yield-bearing wrappers proliferated faster than any interface could standardise: lending markets, aggregators, and⦠|
| defi-primitive | A flash loan lets a borrower take an arbitrary amount of an asset with zero collateral, use it within a single⦠|
| defi-primitive | Frax answered the question pure algorithmic stablecoins (UST, IRON) kept answering badly: can you get capital⦠|
| defi-primitive | A lending market is one shared pool of depositors' liquidity. |
| defi-primitive | An LRT wraps a restaked ETH (or LST) position into a transferable, DeFi-composable token. |
| defi-primitive | Solvency thresholds are the easy half of over-collateralised design: computing a health factor below which a⦠|
| defi-primitive | Native restaking repurposes staked ETH (or an LST) as economic security for services that have nothing to do with⦠|
| defi-primitive | Over-collateralised lending lets a borrower lock volatile collateral and draw a stable or lower-volatility asset⦠|
| defi-primitive | Staking rewards distribute a fixed or rate-limited emission to depositors proportional to their staked balance and⦠|
| defi-primitive | A streaming payment releases tokens to a recipient continuously over time, rather than in one lump at a fixed⦠|
| 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 |
| defi-trading | A bonding curve replaces the LP-and-pool launch with a deterministic pricing function p(s) that maps the amount of⦠|
| defi-trading | The constant-product market maker replaces the order book with a pool that quotes unconditionally. |
| defi-trading | Uniswap v2 spreads each LP's capital uniformly across the entire price range (0, β), which means most of theβ¦ |
| defi-trading | CoW Protocol (formerly Gnosis Protocol, contract GPv2) replaces the AMM's 'first come, first served' curve with a⦠|
| 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⦠|
| defi-trading | The intent/solver pattern inverts who solves the routing problem. |
| defi-trading | An options vault (Ribbon's 'Theta Vault') pools deposits into a single, continuously-run European options-selling⦠|
| defi-trading | A perpetual future has no expiry, so it has no settlement to force it to converge on spot β and withoutβ¦ |
| defi-trading | StableSwap answers a specific problem: x*y=k is the wrong curve for assets that should trade near 1:1. |
| 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 |
| execution | Persistent contract storage is the most expensive thing an EVM contract does: a zero-to-nonzero SSTORE on a cold⦠|
| execution | An |
| execution | A protocol needs thousands of independent, separately-owned instances of the same logic β per-user vaults, per-β¦ |
| execution | Many protocols need an address they can reference before any contract exists there: a state channel's⦠|
| tooling | A protocol that serves twenty chains cannot ship twenty different addresses: every SDK, front-end, bridge UI,β¦ |
| wallet | Raw wallet connection is one of the highest-friction steps in a dApp. |
| execution | Deploying a contract costs gas proportional to its bytecode, and deployed code is immutable. |
| execution | The EVM reads and writes storage one 32-byte word at a time, and the Solidity compiler will pack several⦠|
| 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 |
| governance | A DAO must decide which of dozens of standing spending requests deserve treasury funds, and gathering a fresh⦠|
| governance | On-chain governance needs a way to ask 'how much voting power did this account have at time T?', not 'how many⦠|
| governance | A protocol's parameters are not immutable: interest rates, collateral factors, fees, the contract itself. |
| governance | One-address-one-vote is trivially Sybil-attacked and one-token-one-vote lets whales decide everything, while a⦠|
| governance | A DAO holds pooled capital and makes decisions by vote. |
| governance | On-chain governance costs a transaction per action, which prices out exactly the low-stakes participation that⦠|
| 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 |
| token-standard | A utility token can be permissionless; a security token cannot. |
| 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 |
| data-availability | Rollups work by posting their transaction data to Ethereum so that anyone can re-execute the batch and, in an⦠|
| scaling-l2 | Ethereum executes every transaction on every full node, so cost per transaction rises with congestion and rollups⦠|
| scaling-l2 | Plasma was the first general framework for moving computation off a blockchain while keeping the root chain as the⦠|
| scaling-l2 | A production rollup is not a smart contract. |
| scaling-l2 | A rollup derives its security from the settlement chain: it posts data and proofs there, and L1 enforces⦠|
| scaling-l2 | Rollups amortise cost by batching; channels amortise it by not touching the chain at all. |
| data-availability | A ZK-rollup posts its transaction data to L1 so that anyone can reconstruct the state, prove their balance, and⦠|
| 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 |
| consensus | A public blockchain's environmental footprint is almost entirely a property of how blocks are agreed, not of how⦠|
| mempool | A broadcast transaction is not a submission β it is a bid. |
| mempool | Broadcasting a transaction returns a hash and nothing else. |
mev (3)
Pattern | Layer | What it solves |
| mev | MEV-Boost fixed the proposer side of extraction by inserting a builder auction; MEV-Share fixed the searcher⦠|
| mev | Flashbots Protect protects a user's transaction from frontrunning by routing it privately, but the searcher who⦠|
| 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 |
| nft | Carbon credits live in off-chain registries (Verra, Gold Standard, ACR, Puro) and are unusable by DeFi until they⦠|
| token-standard | Before ERC-2981 every NFT collection and every marketplace invented its own royalty mechanism, so royalties could⦠|
| nft | ERC-721 and ERC-1155 assume a token's metadata is essentially fixed: |
| nft | An NFT is a passive deed: it can be held and transferred, but it cannot hold assets, sign anything, or interact⦠|
| nft | Many NFT designs need the holder β not the contract owner β to be able to destroy their own token: consumableβ¦ |
| nft | ERC-721 gave every unit an owner address, and that single fact is what blocks the composable asset model: a⦠|
| nft | EIP-2981 tells anyone what royalty a token claims, and nothing more. |
oracle (3)
Pattern | Layer | What it solves |
| oracle | A DeFi protocol needs a price, a reserve total or a TWAP, and no single source can be trusted: one exchange can be⦠|
| oracle | A smart contract that needs a model's output β to price a prediction market, gate a carbon credit, score aβ¦ |
| 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 |
| privacy | A contract that computes on secret inputs has no good options on a transparent EVM: store the value encrypted and⦠|
| execution | Groth16's practical dominance came at a price that is easy to forget because it is invisible in the proof object:β¦ |
| privacy | Ethereum is fully transparent: sending to Alice publishes that Alice received it, and any observer can build a⦠|
| execution | A ZK-rollup or a privacy protocol needs the prover to publish a small artefact that lets anyone verify a large⦠|
| 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 |
| security | The Checks-Effects-Interactions pattern organises every statement in a state-changing function into one of three⦠|
| execution | Signing an opaque 32-byte hash is unforgeable but useless: a wallet cannot show the user what they are⦠|
| execution | A token launch, a presale or an airdrop needs to restrict access to a specific list of addresses β but the listβ¦ |
| wallet | An EOA has exactly one key: lose it and the funds are gone; share it and a single compromise drains the account. |
| security | Ownable is the smallest possible privilege model for a smart contract: exactly one address may call a set of⦠|
| execution | A contract that distributes value to many recipients has a choice: push (call out to each recipient during one⦠|
| security | The EVM gives the callee of an external call full control of the remaining gas, and |
| execution | On a public chain, timing is a weapon. |
| wallet | A single key is the weakest link in self-custody: losing it loses everything, and hardware does not prevent a lost⦠|
| execution | EVM arithmetic wraps silently: |
storage (6)
Pattern | Layer | What it solves |
| storage | Arweave solves a problem Ethereum-style chains do not: data written today must still be retrievable in a hundred⦠|
| storage | A legal, journalistic or compliance workflow needs to prove that a specific document, database row, git commit or⦠|
| storage | Off-chain content storage β including the metadata behind essentially every NFT β has no guarantee at all: objectsβ¦ |
| storage | An NFT contract returns |
| storage | A token or contract that needs to reference something larger than a word cannot store it on-chain, so it stores a⦠|
| 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 |
| token-standard | ERC-20 and ERC-721 both force one contract per token type, so a game with thousands of item types pays thousands⦠|
| nft | ERC-721 can tell you who owns a token, but it cannot tell you which tokens exist or which ones an address holds ββ¦ |
| token-standard | You need an asset where every unit is individually distinguishable and individually transferable β a deed to aβ¦ |
| nft | The OpenZeppelin reference ERC-721 writes one ownership slot per minted token, so a 10,000-token mint costs⦠|
| token-standard | Property is a legal claim recorded in a county registry and enforced by courts, not a cryptographic balance. |
| token-standard | Rebasing flips the convention that every yield-bearing token inherits from ERC-20: the balance moves rather than⦠|
| nft | Many collectible and ticketing products need more than one copy of the 'same' thing, and yet not as many as a⦠|
| token-standard | An asset β a share, a bond, a unit of money, a piece of property, a commodity β exists as a record in someβ¦ |
| 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 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 variantConcrete 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)
# Build the image
make docker-build
# Run with your API key
OPENCODE_API_KEY=your_key docker compose -f docker/docker-compose.yml up -dLocal Development (uv)
Prerequisites: Python 3.12+, uv
# 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):
blockchain-pattern-mcp --transport stdioThe 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 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-cpumates for GPU-less hosts) ship a self-built TEI router (v1.9.4 + unmerged PR #884) withWARMUP_TOKENS=0by default β this skips the synthetic warmup pass so containers become ready after weight load only. Override per sidecar viaTEI_WARMUP_TOKENS/TEI_RERANK_WARMUP_TOKENS(positive N warms with N tokens instead; values >MAX_BATCH_TOKENSare 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 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 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):
{
"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). 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 |
|
|
|
|
|
|
|
|
|
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 documentationCustom/OpenAI-compatible endpoints (proxies, vLLM, Ollama, β¦): set
GENERATOR_BASE_URL(generator.config.base_url) β it is passed as the LiteLLMapi_baseGENERATOR_API_KEYis passed as the LiteLLMapi_key;temperature,top_p,top_k, andstreammap to the corresponding LiteLLM parameters
Key environment variables
Variable | Default | Description |
| (required) | API key for your LLM provider (passed to LiteLLM as |
|
| LiteLLM provider prefix: |
|
| API base URL (passed to LiteLLM as |
|
| Model name; final model string is |
|
| Sampling temperature |
|
| Top-p sampling |
|
| Top-k sampling |
|
| Enable streaming responses |
|
| Embedder provider |
|
| TEI embedder URL |
|
| Embedding batch size |
| (empty) | Query instruction prefix |
| (empty) | Text instruction prefix |
| image: | Dense-leg snapshot path: reloaded on restart (zero corpus re-embedding), rebuilt on any embedder/corpus/probe change. |
|
| BM25 stage-1 recall cap (0=full corpus) |
|
| Dense stage-1 recall cap (0=full corpus) |
|
| Stage-1 fusion leg weight on the dense leg. Pairs with |
|
| Stage-1 fusion leg weight on the BM25 leg. See |
|
| Number of patterns to select |
|
| 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. |
|
| Rerank top N (slug-cut after CE) |
|
| Use lean response schema |
|
| Min analysis score for style recommendation |
|
| Server-side reasoning MCP integration β opt-in, off by default (see Structured Reasoning) |
|
| Subprocess spawn timeout per reasoning tool |
|
| Per-thought tool-call timeout |
|
| Hard cap on reasoning steps per phase |
|
| Silence reasoning-subprocess stderr (ASCII progress boxes, |
|
| Fail server startup when a reasoning tool is unreachable |
| (embedded) | JSON list command for shannonthinking (e.g. |
| (embedded) | JSON list command for code-reasoning |
|
| Weight on analysis score in blend |
|
| Weight on fusion score in blend |
|
| Weight smoothing alpha |
|
| 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 |
|
| Log phase timings at INFO level |
|
| Max design loop attempts |
|
| Early-stop quality threshold |
| (default reranker URL) | TEI reranker endpoint (host:port); model is fixed to |
|
| Reranker timeout (seconds) |
|
| 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 files directory (the image bakes the 109-pattern catalogue there) |
|
| SQLite path for async job trio. Override for test isolation |
|
| Emit progress notifications during long tool calls |
|
| Heartbeat interval in seconds (keep below client idle timeout) |
|
| Max self-healing retry attempts |
|
| Retry on validation failure |
|
| Transport mode: |
|
| HTTP bind host |
|
| HTTP bind port |
|
| Logging level |
|
| Logging format: |
|
| 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/cacheon the host stays empty by design. Inspect without sudo:docker exec <container> ls /var/cache/blockchain-pattern-mcp/embedding-index, ordocker 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 anddocker compose down. Reset it withdocker compose down -vordocker volume rm <name>; a baredocker runneeds-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.
CLI flags
Flag | Description |
| Override transport mode |
| Override HTTP bind host (default: 0.0.0.0) |
| Override HTTP port (default: 8050) |
| Path to config file |
| 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 and/or
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-mcpsstage 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 vianode(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=trueto 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.
export REASONING_ENABLED=true # enable the reasoning MCP integration
export REASONING_FAIL_FAST=true # refuse to start with broken MCPsLocal (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):
{
"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.
# 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 callBoth 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
Check the agent's MCP connection: Claude Code
/mcp, OpenCodeopencode mcp list, Codexcodex mcp listVerify the server process started: compose logs should show
MCPBlockchainServer initializedConfirm the TEI embedder is healthy:
curl http://127.0.0.1:8080/healthinside the container
"Connection refused" or timeout errors
The server waits for the TEI embedder to become healthy:
docker compose -f docker/docker-compose.yml logs pattern-tei-embedLLM provider errors (502 / 401)
Confirm
GENERATOR_API_KEYis set and not expiredVerify
GENERATOR_BASE_URLmatches your provider's endpointIf using a proxy, check reachability from inside the container
Pattern JSON files not loading
Files must have
.jsonextensionRequired fields: the full required list in Extending with Custom Patterns
Validate against
docs/pattern-schema.json(or runmake verify-patterns)
Building & Development
Common make targets (full reference: docs/make_rules.md):
Target | Description |
| Install package in editable mode with dev dependencies |
| Run ruff linting |
| Run mypy --strict type checking on src/ |
| Run every check-* quality gate (lint, types, dead code, deps) |
| Run unit tests with uv (tests/unit/) |
| Run the analyze-only MCP client demo (requires server running) |
| Run the synchronous design_blockchain client demo (long-running; requires server running) |
| Build the MCP server Docker image |
| Build MCP server + GPU TEI pair + CPU TEI pair |
| Push image to Docker Hub + GHCR (version + latest) |
| Build and start all services (CUDA pair, needs an NVIDIA GPU) |
| Build and start all services on the CPU pair (no GPU needed) |
| Stop all services |
Development workflow:
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 # StopPublishing
All three images are published to two registries simultaneously:
Image | Docker Hub | GHCR | Tags |
MCP server |
|
|
|
TEI embedder |
|
|
|
TEI reranker |
|
|
|
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 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)
# 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.ioOn 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 |
|
TEI embedder |
|
TEI reranker |
|
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 |
| The systemd unit |
| Production compose variant (no |
| CPU lane overlay for GPU-less TEI infra hosts (see |
| 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-embedembedder andpattern-tei-rerankreranker containers live in the sharedpattern-tei-infrastack. This stack owns thepattern-tei-sharedDocker network and exposes the sidecars athttp://pattern-tei-embed:8080/v1(embedder) andhttp://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:
# 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 healthyStart
blockchain-pattern-mcp.serviceonly AFTERpattern-tei-infra.serviceisactive (running). Seepattern-tei-infra/README.mdfor full details.
Prerequisites
systemd-based Linux host with Docker (
docker compose version).<user>is in thedockergroup.Both images pre-built locally (
make docker-build-allfrom the repo).Shared TEI infra stack installed and enabled (see tei-infra README).
Install
# 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.serviceVerify
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.
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-mcpGET /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
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 -fUpdating the stack
make docker-build-all # rebuild both images
sudo systemctl reload blockchain-pattern-mcp # recreate containersUninstall
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-mcpFor full troubleshooting, networking details, and the coexistence guide, see
systemd/README.md.
License
MIT License. See LICENSE.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
This server cannot be deployed
Maintenance
Related MCP Connectors
AI Design Blueprint is a doctrine and runtime standard for agentic AI: 10 principles, 16 laws, and Pro/Teams validators your coding agent calls over MCP.
A design director for coding agents: it picks, validates and refuses before you build.
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
AI Agent with Architectural Memory. Impact analysis (free), tests and code from the graph (pro).
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceProvides architecture design expertise to AI coding agents, analyzing requirements, selecting architecture patterns, generating concrete designs, and evaluating quality attributes.1MIT
- AlicenseNot gradedqualityAmaintenanceEnables AI coding agents to enforce spec-driven development and verify code before it is marked done, using six tools that catch invented APIs, scan for hallucinated content, check plugin conformance, sandbox-run tests, validate schemas, and record audit evidence.771 npm8PolyForm Noncommercial 1.0.0
- AlicenseAqualityDmaintenanceEnables AI coding agents to make evidence-aware design-pattern decisions by analyzing cases, comparing options, detecting misuse, stress-testing assumptions, planning adoption, writing ADRs, and generating evidence plans with transparent scoring.83MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to design, analyze, and evaluate agent system designs against a curated catalog of agent patterns, with retrieval, scoring, and refinement workflows.MIT