diff --git a/.claude/skills/baba-credits/SKILL.md b/.claude/skills/baba-credits/SKILL.md index 9530fcf..21175fa 100644 --- a/.claude/skills/baba-credits/SKILL.md +++ b/.claude/skills/baba-credits/SKILL.md @@ -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 @@ -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) @@ -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 | @@ -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 diff --git a/.claude/skills/baba-credits/recipes/attach-metadata.md b/.claude/skills/baba-credits/recipes/attach-metadata.md index 93b1cfd..84a2543 100644 --- a/.claude/skills/baba-credits/recipes/attach-metadata.md +++ b/.claude/skills/baba-credits/recipes/attach-metadata.md @@ -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). diff --git a/.claude/skills/baba-credits/tools-reference.md b/.claude/skills/baba-credits/tools-reference.md index a933ad9..256b7c3 100644 --- a/.claude/skills/baba-credits/tools-reference.md +++ b/.claude/skills/baba-credits/tools-reference.md @@ -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 @@ -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). --- diff --git a/.gitignore b/.gitignore index 9305cf7..f65d125 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ __pycache__/ .env .env.local .env.smoke +.env.mcp *.smoke.log *.egg-info/ gen-py/ diff --git a/README.md b/README.md index 7be3d1c..9c3dc48 100644 --- a/README.md +++ b/README.md @@ -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) --- @@ -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 @@ -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 | |---|---| @@ -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 '{ @@ -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 ``?"* 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://PASTE-YOUR-TOKEN-HERE@mcp.example.com/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 @@ -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 @@ -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 | @@ -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! diff --git a/baba_mcp/server.py b/baba_mcp/server.py index 1447ada..276fd16 100644 --- a/baba_mcp/server.py +++ b/baba_mcp/server.py @@ -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/") @@ -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() @@ -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}") diff --git a/baba_mcp/tools/smartcontract.py b/baba_mcp/tools/smartcontract.py index ea6e192..9ed03ba 100644 --- a/baba_mcp/tools/smartcontract.py +++ b/baba_mcp/tools/smartcontract.py @@ -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) @@ -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) diff --git a/gateway.py b/gateway.py index e50402c..854ea91 100644 --- a/gateway.py +++ b/gateway.py @@ -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) diff --git a/routes/smartcontract.py b/routes/smartcontract.py index 09b66a2..8150032 100644 --- a/routes/smartcontract.py +++ b/routes/smartcontract.py @@ -23,6 +23,7 @@ from flask import Blueprint, jsonify, request from services import contracts as _contracts +from services.monitor import _variant_to_python def _poll_sealed_tx_by_inner_id(get_node_client, source_bytes, inner_id, *, @@ -136,11 +137,17 @@ def _execute_smart_tx(tx, rec_fee, inner_id, amount_str="0"): f"{getattr(tx_id, 'poolSeq', 0)}.{getattr(tx_id, 'index', 0) + 1}" if tx_id and hasattr(tx_id, "poolSeq") else None ) + # smart_contract_result is a Thrift Variant (general.Variant + # wrapping the contract method's return value, e.g. v_string + # for getSymbol(), v_boolean for transfer(), etc.). Decode it + # so the client receives a plain JSON value instead of an + # opaque Thrift object that jsonify can't introspect. + scr = _variant_to_python(getattr(res, "smart_contract_result", None)) return jsonify({ "amount": full_decimal(amount_str), "dataResponse": { "actualSum": 0, "publicKey": None, "recommendedFee": float(rec_fee), - "smartContractResult": getattr(res, "smart_contract_result", None), + "smartContractResult": scr, "transactionPackagedStr": None, }, "actualSum": full_decimal(getattr(res, "sum", amount_str)), @@ -163,11 +170,26 @@ def _execute_smart_tx(tx, rec_fee, inner_id, amount_str="0"): if sealed_tx_id: log(f"SmartContract recovered: tx {sealed_tx_id} sealed for inner_id={inner_id}", is_error=False) + # Best-effort: fetch the smart_contract_result via TransactionResultGet + # so the client gets the same shape as the happy-path response. + scr = None + try: + client_r, transport_r = get_node_client() + if client_r: + try: + rres = client_r.TransactionResultGet(int(inner_id)) + scr = _variant_to_python(getattr(rres, "smart_contract_result", None)) + finally: + if transport_r and transport_r.isOpen(): + transport_r.close() + except Exception as e: + log(f"SmartContract recovery: TransactionResultGet failed: {type(e).__name__}: {e!r}", + is_error=False) return jsonify({ "amount": full_decimal(amount_str), "dataResponse": { "actualSum": 0, "publicKey": None, "recommendedFee": float(rec_fee), - "smartContractResult": None, "transactionPackagedStr": None, + "smartContractResult": scr, "transactionPackagedStr": None, }, "actualSum": full_decimal(amount_str), "actualFee": full_decimal(rec_fee), diff --git a/scripts/launch-mcp.ps1 b/scripts/launch-mcp.ps1 new file mode 100644 index 0000000..d41e66e --- /dev/null +++ b/scripts/launch-mcp.ps1 @@ -0,0 +1,191 @@ +<# +.SYNOPSIS + Bootstrap and start the baba-credits MCP server (Windows / PowerShell 5.1+). + +.DESCRIPTION + 1. Finds a Python >= 3.10 interpreter (mcp SDK requires it). + 2. Creates a local virtualenv at \.venv if missing. + 3. Installs the three MCP runtime deps (mcp, httpx, pydantic) if missing. + 4. Loads \.env.mcp if present. + 5. Health-checks the gateway URL. + 6. Launches `python -m baba_mcp.server` and exits with its code. + +.PARAMETER NoPip + Skip the dependency check (faster relaunch when you know deps are installed). + +.PARAMETER Reinstall + Force reinstall of MCP deps even if already present. + +.PARAMETER SkipGatewayCheck + Skip the gateway health-check before launching. + +.EXAMPLE + .\scripts\launch-mcp.ps1 + +.EXAMPLE + $env:MCP_TRANSPORT = 'http'; .\scripts\launch-mcp.ps1 + +.EXAMPLE + .\scripts\launch-mcp.ps1 -Reinstall + +.NOTES + Exit codes: + 0 — server exited cleanly (e.g. Ctrl-C) + 1 — bootstrap failure + 2 — gateway health-check failed +#> +[CmdletBinding()] +param( + [switch]$NoPip, + [switch]$Reinstall, + [switch]$SkipGatewayCheck +) + +$ErrorActionPreference = 'Stop' + +# ----- Paths -------------------------------------------------------------- +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$RepoRoot = (Resolve-Path (Join-Path $ScriptDir '..')).Path +$VenvDir = Join-Path $RepoRoot '.venv' +$VenvPy = Join-Path $VenvDir 'Scripts\python.exe' +$EnvFile = Join-Path $RepoRoot '.env.mcp' + +# ----- Helpers ------------------------------------------------------------ +function Ok($msg) { Write-Host ("[OK] " + $msg) -ForegroundColor Green } +function Warn($msg) { Write-Host ("[WARN] " + $msg) -ForegroundColor Yellow } +function Fail($msg) { Write-Host ("[FAIL] " + $msg) -ForegroundColor Red; exit 1 } +function Step($msg) { Write-Host ""; Write-Host $msg -ForegroundColor Cyan } + +function Test-PythonOk($exe) { + try { + $ver = & $exe -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>$null + if (-not $ver) { return $false } + $parts = $ver -split '\.' + $major = [int]$parts[0]; $minor = [int]$parts[1] + return ($major -gt 3) -or ($major -eq 3 -and $minor -ge 10) + } catch { return $false } +} + +# ----- 1. Find Python >= 3.10 --------------------------------------------- +Step "1. Locating a Python >= 3.10 interpreter" +$PyBin = $null +$candidates = @('py', 'python', 'python3') +# `py -3.x` launcher is the recommended way on Windows +$pyLauncher = $null +if (Get-Command py -ErrorAction SilentlyContinue) { + foreach ($v in @('-3.13', '-3.12', '-3.11', '-3.10')) { + $exe = & py $v -c 'import sys; print(sys.executable)' 2>$null + if ($LASTEXITCODE -eq 0 -and $exe) { + if (Test-PythonOk $exe) { $PyBin = $exe; break } + } + } +} +if (-not $PyBin) { + foreach ($cand in $candidates) { + if (Get-Command $cand -ErrorAction SilentlyContinue) { + $exe = (Get-Command $cand).Source + if (Test-PythonOk $exe) { $PyBin = $exe; break } + } + } +} +if (-not $PyBin) { + Write-Host "[FAIL] No Python >= 3.10 found in PATH." -ForegroundColor Red + Write-Host " Install from https://www.python.org/downloads/ (3.11+ recommended)" -ForegroundColor Red + Write-Host " or run: winget install Python.Python.3.11" -ForegroundColor Red + exit 1 +} +$ver = & $PyBin -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])' +Ok "Found $PyBin (Python $ver)" + +# ----- 2. Create / reuse virtualenv --------------------------------------- +Step "2. Setting up virtualenv at $VenvDir" +$needNewVenv = $true +if (Test-Path $VenvPy) { + if (Test-PythonOk $VenvPy) { + $vver = & $VenvPy -c 'import sys; print("%d.%d" % sys.version_info[:2])' + Ok "Reusing existing venv (Python $vver)" + $needNewVenv = $false + } else { + Warn "Existing venv too old, recreating" + Remove-Item -Recurse -Force $VenvDir + } +} +if ($needNewVenv) { + & $PyBin -m venv $VenvDir + if ($LASTEXITCODE -ne 0) { Fail "Failed to create venv" } + Ok "Venv created" +} + +# ----- 3. Install MCP deps ------------------------------------------------ +Step "3. Verifying MCP dependencies" +$needInstall = $Reinstall.IsPresent +if (-not $Reinstall.IsPresent -and -not $NoPip.IsPresent) { + & $VenvPy -c 'import mcp, httpx, pydantic' 2>$null + if ($LASTEXITCODE -ne 0) { $needInstall = $true } +} +if ($needInstall -and -not $NoPip.IsPresent) { + & $VenvPy -m pip install --upgrade pip | Out-Null + $reqFile = Join-Path $RepoRoot 'requirements.txt' + if (Test-Path $reqFile) { + & $VenvPy -m pip install -r $reqFile + } else { + & $VenvPy -m pip install 'mcp>=1.0.0' 'httpx>=0.27.0' 'pydantic>=2.5.0' + } + if ($LASTEXITCODE -ne 0) { Fail "pip install failed" } + Ok "Dependencies installed" +} else { + Ok "All deps already present (use -Reinstall to force)" +} + +# ----- 4. Load .env.mcp --------------------------------------------------- +Step "4. Loading environment" +if (Test-Path $EnvFile) { + Get-Content $EnvFile | ForEach-Object { + $line = $_.Trim() + if ($line -and -not $line.StartsWith('#') -and $line -match '^([^=]+)=(.*)$') { + $k = $Matches[1].Trim() + $v = $Matches[2].Trim().Trim('"').Trim("'") + [Environment]::SetEnvironmentVariable($k, $v, 'Process') + } + } + Ok "Loaded $EnvFile" +} else { + Warn "$EnvFile not found — using defaults / shell env vars only" +} +if (-not $env:BABA_GATEWAY_URL) { $env:BABA_GATEWAY_URL = 'http://127.0.0.1:5000' } +if (-not $env:MCP_TRANSPORT) { $env:MCP_TRANSPORT = 'stdio' } +if (-not $env:MCP_HTTP_HOST) { $env:MCP_HTTP_HOST = '127.0.0.1' } +if (-not $env:MCP_HTTP_PORT) { $env:MCP_HTTP_PORT = '7000' } +Write-Host (" Gateway: " + $env:BABA_GATEWAY_URL) +$transportLine = " Transport: " + $env:MCP_TRANSPORT +if ($env:MCP_TRANSPORT -eq 'http') { + $transportLine += " on " + $env:MCP_HTTP_HOST + ":" + $env:MCP_HTTP_PORT +} +Write-Host $transportLine + +# ----- 5. Gateway health-check -------------------------------------------- +Step "5. Gateway health-check" +if ($SkipGatewayCheck.IsPresent -or $env:SKIP_GATEWAY_CHECK -eq '1') { + Warn "Skipped" +} else { + try { + $resp = Invoke-RestMethod -Uri ($env:BABA_GATEWAY_URL + '/api/Diag/GetSupply') ` + -Method Post -Body '{}' -ContentType 'application/json' ` + -TimeoutSec 5 -SkipCertificateCheck:$true + if ($resp.success) { + Ok "Gateway reachable (Diag/GetSupply returned success)" + } else { + Warn "Gateway reachable but response unexpected" + } + } catch { + Write-Host "[FAIL] Gateway unreachable at $($env:BABA_GATEWAY_URL): $_" -ForegroundColor Red + Write-Host " Set BABA_GATEWAY_URL, start the gateway, or pass -SkipGatewayCheck" -ForegroundColor Red + exit 2 + } +} + +# ----- 6. Launch ---------------------------------------------------------- +Step "6. Starting MCP server" +Set-Location $RepoRoot +& $VenvPy -m baba_mcp.server +exit $LASTEXITCODE diff --git a/scripts/launch-mcp.sh b/scripts/launch-mcp.sh new file mode 100755 index 0000000..95566e1 --- /dev/null +++ b/scripts/launch-mcp.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# launch-mcp.sh — bootstrap and start the baba-credits MCP server (Linux/macOS). +# +# What it does: +# 1. Finds a Python >= 3.10 interpreter (the `mcp` SDK requires it). +# 2. Creates a local virtualenv at /.venv if missing. +# 3. Installs the three MCP runtime deps (mcp, httpx, pydantic) if missing. +# 4. Loads /.env.mcp if present (BABA_GATEWAY_URL, MCP_TRANSPORT, …). +# 5. Health-checks the gateway URL (read-only HEAD/POST to /api/Diag/GetSupply). +# 6. Launches `python -m baba_mcp.server` and forwards exit code. +# +# Usage: +# bash scripts/launch-mcp.sh # stdio transport (default) +# MCP_TRANSPORT=http bash scripts/launch-mcp.sh # HTTP/SSE transport +# bash scripts/launch-mcp.sh --no-pip # skip pip install (faster relaunch) +# bash scripts/launch-mcp.sh --reinstall # force reinstall of MCP deps +# +# Exit codes: +# 0 — server exited cleanly (e.g. SIGINT) +# 1 — bootstrap failure (Python missing, venv broken, deps install failed) +# 2 — gateway health-check failed (skip with SKIP_GATEWAY_CHECK=1) +# anything else — propagated from `python -m baba_mcp.server` + +set -euo pipefail + +# ----- Paths -------------------------------------------------------------- +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +VENV_DIR="$REPO_ROOT/.venv" +ENV_FILE="$REPO_ROOT/.env.mcp" + +# ----- ANSI helpers ------------------------------------------------------- +if [ -t 1 ]; then + GREEN='\033[0;32m'; YELLOW='\033[0;33m'; RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m' +else + GREEN=''; YELLOW=''; RED=''; BOLD=''; NC='' +fi +ok() { printf "${GREEN}✓${NC} %s\n" "$*"; } +warn() { printf "${YELLOW}⚠${NC} %s\n" "$*"; } +err() { printf "${RED}✗${NC} %s\n" "$*" >&2; } +step() { printf "\n${BOLD}%s${NC}\n" "$*"; } + +# ----- Args --------------------------------------------------------------- +SKIP_PIP=0 +REINSTALL=0 +for arg in "$@"; do + case "$arg" in + --no-pip) SKIP_PIP=1 ;; + --reinstall) REINSTALL=1 ;; + -h|--help) + sed -n '2,/^$/p' "$0" | sed 's/^# \?//' + exit 0 + ;; + *) + err "Unknown argument: $arg" + exit 1 + ;; + esac +done + +# ----- 1. Find Python >= 3.10 --------------------------------------------- +step "1. Locating a Python >= 3.10 interpreter" +PY_BIN="" +for cand in python3.13 python3.12 python3.11 python3.10 python3 python; do + if command -v "$cand" >/dev/null 2>&1; then + ver=$("$cand" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo "0.0") + major=${ver%%.*}; minor=${ver##*.} + if [ "$major" -gt 3 ] || { [ "$major" -eq 3 ] && [ "$minor" -ge 10 ]; }; then + PY_BIN="$cand" + ok "Found $cand (Python $ver)" + break + fi + fi +done + +if [ -z "$PY_BIN" ]; then + err "No Python >= 3.10 found in PATH." + err "Install one of:" + err " - Linux: apt install python3.11 python3.11-venv (or your distro's equivalent)" + err " - macOS: brew install python@3.11" + err " - Or use pyenv / asdf to manage multiple versions." + exit 1 +fi + +# ----- 2. Create / reuse virtualenv --------------------------------------- +step "2. Setting up virtualenv at $VENV_DIR" +VENV_PY="" +if [ -x "$VENV_DIR/bin/python" ]; then + VENV_PY="$VENV_DIR/bin/python" + ver=$("$VENV_PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo "0.0") + major=${ver%%.*}; minor=${ver##*.} + if [ "$major" -gt 3 ] || { [ "$major" -eq 3 ] && [ "$minor" -ge 10 ]; }; then + ok "Reusing existing venv (Python $ver)" + else + warn "Existing venv has Python $ver, recreating with $PY_BIN" + rm -rf "$VENV_DIR" + VENV_PY="" + fi +fi +if [ -z "$VENV_PY" ]; then + "$PY_BIN" -m venv "$VENV_DIR" || { + err "Failed to create venv. On Debian/Ubuntu try: apt install ${PY_BIN}-venv" + exit 1 + } + VENV_PY="$VENV_DIR/bin/python" + ok "Venv created" +fi + +# ----- 3. Install MCP deps ------------------------------------------------ +step "3. Verifying MCP dependencies" +need_install=$REINSTALL +if [ $REINSTALL -eq 0 ] && [ $SKIP_PIP -eq 0 ]; then + if ! "$VENV_PY" -c 'import mcp, httpx, pydantic' 2>/dev/null; then + need_install=1 + fi +fi +if [ $need_install -eq 1 ] && [ $SKIP_PIP -eq 0 ]; then + "$VENV_PY" -m pip install --upgrade pip >/dev/null + if [ -f "$REPO_ROOT/requirements.txt" ]; then + "$VENV_PY" -m pip install -r "$REPO_ROOT/requirements.txt" || { + err "pip install failed" + exit 1 + } + else + "$VENV_PY" -m pip install 'mcp>=1.0.0' 'httpx>=0.27.0' 'pydantic>=2.5.0' || { + err "pip install failed" + exit 1 + } + fi + ok "Dependencies installed" +else + ok "All deps already present (use --reinstall to force)" +fi + +# ----- 4. Load .env.mcp --------------------------------------------------- +step "4. Loading environment" +if [ -f "$ENV_FILE" ]; then + set -a; . "$ENV_FILE"; set +a + ok "Loaded $ENV_FILE" +else + warn "$ENV_FILE not found — using defaults / shell env vars only" +fi +: "${BABA_GATEWAY_URL:=http://127.0.0.1:5000}" +: "${MCP_TRANSPORT:=stdio}" +: "${MCP_HTTP_HOST:=127.0.0.1}" +: "${MCP_HTTP_PORT:=7000}" +export BABA_GATEWAY_URL MCP_TRANSPORT MCP_HTTP_HOST MCP_HTTP_PORT +printf " Gateway: %s\n" "$BABA_GATEWAY_URL" +printf " Transport: %s" "$MCP_TRANSPORT" +[ "$MCP_TRANSPORT" = "http" ] && printf " on %s:%s" "$MCP_HTTP_HOST" "$MCP_HTTP_PORT" +echo + +# ----- 5. Gateway health-check -------------------------------------------- +step "5. Gateway health-check" +if [ "${SKIP_GATEWAY_CHECK:-0}" = "1" ]; then + warn "Skipped (SKIP_GATEWAY_CHECK=1)" +elif command -v curl >/dev/null 2>&1; then + if body=$(curl -fsS -m 5 -X POST "$BABA_GATEWAY_URL/api/Diag/GetSupply" \ + -H "Content-Type: application/json" -d '{}' 2>&1); then + if echo "$body" | grep -q '"success":[[:space:]]*true'; then + ok "Gateway reachable (Diag/GetSupply returned success)" + else + warn "Gateway reachable but response unexpected: ${body:0:80}" + fi + else + err "Gateway unreachable at $BABA_GATEWAY_URL" + err "Set BABA_GATEWAY_URL or start the gateway, or pass SKIP_GATEWAY_CHECK=1" + exit 2 + fi +else + warn "curl not installed — skipping health-check" +fi + +# ----- 6. Launch ---------------------------------------------------------- +step "6. Starting MCP server" +cd "$REPO_ROOT" +exec "$VENV_PY" -m baba_mcp.server diff --git a/services/contracts.py b/services/contracts.py index 399de23..77bdb40 100644 --- a/services/contracts.py +++ b/services/contracts.py @@ -383,22 +383,74 @@ def map_methods(res: Any) -> dict: def map_state(res: Any) -> dict: + """Shape ``SmartContractDataResult`` (apihandler.cpp:2611) for the gateway. + + The Thrift schema is:: + + struct SmartContractDataResult { + 1: APIResponse status + 2: list methods + 3: map variables + } + + Both ``methods`` and ``variables`` are exposed: this is the most reliable + way to read a deployed contract's public surface plus its instance fields, + even when ``ContractMethodsGet(address)`` returns an empty list because + the executor hasn't cached the contract yet. ``variables`` is decoded + Variant-by-Variant so the client receives plain JSON values + (strings/ints/booleans) instead of opaque Thrift Variant blobs. + """ + # Reuse the shared Variant decoder from services.monitor to avoid duplication. + from services.monitor import _variant_to_python # local import — circular safe + s = _status(res) - contract_state = getattr(res, "contractState", None) or getattr(res, "state", None) - variables_raw = getattr(res, "variables", None) or [] - variables = [] - for v in variables_raw: - variables.append( - { - "name": getattr(v, "name", None), - "type": getattr(v, "type", None), - "value": getattr(v, "value", None), - } - ) + # variables: schema is map; older / fork shapes may use + # a list<{name, type, value}> too — accept both for defensiveness. + variables_raw = getattr(res, "variables", None) + variables: list = [] + if isinstance(variables_raw, dict): + for name, variant in variables_raw.items(): + variables.append({ + "name": name, + "value": _variant_to_python(variant), + }) + elif variables_raw: + for v in variables_raw: + if isinstance(v, dict): + variables.append(v) + else: + raw_val = getattr(v, "value", None) + # If value is a Thrift Variant (has v_string/v_int/...), decode it. + # Otherwise pass through as-is so plain primitives stay plain. + decoded = _variant_to_python(raw_val) if any( + hasattr(raw_val, a) for a in ( + "v_string", "v_int", "v_long", "v_boolean", "v_byte_array", + "v_amount", "v_array", "v_map", + ) + ) else raw_val + variables.append({ + "name": getattr(v, "name", None), + "type": getattr(v, "type", None), + "value": decoded, + }) + + methods_raw = getattr(res, "methods", None) or [] + methods = [] + for m in methods_raw: + args_raw = getattr(m, "arguments", None) or [] + methods.append({ + "name": getattr(m, "name", None), + "returnType": getattr(m, "returnType", None), + "arguments": [ + {"name": getattr(a, "name", None), "type": getattr(a, "type", None)} + for a in args_raw + ], + }) + return { "success": s["code"] == 0, "message": s["message"] or None, - "state": contract_state, + "methods": methods, "variables": variables, } diff --git a/services/userfields.py b/services/userfields.py index 3e9c075..9a09cc6 100644 --- a/services/userfields.py +++ b/services/userfields.py @@ -1,10 +1,17 @@ -"""ArtVerse userFields v1 codec. +"""userFields v1 codec — ordinals-style on-chain metadata for Credits. + +Encodes a small structured payload (digest, IPFS CID, MIME, size, optional +TLV extensions) into a base58 blob suitable for the `UserData` field of a +Credits transaction, so the chain carries a verifiable reference to the +off-chain asset. Decoding round-trips the same fields. Wire format (binary): userFields := MAGIC | VERSION | TLV_RECORDS - MAGIC = b"ARTV" (4 bytes ASCII) + MAGIC = b"ARTV" (4 bytes ASCII; legacy magic, retained for + backwards compatibility with existing inscribed + transactions and test vectors) VERSION = 0x01 (1 byte) TLV_RECORDS = (TYPE | LEN | VALUE)* TYPE = 1 byte diff --git a/tests/test_contracts.py b/tests/test_contracts.py index d8573ef..0ef179a 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -206,16 +206,45 @@ def test_map_methods_includes_arguments(): def test_map_state_includes_variables(): + # Legacy list-of-objects shape kept for backwards compatibility with + # forks that pre-date the proper map Thrift schema. res = NS( status=OK, - contractState="", variables=[NS(name="counter", type="int", value="42")], ) out = c.map_state(res) - assert out["state"] == "" assert out["variables"] == [{"name": "counter", "type": "int", "value": "42"}] +def test_map_state_handles_thrift_map_variables(): + # Real Thrift schema: variables: map. Each Variant is + # decoded so the JSON-facing client gets a primitive instead of an + # opaque Thrift struct. + counter = NS(v_long=42) + name = NS(v_string="EBB") + res = NS(status=OK, variables={"counter": counter, "name": name}) + out = c.map_state(res) + decoded = {v["name"]: v["value"] for v in out["variables"]} + assert decoded == {"counter": 42, "name": "EBB"} + + +def test_map_state_includes_methods_from_data_get(): + # SmartContractDataResult also carries the contract's public methods. + method = NS( + name="transfer", + returnType="boolean", + arguments=[NS(name="to", type="String"), NS(name="amount", type="String")], + ) + res = NS(status=OK, methods=[method], variables={}) + out = c.map_state(res) + assert out["methods"][0]["name"] == "transfer" + assert out["methods"][0]["returnType"] == "boolean" + assert out["methods"][0]["arguments"] == [ + {"name": "to", "type": "String"}, + {"name": "amount", "type": "String"}, + ] + + def test_map_list_by_wallet_serialises_contracts(): contracts = [ NS(