Skip to content
Merged
14 changes: 8 additions & 6 deletions .claude/skills/baba-credits/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ name: baba-credits
description: |
Use when the user wants to interact with the Credits blockchain via the
baba-credits MCP server — sending CS transfers, deploying/calling Java
smart contracts, querying balances, transactions, tokens, attaching
userFields metadata (ArtVerse-style), or running node diagnostics.
smart contracts, querying balances, transactions, tokens, inscribing
ordinals-style on-chain metadata via userFields v1, or running node
diagnostics.
Triggers when the user mentions: Credits, CS coin, $CS, baba-credits,
Credits wallet, BABA Wallet, smart contract on Credits, ArtVerse mint.
Credits wallet, BABA Wallet, smart contract on Credits, on-chain
ordinal/inscription, userFields metadata.
---

# baba-credits
Expand Down Expand Up @@ -38,7 +40,7 @@ For read-only inspection just call the corresponding `*_get_*`, `*_info`,
- "Send N CS from A to B" → recipe `transfer-cs.md`
- "Deploy this Java contract" → recipe `deploy-contract.md`
- "Call method `x` on contract C" → recipe `execute-method.md`
- "Mint an ArtVerse asset" → recipe `attach-metadata.md` + `transfer-cs.md`
- "Inscribe an ordinal" / "Attach metadata to a tx" / "Mint an on-chain asset" → recipe `attach-metadata.md` + `transfer-cs.md`
- "Show me details of the network" → `diag_*`
- "Wait until the next block" → `monitor_wait_for_block` (long-poll)

Expand Down Expand Up @@ -77,7 +79,7 @@ See `tools-reference.md` for the full catalog (29 tools, 6 categories).
|---|---|---|
| `monitor_*` | 6 | balance, history, fee estimation, long-poll waits |
| `transaction_*` | 4 | get/pack/execute/result for plain CS transfers |
| `userfields_*` | 2 | encode/decode of v1 metadata blobs (ArtVerse) |
| `userfields_*` | 2 | encode/decode of v1 on-chain metadata blobs (ordinals-style inscription) |
| `tokens_*` | 5 | balances, transfers, info, holders, transactions |
| `smartcontract_*` | 8 | compile, pack, deploy, execute, get, methods, state, list |
| `diag_*` | 4 | active nodes, mempool count, node info, supply |
Expand All @@ -88,7 +90,7 @@ See `tools-reference.md` for the full catalog (29 tools, 6 categories).
- `recipes/deploy-contract.md` — Java contract on-chain
- `recipes/execute-method.md` — call a method on a deployed contract
- `recipes/inspect-wallet.md` — read-only exploration
- `recipes/attach-metadata.md` — userFields v1 (ArtVerse minting)
- `recipes/attach-metadata.md` — userFields v1 ordinals-style on-chain inscription
- `recipes/token-operations.md` — token info / balances / transfers / holders

## Client-side signing
Expand Down
9 changes: 5 additions & 4 deletions .claude/skills/baba-credits/recipes/attach-metadata.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# Recipe: attach userFields v1 metadata to a transaction (ArtVerse)
# Recipe: inscribe ordinals-style metadata on a transaction (`userFields` v1)

## When to use
The user wants to anchor an off-chain asset (image, video, document) to a
Credits transaction with verifiable metadata: SHA-256 hash, IPFS CID, MIME
type, size. Typical use case: ArtVerse minting — a transfer that doubles as
a "proof of authorship" record.
Credits transaction with verifiable, structured metadata: SHA-256 hash,
IPFS CID, MIME type, size. Typical use cases: on-chain inscription /
"ordinal" minting — a transfer that doubles as a proof-of-authorship record
or a content-addressable asset registry.

## Prerequisites
- The asset itself, hashed with SHA-256 (32 bytes, hex-encoded).
Expand Down
11 changes: 6 additions & 5 deletions .claude/skills/baba-credits/tools-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,9 @@ transaction (executionTime, returnValue Variant, status).

## userfields_*

Pure codec for the userFields v1 blob format used by ArtVerse and similar
metadata-on-chain use cases. Both tools are read-only / idempotent — they
never write on-chain.
Pure codec for the userFields v1 blob format used to inscribe ordinals-style
on-chain metadata (digest + IPFS CID + mime + size) onto a Credits transaction.
Both tools are read-only / idempotent — they never write on-chain.

