From 0a8de86c438397e07c10509ccaf64beeea4b2c4f Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 06:44:55 +0200 Subject: [PATCH 1/7] feat(mcp): Bearer-token + IP allowlist enforcement on HTTP/SSE transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The HTTP transport was previously bound on the configured host with no inbound auth check — only an outbound bearer for the gateway client and a warning log. Exposing port 7000 beyond localhost meant any external client could enumerate tools and invoke them. Add a Starlette BaseHTTPMiddleware that gates both /sse and /messages/: - Reject 401 if MCP_AUTH_TOKEN is configured and the request omits or mismatches the `Authorization: Bearer ` header. - Reject 403 if MCP_WHITELIST_IPS is configured and the client IP is not in the list. The literal "0.0.0.0/0" is treated as a wildcard sentinel that disables the IP gate (use Bearer-only auth). - Middleware is only registered when at least one gate is active, so a pure-localhost dev setup (`MCP_HTTP_HOST=127.0.0.1`, no token) keeps zero overhead. Wire cfg.auth_token and cfg.whitelist_ips through main() so the existing .env.mcp.example knobs actually take effect end-to-end. .gitignore: add .env.mcp so the production token never gets committed (matches the pattern already in place for .env, .env.local, .env.smoke). Tested locally: - `curl http://0.0.0.0:7000/sse` (no token) → HTTP 401 - `curl -H 'Authorization: Bearer ' .../sse` → HTTP 200 (SSE) - `curl -H 'Authorization: Bearer wrong' .../sse` → HTTP 401 Co-Authored-By: Claude Opus 4.7 --- .gitignore | 1 + baba_mcp/server.py | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) 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/baba_mcp/server.py b/baba_mcp/server.py index 1447ada..31be1ee 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,36 @@ 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) + app = Starlette(routes=[ Route("/sse", handle_sse), Mount("/messages/", app=sse.handle_post_message), ]) + 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 +164,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}") From a0de996b72b26d1553449189afb9c58d767db311 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 07:01:16 +0200 Subject: [PATCH 2/7] feat(gateway): GATEWAY_HOST env var to bind behind reverse proxy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hardcoding host='0.0.0.0' in gateway.py forced the gateway to listen on all interfaces, which is fine for a direct deployment but undesirable when the gateway sits behind Nginx/Caddy as a reverse proxy with TLS: exposing :5000 directly bypasses TLS, rate-limiting middleware, and Bearer auth (for the MCP). Read GATEWAY_HOST and GATEWAY_PORT from the environment (typically loaded from .env), defaulting to the historical 0.0.0.0:5000 so direct deployments keep working unchanged. Reverse-proxy deployments set GATEWAY_HOST=127.0.0.1 in their .env and stop publishing :5000. Tested locally: - GATEWAY_HOST=127.0.0.1 → ss shows 127.0.0.1:5000 only; curl http://:5000/api/Diag/GetSupply → connection refused; curl https:///api/Diag/GetSupply (via Nginx) → 200 OK. - Without GATEWAY_HOST → defaults to 0.0.0.0:5000 unchanged. Co-Authored-By: Claude Opus 4.7 --- gateway.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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) From b04a8690838bd66f68851ad3dc248c0015be832a Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 09:49:49 +0200 Subject: [PATCH 3/7] feat(scripts): cross-platform MCP launch scripts (Linux/macOS + Windows) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripts/launch-mcp.sh — bash 4+ script for Linux and macOS. scripts/launch-mcp.ps1 — PowerShell 5.1+ script for Windows. Both perform the same bootstrap + sanity sequence and stream coloured progress (six numbered steps): 1. Locate a Python >= 3.10 interpreter. The `mcp` SDK on PyPI does not ship wheels for older versions, so anything earlier than 3.10 is a non-starter. The bash version probes python3.13 down to python3, the PowerShell version uses the `py -3.x` launcher when available then falls back to `python` / `python3` on PATH. 2. Create or reuse `.venv/` next to the repo. If an existing venv is pinned to an older Python it gets recreated. 3. `pip install` the three MCP runtime deps (mcp, httpx, pydantic) only when missing — `--no-pip` / `-NoPip` skips the check entirely for fast relaunches; `--reinstall` / `-Reinstall` forces a reinstall. 4. Source `.env.mcp` if present so BABA_GATEWAY_URL, MCP_TRANSPORT, MCP_AUTH_TOKEN, MCP_HTTP_HOST/PORT all flow through with one file. 5. Hit the gateway with a 5-second read-only POST to /api/Diag/GetSupply and abort (exit 2) on failure, unless SKIP_GATEWAY_CHECK=1 / -SkipGatewayCheck is set. 6. `exec` `python -m baba_mcp.server` so the script's PID becomes the server (signals + exit code propagate cleanly). README "MCP Server" section gains a "Quick start (cross-platform launch script)" sub-section that documents both invocations + flag matrix before the existing Configure an Agent walkthrough. Tested on Linux: end-to-end run reaches step 6, then defers to the underlying `python -m baba_mcp.server` (which currently fails because the production MCP is already on :7000 — expected port collision). Co-Authored-By: Claude Opus 4.7 --- README.md | 44 ++++++++++ scripts/launch-mcp.ps1 | 191 +++++++++++++++++++++++++++++++++++++++++ scripts/launch-mcp.sh | 177 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 412 insertions(+) create mode 100644 scripts/launch-mcp.ps1 create mode 100755 scripts/launch-mcp.sh diff --git a/README.md b/README.md index 7be3d1c..0c52278 100644 --- a/README.md +++ b/README.md @@ -460,6 +460,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 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 From 0578f92df4826dd9983d26ef017a34774d8df925 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 10:00:23 +0200 Subject: [PATCH 4/7] docs(readme): add 30-second mobile/desktop quick-add for end users MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The MCP section opened with operator-side topics (pm2 bundle, launch scripts, signing material) and only got to "how do I plug Claude into a running server" after ~150 lines. That order is right for the operator but wrong for the most common end-user path: someone on a phone who just wants to paste a URL and a token into Claude and start using the tools. Add a "Connect from Claude in 30 seconds" subsection at the very top of the MCP section, before any operator material. It covers: - The two pieces of info to ask the operator for: a URL and a Bearer token, with the password-treatment caveat. - A copy-pasteable JSON snippet that works for both Claude Desktop (claude_desktop_config.json) and Claude Code (.mcp.json), with the two PASTE-YOUR-* placeholders. After restarting Claude the 29 tools appear in the picker; gives a "what's the balance of " prompt to confirm the connection. - Instructions for Claude.ai (web/mobile browser) via Settings → Connectors → Add custom connector. - A one-tap `mcp+sse://token@host/sse` URI for clients that support it. - A heads-up about self-signed certificates: links to the trust-store install path on iOS and Android, plus the recommendation to push the operator toward Let's Encrypt for a public deployment. - A signpost down to the operator-side material for readers who want to host their own. Existing operator content (pm2, launch scripts, configure-an-agent walkthrough, security notes) stays unchanged — this is an additive on-ramp. Co-Authored-By: Claude Opus 4.7 --- README.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/README.md b/README.md index 0c52278..9141c25 100644 --- a/README.md +++ b/README.md @@ -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 From 55bf98a66fc33aca88c3a187a7478103acaf324e Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 10:10:10 +0200 Subject: [PATCH 5/7] docs: replace 'ArtVerse' with generic 'ordinals-style on-chain inscription' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ArtVerse is one application of the userFields v1 codec, not the codec itself. Naming the public API after a single consumer made the surface look proprietary, hurt discoverability for agents reasoning in terms of the more widely-known "ordinals / inscription" pattern, and tied the upstream PR to BABA branding instead of the underlying technical idea. Rewrite all user-facing copy (README, skill, tools-reference, recipe) to describe the codec as ordinals-style on-chain metadata inscription (digest + IPFS CID + MIME + size). Triggers in the skill frontmatter now key off "on-chain ordinal/inscription, userFields metadata" rather than the previous "ArtVerse mint" trigger phrase. services/userfields.py: docstring rewritten in the same spirit; the binary MAGIC bytes "ARTV" are *kept* — they're an on-chain wire-format constant that any already-inscribed transaction depends on, and changing them would break decoding of historical user-data blobs. The docstring now explicitly documents this as a backwards-compat decision. Internal historical docs (docs/superpowers/*, docs/FOLLOW_UP.md) keep their original wording — they record what was discussed at the time. Tests: 121 passed (no behavioural change). Co-Authored-By: Claude Opus 4.7 --- .claude/skills/baba-credits/SKILL.md | 14 ++++++++------ .../skills/baba-credits/recipes/attach-metadata.md | 9 +++++---- .claude/skills/baba-credits/tools-reference.md | 11 ++++++----- README.md | 12 ++++++------ services/userfields.py | 11 +++++++++-- 5 files changed, 34 insertions(+), 23 deletions(-) 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/README.md b/README.md index 9141c25..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 '{ @@ -724,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 | @@ -785,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/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 From 96973e1d9c2c6a8a2be6b9005f7cb4d3cf61ae97 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 15:32:45 +0200 Subject: [PATCH 6/7] fix(gateway): decode SC return values + map state map+methods correctly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surfaced testing the EBB token contract (EK7Fm4JPmfACz...): every smartcontract_execute call sealed on-chain successfully but the gateway was returning smartContractResult=null and smartcontract_state was returning empty variables/no methods. Three independent bugs in the mapping layer. 1. routes/smartcontract.py:_execute_smart_tx — TransactionFlowResult carries `smart_contract_result: optional general.Variant` (the method return value: e.g. v_string for getSymbol(), v_boolean for transfer()). The handler was passing the raw Thrift Variant object to jsonify, which serialised it as null instead of extracting the primitive. Decode via services.monitor._variant_to_python. 2. routes/smartcontract.py:_execute_smart_tx polling fallback path — when TransactionFlow disconnects early, after recovering the sealed tx_id via TransactionsGet polling, also call TransactionResultGet to pull the smart_contract_result (so the recovered response shape matches the happy path). 3. services/contracts.py:map_state — SmartContractDataResult is:: struct SmartContractDataResult { 1: APIResponse status 2: list methods 3: map variables } The old mapper iterated `variables` as if it were a list-of-objects with .name/.type/.value attrs (returning [] for any real-Thrift dict), and ignored `methods` entirely. New mapper: - Detects map shape and emits one {name, value} entry per key, with the Variant decoded to a JSON primitive. - Falls back to the legacy list-of-objects shape (NS-style) so the unit-test fixtures and any fork variants keep working. - Surfaces `methods` (the contract's public surface) — this is the only reliable way to read it on this node version, since ContractMethodsGet(address) returns an empty list until the executor decides to populate its cache. Tests: - New test_map_state_handles_thrift_map_variables exercising the map path with v_long + v_string Variants. - New test_map_state_includes_methods_from_data_get exercising the methods passthrough. - Existing test_map_state_includes_variables relaxed: dropped the no-longer-emitted "state" field, kept the list-of-objects coverage. - 123 passed (was 121). Co-Authored-By: Claude Opus 4.7 --- routes/smartcontract.py | 26 ++++++++++++-- services/contracts.py | 76 ++++++++++++++++++++++++++++++++++------- tests/test_contracts.py | 33 ++++++++++++++++-- 3 files changed, 119 insertions(+), 16 deletions(-) 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/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/tests/test_contracts.py b/tests/test_contracts.py index d6b549e..fc235df 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -207,16 +207,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( From 9ad65b5b60b5646384e15579beb7632e25a26733 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Thu, 30 Apr 2026 15:59:29 +0200 Subject: [PATCH 7/7] feat(mcp): expose forgetNewState on SC pack/execute (read-only contract reads) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validating the EBB token contract on-chain showed that the Credits node populates TransactionFlowResult.smart_contract_result (the method's return Variant) only when the call is invoked with forgetNewState=True. That's the standard read-only-call hint: the executor runs the method, returns the value, then drops the state mutation. Without it, the transaction persists but the node leaves smart_contract_result empty — so getters like getSymbol(), totalSupply(), balanceOf(...) appear to "succeed but return null" through the gateway. Add forget_new_state to both: - SmartContractPackInput (alias forgetNewState, optional) - SmartContractExecuteInput (alias forgetNewState, default False) Pydantic models had extra='forbid' so the field had to be declared on both sides — the gateway already supported `forgetNewState` on its /SmartContract/Pack and /SmartContract/Execute payloads. Both endpoints (Pack and Execute) MUST receive the same value: the canonical signing payload depends on the SmartContractInvocation serialisation, and forgetNewState is part of that payload. A mismatch would change the rebuilt inner_id signature and the node would reject the tx. Validated: the same contract calls now return: getName → 'EBB' getSymbol → 'EBB' getDecimal → 18 totalSupply → '1000000' balanceOf(...) → numeric string And a real transfer (forget=False) followed by post-transfer balanceOf (forget=True) shows the expected delta: -0.25 sender / +0.25 receiver. Also (defensive cleanup): removed an experimental 96 KiB SSE-padding ASGI send wrapper in baba_mcp/server.py:_run_http that was added to try unsticking Cloudflare Quick Tunnel buffering. Cloudflare Quick Tunnel turned out to be the wrong path entirely (proper Let's Encrypt cert via DuckDNS works fine without it), and the wrapper had an exit path that let starlette receive a None response object on certain race conditions, producing 'NoneType is not callable' tracebacks. SseNoBufferMiddleware (X-Accel-Buffering: no header) is the standard nginx-friendly hint and is sufficient. Co-Authored-By: Claude Opus 4.7 --- baba_mcp/server.py | 31 +++++++++++++++++++++++++++++++ baba_mcp/tools/smartcontract.py | 17 +++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/baba_mcp/server.py b/baba_mcp/server.py index 31be1ee..276fd16 100644 --- a/baba_mcp/server.py +++ b/baba_mcp/server.py @@ -141,10 +141,41 @@ async def dispatch(self, request, call_next): ) 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") 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)