Skip to content

Adds the baba-credits Model Context Protocol (MCP) server on top of the existing gateway - #2

Merged
molaanaa merged 66 commits into
molaanaa:mainfrom
EnzinoBB:main
Apr 29, 2026
Merged

molaanaa merged 66 commits into
molaanaa:mainfrom
EnzinoBB:main

Conversation

@EnzinoBB

Copy link
Copy Markdown
Contributor

Summary
Adds the baba-credits Model Context Protocol (MCP) server on top of the existing gateway, exposing all 29 REST endpoints as MCP tools so AI agents (Claude Code/Desktop, Cline, Cursor, smart wallets with embedded AI, custom agents) can operate on the Credits blockchain through structured tool calls. Ships with a Claude Code skill that documents the canonical pipelines and a full on-chain smoke validated against a live node.

The MCP server is a thin Python wrapper sitting alongside the gateway. It is non-custodial: it never holds private keys. The signing pipeline stays client-side: Pack → ed25519 sign → Execute → Wait. No change to existing gateway endpoints' contract.

What's in this PR
baba_mcp/ — MCP server package
29 tools registered as a single @server.list_tools() and @server.call_tool() pair on the MCP server. Per-module decorator registration was found to overwrite previous handlers (the SDK keys request handlers by request type), so the loader aggregates each module's _DISPATCH and _TOOL_DEFS into one merged dispatch table — verified with a runtime test asserting all 29 tools surface to a real ListToolsRequest.
Pydantic input models per tool with field-name + alias acceptance (PublicKey/publicKey, transactionId/TransactionId, etc.) to match the gateway's existing dual-naming.
httpx async client with retry on 503 + bearer auth + HTTP error mapping (400→invalid_input, 404→not_found, 429→rate_limited, 503→node_unavailable, 500→internal).
stdio and http+SSE transports; configurable via env (MCP_TRANSPORT, MCP_HTTP_HOST, MCP_HTTP_PORT, MCP_AUTH_TOKEN, etc.).
.claude/skills/baba-credits/ — Claude Code skill
SKILL.md entry point with the canonical Pack→sign→Execute pipeline, decision tree (which tool for which user intent), critical constraints (innerId stickiness, SCAPI import, deterministic deploy address), and error-code map.
tools-reference.md catalogue of all 29 tools (input schema, sample output, when-to-use). Verified by a tests/test_skill_drift.py that asserts the skill catalogue and the registered MCP tools stay in sync.
6 recipes (recipes/transfer-cs.md, deploy-contract.md, execute-method.md, inspect-wallet.md, attach-metadata.md, token-operations.md) walking the agent through full pipelines.
2 signing snippets (signing/python-pynacl.md validated on-chain 2026-04-27, signing/typescript-tweetnacl.md for wallet keystores).
troubleshooting.md mapping common errors to causes and fixes.
Deployment
ecosystem.config.js: pm2 bundle that runs gateway.py (:5000) and baba-mcp-http (:7000) side by side.
.env.mcp.example: 10 documented MCP env vars.
README.md: new ## 🤖 MCP Server section (~230 lines) with concrete config recipes for Claude Code, Claude Desktop, Cline/Cursor, remote HTTP/SSE agents, and a custom Python agent example.
Gateway hardening (surfaced by the on-chain smoke)
While running the smoke against a live node we hit 5 issues that produced 500/400 responses for legitimate inputs. Each is a minimal, targeted fix:

gateway.py:GetTransactionInfo — getattr(data, 'userFields', b'') returned None (not the b'' default) when the attribute existed but was unset, then .decode() crashed. Coerce: (getattr(...) or b'').decode().
routes/monitor_wait.py:transaction_result — TransactionResultGet expects an i64 requestId per the Thrift schema, not a TransactionId object. Look up the innerId via TransactionGet first, then call TransactionResultGet(int(inner_id)).
routes/monitor_wait.py:wait_for_smart_transaction — accept address/Address aliases (matches the natural input name for contract-targeting calls).
routes/smartcontract.py:Pack/Execute — accept ReceiverPublicKey/receiverPublicKey aliases on the target lookup, matching transaction_pack/transaction_execute conventions.
routes/smartcontract.py:_execute_smart_tx — most impactful: on the tested node, client.TransactionFlow(tx) for SmartContract Deploy/Execute raises TTransportException: unexpected exception because the node closes the Thrift connection a few seconds before sending the response, even though the transaction is accepted and sealed. Cross-checked in the node's debug.log (Smart: state is updated by {.} entries appear ~5s after the gateway error). Fix: catch the disconnect, poll TransactionsGet(source) every 1s for up to 15s, look for a SealedTransaction with trxn.id == inner_id, return success + formatted transactionId. Re-raise only if polling times out. Pure recovery — no behaviour change on healthy connections.
Better exception logging across the touched handlers (type(e).name: {e!r}) so downstream consumers can distinguish transport vs application errors.
On-chain validation
scripts/mcp_full_smoke.py exercises every implemented tool end-to-end against a live node. Latest run on the project's Credits node:

25 PASS — all 4 diag_, 4 monitor_ read-only, monitor_wait_for_smart_transaction, both userfields_, all 4 transaction_ (incl. an on-chain transaction_execute of 0.001 CS that sealed in <5s), and 8 smartcontract_* (compile, pack×2, deploy real on-chain, get, methods×2, state, list_by_wallet, execute real on-chain).
0 FAIL.
6 SKIP for node-side limitations confirmed to fail even when bypassing the gateway (verified by direct Thrift calls to the node): monitor_wait_for_block (TTransportException on long-poll), tokens_balances_get (node responds "This node doesn't provide such info"), tokens_info/tokens_transfers_get/tokens_holders_get/tokens_transactions_get (require a node configured with the monitor API). On a Credits node with the monitor service enabled, all six should pass without code changes on this side.
Test plan
[x] Unit tests: pytest tests/ -q → 121 passed.
[x] Skill ↔ code drift test ensures catalogue/frontmatter/recipes stay in sync with registered tools.
[x] CI extended: MCP byte-compile + filtered pytest gated on Python 3.11.
[x] On-chain smoke against a live Credits node (results above).
[x] Manual QA checklist documented in scripts/MANUAL_QA.md.
[x] Runtime sanity: request_handlers[ListToolsRequest] returns exactly 29 tools.
Compatibility & scope
Zero breaking changes to existing gateway endpoints. All MCP code lives in new baba_mcp/ and .claude/skills/baba-credits/. The five gateway hardening fixes (1-5 above) widen the accept-list and harden error paths but never narrow inputs.
The new dependencies (mcp, httpx, pydantic) are added to requirements.txt and used only by the MCP server, never by the gateway runtime.
Tested as a clean fast-forward of the deployment runtime — gateway restarts on top of the merged code with no config changes.
🤖 Generated with Claude Code

EnzinoBB and others added 30 commits April 28, 2026 18:58
README rewrite

- Document the post-refactoring layout: gateway.py + routes/ Blueprints
  + services/ pure-Python helpers, with the 22-endpoint matrix.
- Cover every variable in .env.example, including NODE_DIAG_PORT (the
  single-port assumption was a recurring foot-gun: API_DIAG normally
  lives on a separate port — typically 9088).
- Add a dedicated section "Smart Contract end-to-end flow" describing
  the Compile -> Pack -> sign -> Deploy/Execute -> Result pipeline and
  the canonical signing layout the node validates against.
- Replace the static curl examples with a worked Pack -> sign -> Deploy
  -> Pack -> sign -> Execute flow.
- Drop a broken link to docs/SMART_CONTRACTS.md (file never existed).
- Mention the CI workflow + Python 3.8/3.11 matrix.

payloads/ examples (28 files, organised by route module)

  payloads/
    monitor/{GetWalletInfo,GetBalance,GetTransactionsByWallet,GetEstimatedFee}.json
    transaction/{Pack,Execute,GetTransactionInfo,Result}.json
    smartcontract/{Compile,Get,Methods,State,ListByWallet,Pack,Deploy,Execute}.json
    tokens/{BalancesGet,TransfersGet,Info,HoldersGet,TransactionsGet}.json
    monitor_wait/{WaitForBlock,WaitForSmartTransaction}.json
    diag/{GetActiveNodes,GetActiveTransactionsCount,GetNodeInfo,GetSupply}.json
    userfields/{Encode,Decode}.json

Each file is a single JSON object with a stable shape:

  { endpoint, method, description,
    request (or request_<variant>),
    response_success (or response_success_<variant>),
    response_error (or response_error_<variant>),
    notes }