### `userfields_encode`
**Endpoint:** `POST /api/UserFields/Encode` **Annotations:** read-only, idempotent
Expand All @@ -326,8 +326,9 @@ never write on-chain.
}
```

**When to use:** Build the base58 `UserData` blob to attach metadata to a
`transaction_pack`/`transaction_execute` call (ArtVerse mint).
**When to use:** Build the base58 `UserData` blob to attach ordinals-style
on-chain metadata to a `transaction_pack`/`transaction_execute` call
(asset inscription).

---

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ __pycache__/
.env
.env.local
.env.smoke
.env.mcp
*.smoke.log
*.egg-info/
gen-py/
Expand Down
112 changes: 106 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ dashboards) with a raw Credits Node (Thrift/TCP). Built for the
upstream review surface stays small
- ⛓ **Smart Contract pipeline** — Compile → Pack → sign offline → Deploy/Execute,
with on-chain validation against mainnet
- 🪪 **ArtVerse `userFields` v1** — typed metadata codec with stable wire format
- 🪪 **Ordinals-style `userFields` v1** — typed on-chain metadata codec with a stable wire format for inscription workflows (digest + IPFS CID + mime + size)

---

Expand All @@ -51,7 +51,7 @@ routes/
monitor_wait.py # /Monitor/WaitForBlock|WaitForSmartTransaction, /Transaction/Result
smartcontract.py # /SmartContract/Compile|Get|Methods|State|ListByWallet|Pack|Deploy|Execute
services/
userfields.py # ArtVerse v1 codec (encode/decode)
userfields.py # Ordinals-style v1 metadata codec (encode/decode)
monitor.py # WaitForBlock / TransactionResult mappers + Variant decoder
tokens.py # Token mappers
diag.py # API_DIAG mappers
Expand Down Expand Up @@ -241,7 +241,7 @@ bytecode travels as **base64** (consistent with `SmartContractCompile`).
`WAIT_MAX_TIMEOUT_MS` from the environment (default 120s). The socket waits
5s longer than the requested wait so the node can complete in-flight work.

### UserFields v1 codec (ArtVerse, local)
### UserFields v1 codec (ordinals-style on-chain metadata, local)

| Method | Endpoint |
|---|---|
Expand Down Expand Up @@ -346,7 +346,7 @@ curl -X POST http://localhost:5000/api/Monitor/WaitForBlock \
-H "Content-Type: application/json" \
-d '{"timeoutMs": 30000}'

# Encode an ArtVerse userFields v1 payload
# Encode an ordinals-style userFields v1 payload (on-chain inscription)
curl -X POST http://localhost:5000/api/UserFields/Encode \
-H "Content-Type: application/json" \
-d '{
Expand Down Expand Up @@ -450,6 +450,62 @@ The MCP server is a thin Python wrapper sitting on top of this gateway. It is
**non-custodial**: it never holds private keys. The signing pipeline is
`Pack → ed25519 sign (client-side) → Execute → Wait`.

### 📲 Connect from Claude (mobile, desktop, or web) in 30 seconds

If a public **`baba-credits`** MCP is already running and you just want to plug
your Claude client into it:

**You'll need from the operator:**
- ① a **URL**, e.g. `https://mcp.example.com/sse`
- ② a **Bearer token** (a long random string, treat it like a password)

**On Claude Desktop / Claude Code (any OS):** drop this into your config
(`claude_desktop_config.json` on desktop, `.mcp.json` at the repo root for
Claude Code). Replace the two placeholders:

```json
{
"mcpServers": {
"baba-credits": {
"url": "https://mcp.example.com/sse",
"headers": {
"Authorization": "Bearer PASTE-YOUR-TOKEN-HERE"
}
}
}
}
```

Restart Claude. The 29 tools (`monitor_get_balance`, `transaction_pack`,
`smartcontract_deploy`, …) appear in the MCP picker. Try
*"What's the CS balance of wallet `<your address>`?"* to confirm.

**On Claude.ai (web app, including the iOS / Android browser):** Settings →
**Connectors** → **Add custom connector** → paste the same URL and token.
Save. Open a new chat, the connector toggles on the prompt bar.

**One-tap link** (some clients support `mcp+sse://` URI scheme):

```
mcp+sse://[email protected]/sse
```

Treat the URL above as plain Markdown — copy it, replace the token, and your
client (if it supports the scheme) will pre-fill the connector dialog.

> **Self-signed cert?** If the operator hasn't installed a Let's Encrypt
> certificate, the URL likely uses an IP and a self-signed cert. Many mobile
> apps will refuse it. Either ask the operator to add a real domain + TLS, or
> manually trust the cert on your device (iOS: install via Profile, then
> *Settings → General → About → Certificate Trust Settings*; Android:
> *Settings → Security → Encryption & credentials → Install certificate*).

> **Want to host your own?** Keep reading — the rest of this section walks
> you through running the server, signing transactions, and securing the
> endpoint.

---

### Quick start (bundled with the gateway via pm2)

```bash
Expand All @@ -460,6 +516,50 @@ pm2 start ecosystem.config.js && pm2 save
# baba-mcp-http on :7000 (MCP SSE)
```

### Quick start (cross-platform launch script)

The fastest way to bring the MCP server up — picks the right Python, creates
the virtualenv, installs deps if missing, validates the gateway, and starts
`python -m baba_mcp.server`:

| Platform | Command |
|---|---|
| Linux / macOS | `bash scripts/launch-mcp.sh` |
| Windows (PowerShell) | `powershell -ExecutionPolicy Bypass -File scripts\launch-mcp.ps1` |

Both scripts perform the same six steps and stream coloured ✓/⚠/✗ progress:

1. Locate a **Python ≥ 3.10** interpreter (`mcp` SDK requires it). Probes
`python3.13 → python3.10`, then `py -3.x` on Windows.
2. Create or reuse `.venv/` next to the repo.
3. Install (or reinstall) `mcp`, `httpx`, `pydantic` from
`requirements.txt` if not yet present in the venv.
4. Load `.env.mcp` (`BABA_GATEWAY_URL`, `MCP_TRANSPORT`,
`MCP_AUTH_TOKEN`, …) when present.
5. Health-check the gateway with a single read-only POST to
`/api/Diag/GetSupply`. Aborts (exit 2) if unreachable, unless you pass
`SKIP_GATEWAY_CHECK=1`.
6. `exec`s `python -m baba_mcp.server`, forwarding signals and exit code.

Useful flags (same on both scripts):

```bash
bash scripts/launch-mcp.sh --no-pip # skip the dep check (faster relaunch)
bash scripts/launch-mcp.sh --reinstall # force pip reinstall
SKIP_GATEWAY_CHECK=1 bash scripts/launch-mcp.sh # bypass health-check
MCP_TRANSPORT=http bash scripts/launch-mcp.sh # HTTP/SSE instead of stdio
```

```powershell
.\scripts\launch-mcp.ps1 -NoPip
.\scripts\launch-mcp.ps1 -Reinstall
.\scripts\launch-mcp.ps1 -SkipGatewayCheck
$env:MCP_TRANSPORT = 'http'; .\scripts\launch-mcp.ps1
```

Full configuration reference (env vars, `.mcp.json`, signing material) is
below.

### Configure an agent

The MCP server exposes 29 tools (1:1 with the gateway REST endpoints) and
Expand Down Expand Up @@ -624,7 +724,7 @@ implemented tool end-to-end against a live node (run with
|---|---|---|
| `monitor_*` | 6 | balance, history, fee estimation, long-poll waits |
| `transaction_*` | 4 | get/pack/execute/result for plain CS transfers |
| `userfields_*` | 2 | encode/decode of v1 metadata blobs (ArtVerse) |
| `userfields_*` | 2 | encode/decode of v1 on-chain metadata blobs (ordinals-style inscription) |
| `tokens_*` | 5 | balances, transfers, info, holders, transactions |
| `smartcontract_*` | 8 | compile, pack, deploy, execute, get, methods, state, list |
| `diag_*` | 4 | active nodes, mempool count, node info, supply |
Expand Down Expand Up @@ -685,7 +785,7 @@ MIT License
- Designed for high-uptime blockchain infrastructure
- Safe against common Credits Node crashes (defensive Thrift accessors,
fallback for renamed/optional fields)
- Optimized for mobile wallet backends and ArtVerse content workflows
- Optimized for mobile wallet backends and ordinals-style on-chain content workflows

💡 If this project helps you build on the Credits Blockchain, consider
starring the repo!
67 changes: 65 additions & 2 deletions baba_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,14 @@ async def _run_stdio(server: Server) -> None:
await server.run(read, write, server.create_initialization_options())


async def _run_http(server: Server, host: str, port: int) -> None:
async def _run_http(server: Server, host: str, port: int,
auth_token: Optional[str] = None,
whitelist_ips: Optional[list[str]] = None) -> None:
from mcp.server.sse import SseServerTransport
import uvicorn
from starlette.applications import Starlette
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Mount

sse = SseServerTransport("/messages/")
Expand All @@ -113,10 +117,67 @@ async def handle_sse(request):
async with sse.connect_sse(request.scope, request.receive, request._send) as (r, w):
await server.run(r, w, server.create_initialization_options())

class AuthMiddleware(BaseHTTPMiddleware):
"""Optional Bearer-token + IP allowlist gate on /sse and /messages/.

Active only when ``auth_token`` is set or ``whitelist_ips`` is non-default.
Returns 401 on missing/wrong token, 403 on disallowed IP.
"""
async def dispatch(self, request, call_next):
client_ip = (request.client.host if request.client else None) or "unknown"
if whitelist_ips and "0.0.0.0/0" not in whitelist_ips:
if client_ip not in whitelist_ips:
return PlainTextResponse(
f"403 Forbidden: client {client_ip} not in MCP_WHITELIST_IPS",
status_code=403,
)
if auth_token:
header = request.headers.get("authorization", "")
expected = f"Bearer {auth_token}"
if header != expected:
return PlainTextResponse(
"401 Unauthorized: missing or invalid Bearer token",
status_code=401,
)
return await call_next(request)

class SseNoBufferMiddleware(BaseHTTPMiddleware):
"""Force reverse proxies / tunnels (Cloudflare, Nginx, Envoy, …) not
to buffer the SSE response.

SSE relies on the server flushing the first ``event:`` frame to the
client immediately so the MCP handshake can start. When the response
is hidden behind a buffering intermediary the first bytes are held
until the stream closes (or a buffer threshold is reached), which
looks like a 30s hang from the client's side.

Setting ``X-Accel-Buffering: no`` is the documented opt-out for
Nginx and is honoured by Cloudflare Tunnel and a few other proxies.
``Cache-Control: no-cache`` and ``Connection: keep-alive`` are
belt-and-braces hints for the same purpose.

Only applied to ``/sse`` so the JSON ``/messages/`` posts are
unaffected.
"""
async def dispatch(self, request, call_next):
response = await call_next(request)
if request.url.path == "/sse":
response.headers["X-Accel-Buffering"] = "no"
response.headers["Cache-Control"] = "no-cache"
response.headers["Connection"] = "keep-alive"
return response

app = Starlette(routes=[
Route("/sse", handle_sse),
Mount("/messages/", app=sse.handle_post_message),
])
# Order matters: middlewares wrap the app inside-out (last added is
# outermost). Add SseNoBuffer first so it runs *closer* to the route,
# then auth on the outside so unauthorised requests never reach the SSE
# path at all.
app.add_middleware(SseNoBufferMiddleware)
if auth_token or (whitelist_ips and "0.0.0.0/0" not in whitelist_ips):
app.add_middleware(AuthMiddleware)
config = uvicorn.Config(app, host=host, port=port, log_level="info")
await uvicorn.Server(config).serve()

Expand All @@ -134,7 +195,9 @@ def main() -> None:
"MCP exposed on %s without MCP_AUTH_TOKEN — strongly recommended for production",
cfg.http_host,
)
asyncio.run(_run_http(server, cfg.http_host, cfg.http_port))
asyncio.run(_run_http(server, cfg.http_host, cfg.http_port,
auth_token=cfg.auth_token,
whitelist_ips=cfg.whitelist_ips))
else:
raise SystemExit(f"Unknown MCP_TRANSPORT={cfg.transport!r}")

Expand Down
17 changes: 17 additions & 0 deletions baba_mcp/tools/smartcontract.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ class SmartContractPackInput(_Base):
description="Variant list for execute method args")
fee_as_string: str = Field(alias="feeAsString", default="0")
user_data: str = Field(alias="UserData", default="")
forget_new_state: Optional[bool] = Field(alias="forgetNewState", default=None,
description=(
"execute-only: when True the executor runs the method but the "
"resulting state is dropped. Use for read-only getters that need "
"the return value populated. The same value MUST be re-passed to "
"smartcontract_execute, otherwise the canonical signing payload "
"differs and the node rejects the signature."
))

async def _pack_impl(client, inp):
return await call_gateway(client, "/api/SmartContract/Pack", inp)
Expand Down Expand Up @@ -60,6 +68,15 @@ class SmartContractExecuteInput(_Base):
transaction_inner_id: int = Field(alias="transactionInnerId", ge=1)
fee_as_string: str = Field(alias="feeAsString", default="0")
user_data: str = Field(alias="UserData", default="")
forget_new_state: bool = Field(alias="forgetNewState", default=False,
description=(
"When True, the executor runs the method but the resulting state "
"(and any persistent side-effect) is dropped. Use for read-only "
"getters where you want the return value without paying for state "
"persistence. The on-chain transaction is still sealed and fee "
"is still consumed. Required by some Credits node versions to "
"actually populate `smartContractResult` in the response."
))

async def _execute_impl(client, inp):
return await call_gateway(client, "/api/SmartContract/Execute", inp)
Expand Down
7 changes: 6 additions & 1 deletion gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -742,4 +742,9 @@ def execute():


if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
# Behind a reverse proxy (Nginx + TLS) bind to 127.0.0.1 by exporting
# GATEWAY_HOST=127.0.0.1 in .env. Default keeps the historical
# 0.0.0.0:5000 behaviour for direct deployments.
bind_host = os.getenv('GATEWAY_HOST', '0.0.0.0')
bind_port = int(os.getenv('GATEWAY_PORT', '5000'))
app.run(host=bind_host, port=bind_port)
Loading
Loading