Samples are taken from the live mainnet smoke runs where possible
(GetWalletInfo, SmartContract/Get on a real TokenSRG, Diag/* against
the local node, the Deploy/Execute round-trip on FwdrHR4w...) and
plausible otherwise. All addresses, hashes and signatures are base58;
bytecode is base64; amounts are strings.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Spec completo per esporre il gateway HTTP come MCP server (29 tools 1:1
con gli endpoint REST) e per una skill versionata in .claude/skills/
che documenta tutte le operazioni blockchain (recipes, signing,
troubleshooting). Architettura: thin Python wrapper non-custodial
sopra il gateway, processi disaccoppiati gestiti via pm2 ecosystem.
54 task TDD copre: foundation (package, client httpx, errors, schemas,
server, tool helpers), 29 tools 1:1 con gli endpoint REST suddivisi
per categoria, skill completa in .claude/skills/baba-credits/ (SKILL,
tools-reference, 6 recipes, 2 signing snippet, troubleshooting),
deployment (pm2 ecosystem + .env.mcp.example + README), drift test
skill<->codice, CI estesa, smoke on-chain manuale.
Documenta lo stato del lavoro dopo M1 Foundation e fornisce le
istruzioni per riprendere da una nuova sessione (eventualmente
con un account diverso) senza perdere context.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
EnzinoBB and others added 26 commits April 29, 2026 15:35
Fixes a critical bug where each tool module's @server.list_tools()
and @server.call_tool() decorators overwrote the previous module's
handlers, leaving only 4 tools reachable via the MCP protocol at
runtime. Now build_server() aggregates _DISPATCH and _TOOL_DEFS
from all 6 modules and registers a single pair of handlers.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
End-to-end smoke testing on a live Credits node surfaced several mismatches
between gateway field-name conventions and the MCP/SDK input schemas, plus
two unsafe gateway code paths. All fixes preserve the documented MCP tool
inputs while broadening the gateway accept-list and improving error context.

Gateway changes:
- gateway.py: GetTransactionInfo crashed with "'NoneType' object has no
  attribute 'decode'" when a transaction had no userFields. Coerce None to
  b"" before decoding.
- routes/monitor_wait.py: TransactionResultGet expects an i64 innerId per
  the Thrift schema, not a TransactionId object. Look up the innerId via
  TransactionGet first, then call TransactionResultGet with it.
  Also accept 'address'/'Address' aliases on /Monitor/WaitForSmartTransaction
  to match the MCP tool input.
- routes/smartcontract.py: accept 'ReceiverPublicKey'/'receiverPublicKey'
  on /SmartContract/Pack and /SmartContract/Execute target lookup, matching
  the field name used by transaction_pack/execute and by the MCP tool.
- routes/{monitor_wait,smartcontract}.py: include exception type and repr
  in error logs and response messages, so the MCP layer surfaces actionable
  details instead of a generic "failed".

MCP change:
- baba_mcp/tools/smartcontract.py: SmartContractListByWalletInput.deployer
  serialised as 'deployer' but the gateway expects 'publicKey'. Add
  alias='publicKey' so model_dump_json(by_alias=True) emits the right key.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
scripts/mcp_full_smoke.py exercises every implemented tool end-to-end
against a live Credits node:
- All 4 diag, 4 monitor read-only, monitor_wait_for_smart_transaction,
  both userfields, all 4 transaction (pack→sign→execute→info→result),
  and 8 smartcontract tools (compile, pack/deploy/execute, get, methods
  by-address and by-bytecode, state, list_by_wallet).
- Tools that depend on optional state (a token in the wallet, a node
  that supports WaitForBlock long-poll, a node Thrift schema matching
  gen-py for SC Deploy/Execute) report SKIP with the underlying reason
  rather than FAIL, so the report distinguishes MCP issues from
  node-side limitations.
- "Transaction has been seen before" on re-runs (duplicate innerId)
  is treated as conditional PASS — the pipeline reached the node.

Verified: 23 PASS / 0 FAIL / 8 SKIP on the project's Credits node.

.gitignore: add .env.smoke and *.smoke.log so secrets used by the
smoke (sender private key, receiver public key) never get committed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brings the baba-credits MCP server, skill, deployment configs, drift
tests, and on-chain smoke fixes onto main.

Highlights:
- New baba_mcp/ package: 29 MCP tools (monitor, transaction, tokens,
  smartcontract, userfields, diag) registered as a single list_tools/
  call_tool pair on the MCP server (avoids the per-module decorator
  overwrite that limited runtime to 4 tools).
- New .claude/skills/baba-credits/ skill (SKILL.md + tools-reference +
  6 recipes + 2 signing snippets + troubleshooting).
- Deployment: ecosystem.config.js (pm2 bundle gateway + mcp-http),
  .env.mcp.example, README MCP section.
- CI: Python 3.11 step compileall + MCP unit tests + skill-drift test.
- Gateway hardening from on-chain smoke: userData decode None-safety,
  TransactionResult innerId lookup, ReceiverPublicKey/address aliases on
  SC and wait-for-smart-transaction endpoints, deeper exception logging.
- scripts/mcp_full_smoke.py exercises every implemented tool against a
  live node; run reports 23 PASS / 0 FAIL / 8 SKIP (SKIPs are node-side
  limitations, not MCP issues).

Test suite: 121 passed, 0 skipped (was 113 + 1 skipped before gen-py
became locally available).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…connects

The Credits node accepts SmartContract Deploy and Execute transactions and
seals them within ~5 seconds, but in this deployment it consistently closes
the Thrift connection BEFORE returning the TransactionFlow response. The
gateway was raising the resulting TTransportException as a 400 error to
the caller, even though the on-chain transaction had succeeded — verified
in the node debug.log with "Smart: <addr> state is updated by {<seq>.<idx>}"
entries that match the gateway-issued requests.

Fix: in _execute_smart_tx (used by both /SmartContract/Deploy and
/SmartContract/Execute), wrap client.TransactionFlow(tx) in an inner
try/except. On any exception, close the broken transport, then poll
TransactionsGet(source) every 1s for up to 15s looking for a sealed
SealedTransaction whose trxn.id == our innerId. When found, format the
"<poolSeq>.<idx>" tx id and return success=true. Only re-raise the
original error if polling times out.

Validated against the live node: smartcontract_deploy and
smartcontract_execute now PASS end-to-end with real on-chain transaction
ids returned to the MCP layer.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds concrete configuration recipes for plugging the baba-credits MCP
server into common AI agents:

- Transport choice (stdio vs HTTP/SSE) with guidance on when to use each.
- Signing material setup: env-var pattern (BABA_PUBLIC_KEY/PRIVATE_KEY)
  for CLI/batch agents, vs keystore-backed signing for smart wallets,
  with explicit warning never to send the private key to the MCP/gateway.
- Per-client config snippets:
  - Claude Code (.mcp.json at repo root)
  - Claude Desktop (claude_desktop_config.json on macOS/Windows/Linux)
  - Cline / Cursor (same shape as Claude Code)
  - HTTP/SSE for remote agents (pm2 + MCP_AUTH_TOKEN + Nginx/TLS)
  - Custom Python agent (mcp.client.session over SSE or stdio)
- Verification step (ask the agent for a balance, then a 0.001 CS transfer)
  pointing at scripts/mcp_full_smoke.py for the full coverage check.
- Tool catalogue table by category.
- Updated security notes (private-key hygiene, destructiveHint annotations).
- Troubleshooting links to the skill, plus the three known node-side
  limitations that may surface on consensus-producer-only nodes:
  tokens_* requiring monitor API, monitor_wait_for_block long-poll, and
  the SmartContract Deploy/Execute Thrift early-disconnect (which the
  gateway already recovers from via TransactionsGet polling).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
… fixes

Brings in 5 commits from molaanaa/baba-node-api that landed after our
PR #1 was merged:
- f09fa66 Update README.md
- ae5f4f9 fix: convert JSON params to Thrift Variant before Pack signing
- 23fba1a test: add Variant stub for build_smart_invocation test
- 6604e21 fix: correct indentation in test stub Variant class
- ed7011f fix: indent pass in test Variant stub

Auto-merge clean across README.md, services/contracts.py, tests/test_contracts.py.
Test suite stays green: 121 passed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
PR molaanaa#2 surfaced a CI failure on the Python 3.8 matrix entry: the existing
"Install Python deps" step does `pip install -r requirements-dev.txt`,
which transitively pulls `mcp>=1.0.0` from requirements.txt — but the
`mcp` package only ships wheels for Python 3.10+, so pip aborts with
"No matching distribution found for mcp>=1.0.0".

Two changes, both keeping the gateway-only matrix entry green:

1. requirements.txt: add `python_version >= "3.10"` markers on `mcp`,
   `httpx`, and `pydantic`. pip now silently skips them on 3.8 instead
   of failing the install step. The gateway runtime never imports any
   of these (they're only used by baba_mcp/), so this is safe.

2. .github/workflows/ci.yml: split the "Run pytest" step in two —
   a gateway-only run on the 3.8 matrix entry (skips test_mcp_*.py and
   test_skill_drift.py via --ignore-glob), and a full-suite run on the
   3.11 entry. Removed the now-redundant "MCP unit tests" step that
   duplicated coverage already provided by the full 3.11 run.

Local sanity:
- gateway-only collection on 3.8 simulation: 63 tests collected.
- full suite on 3.11: 121 passed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@molaanaa
molaanaa merged commit b18bb37 into molaanaa:main Apr 29, 2026
2 checks passed
EnzinoBB added a commit to EnzinoBB/baba-node-api that referenced this pull request Apr 30, 2026
molaanaa added a commit that referenced this pull request Apr 30, 2026
feat: post-PR-#2 hardening — public MCP exposure, SC observability, ordinals naming
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants