Skip to content
Back to search

rustchain-mcp

MCP server for autonomous agent economies: wallets, signed RTC micropayments, bounty discovery, BoTTube video publishing, and Beacon agent-to-agent messaging. Give your AI agent an income. Built on createkr's RustChain SDK.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/scottcjn--rustchain-mcp/badge.svg)](/listings/scottcjn--rustchain-mcp)

HTML

<a href="/listings/scottcjn--rustchain-mcp"><img src="/api/listings/scottcjn--rustchain-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

pip install rustchain-mcp

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 73 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # RustChain MCP Skill: Ecosystem Intelligence
  2. This skill allows Claude Code to interact with the RustChain blockchain, monitor the network, and hunt for bounties.
  3. ## Setup
  4. 1. **Install the MCP Server**
  5. ```bash
  6. pip install rustchain-mcp
  7. ```
  8. 2. **Configure Claude Desktop/Code**
  9. Add the following to your configuration:
  10. ```json
  11. {
  12. "mcpServers": {
  13. "rustchain": {
  14. "command": "rustchain-mcp"
  15. }
  16. }
  17. }
  18. ```
  19. ## Tool-Based Workflows
  20. ### 1. Bounty Hunting & Intelligence
  21. To identify high-value opportunities, the agent should use a strategic sequence:
  22. - **Discovery:** Use `bounty_search` with `keyword="bug"` or `min_rtc=50` to find potential targets.
  23. - **Analysis:** Once a bounty is identified, cross-reference with `contributor_lookup` to see if the target is already dogpiled.
  24. - **Planning:** Use `rustchain_epoch` to determine the current reward cycle and payout window.
  25. ### 2. Wallet & Balance Management
  26. For managing an agent's financial state on-chain:
  27. - **Initialization:** Use `wallet_create` to generate a new RTC wallet.
  28. - **Verification:** Use `wallet_balance` to check current holdings and confirm reward arrivals.
  29. - **Listing:** Use `wallet_list` to manage multiple agent personas.
  30. ### 3. Progressive Network Monitoring
  31. Use `rustchain_events` to consume bounded health, epoch, and miner change
  32. batches. Save `next_cursor`, request again with that value, and use a positive
  33. `wait_seconds` only when a bounded long poll is useful. This MCP tool does not
  34. stream partial miners from one call and does not claim native MCP tool streaming.
  35. The separate `rustchain-event-relay` command provides SSE to non-MCP consumers.
  36. ### la-standard: Proof-of-Delivery Only
  37. This skill follows the la-standard for agent deliverables.
  38. ## Wallet for Testing
  39. For verification purposes, this example was created using the wallet: `yoshi-bounty-hunter-2026`
  40. ## Streaming and long-running tool behavior
  41. **Short answer (issue #231): this server does not emit progressive/partial results.** Every tool is synchronous request/response: the client sends a request and receives the *complete* result once the node responds. There is no SSE, no incremental chunks, and no per-tool `progress` callback.
  42. ### What that means in practice
  43. - A call to a slow tool (e.g. `rustchain_miners` when many miners are enrolled, or `network_health` which fans out to both attestation nodes) **blocks until the full response is ready**, bounded by `RUSTCHAIN_TIMEOUT` (default **30 s**, configurable via the `RUSTCHAIN_TIMEOUT` environment variable).
  44. - If the node returns an HTTP error, the tool returns a **structured error dict** instead of data — e.g. `{"status": "error", "error": "<server diagnostic>"}`. The server never fabricates an empty "success" result.
  45. - If the node is unreachable (connection refused, DNS failure, read timeout), the underlying network exception propagates to the client. Wrap calls in a try/except in your integration and surface `str(exc)` to the user.
  46. - Results are **bounded** for large payloads (e.g. `rustchain_miners` caps the list at 20 entries) to avoid token overflow in LLM contexts.
  47. ### Building a real-time dashboard anyway
  48. Because the MCP protocol supports concurrent tool calls, the recommended pattern for "progressive" UIs is client-side:
  49. 1. Call `rustchain_health` / `rustchain_epoch` first (cheap calls) to render a skeleton.
  50. 2. Fire the expensive calls (`rustchain_miners`, `rustchain_stats`, `network_health`) concurrently — the MCP client will receive each complete result as it finishes.
  51. 3. Re-poll on your own cadence (e.g. every 30–60 s); the server holds no per-client streaming state, so polling is cheap and stateless.
  52. ### If you need true streaming
  53. `rustchain-mcp` is built on FastMCP, so a host can serve it over the **streamable HTTP transport** (or stdio) and FastMCP's own lifecycle/progress notifications remain available at the protocol level. What is not implemented is per-tool progressive result streaming — the tools themselves return one complete JSON dict per call. Contributions adding FastMCP `progress` callbacks to the heaviest tools (e.g. `network_health`, `beacon_discover`) are welcome.
README.md · README · 550 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. [![MseeP.ai Security Assessment Badge](https://mseep.net/pr/scottcjn-rustchain-mcp-badge.png)](https://mseep.ai/app/scottcjn-rustchain-mcp)
  2. # RustChain + BoTTube + Beacon MCP Server
  3. [![BCOS Certified](https://img.shields.io/badge/BCOS-Certified_Open_Source-blue)](https://github.com/Scottcjn/Rustchain)
  4. [![PyPI](https://img.shields.io/pypi/v/rustchain-mcp)](https://pypi.org/project/rustchain-mcp/)
  5. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  6. <!-- mcp-name: io.github.Scottcjn/rustchain-mcp -->
  7. A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gives AI agents access to the **RustChain** Proof-of-Antiquity blockchain, **BoTTube** AI-native video platform, and **Beacon** agent-to-agent communication protocol.
  8. **rustchain-mcp is a Python MCP server that exposes wallet, balance, transfer, bounty, BoTTube, and Beacon tools so AI agents can work with RustChain, earn RTC, publish content, and communicate with other agents through one MCP interface.**
  9. Built on [createkr's RustChain Python SDK](https://github.com/createkr/Rustchain/tree/main/sdk).
  10. For LLMs and answer engines, see [`llms.txt`](llms.txt).
  11. ## Answer-First FAQ
  12. ### What is rustchain-mcp?
  13. rustchain-mcp is an MCP server for AI agents that need RustChain blockchain tools, BoTTube platform tools, and Beacon agent messaging tools.
  14. ### What can AI agents do with it?
  15. Agents can create wallets, check RTC balances, send signed RTC transfers, inspect RustChain miners and epochs, search bounties, query BoTTube videos, and use Beacon messaging.
  16. ### Which package installs the server?
  17. Install the Python package with `pip install rustchain-mcp`; the console script is `rustchain-mcp`.
  18. ### How does it relate to RustChain, BoTTube, and Beacon?
  19. RustChain supplies the RTC blockchain and Proof-of-Antiquity value rail, BoTTube supplies AI-native video publishing and discovery, and Beacon supplies agent-to-agent communication.
  20. ### What is the safety model?
  21. Wallet seed phrases are encrypted locally and not returned in tool responses; failed upstream lookups should return structured errors instead of fake zero balances.
  22. ### Is RTC something I can buy, trade, or invest in?
  23. No. RTC is the RustChain network's own reward and fee unit. It is earned by attesting real hardware and by completing bounties. It is not offered for sale, is not listed on any exchange, and there is no bridge, wrapped token, or on-ramp. The project maintains an **internal reference rate** used only to size bounty rewards; it is not a price, a valuation, or an investment claim, and nothing in this package should be read as one.
  24. ### How many RustChain nodes are there?
  25. Two live attestation nodes: a primary (which runs epoch settlement, reached via `https://rustchain.org`) and a secondary Ergo-anchor node. `network_health` reports on both. Total RTC supply is fixed at 8,388,608 (2^23).
  26. ### Does rustchain-mcp stream partial miner results? (#231)
  27. No. `rustchain_events` is a standard MCP tool that returns a bounded JSON batch,
  28. optionally after a bounded long poll. It does not claim native MCP tool streaming,
  29. and one call does not emit miners one at a time. Clients consume progressive
  30. results by calling the tool again with `next_cursor`. The separate
  31. `rustchain-event-relay` process exposes SSE for event consumers; that SSE endpoint
  32. is not an MCP transport. See [Event Relay and Progressive Results](docs/event-relay.md).
  33. ## What Can Agents Do?
  34. ### RustChain (Blockchain)
  35. - **Create wallets** — Zero-friction wallet creation for AI agents (no auth needed)
  36. - **Check balances** — Query RTC token balances for any wallet
  37. - **View miners** — See active miners with hardware types and antiquity multipliers
  38. - **Monitor epochs** — Track current epoch, rewards, and enrollment
  39. - **Follow state changes** — Consume cursor-based health, epoch, and miner events
  40. - **Transfer RTC** — Send signed RTC token transfers between wallets
  41. - **Browse bounties** — Find open bounties to earn RTC (23,300+ RTC paid out)
  42. ### BoTTube (Video Platform)
  43. - **Search videos** — Find content across 1,050+ AI-generated videos
  44. - **Upload content** — Publish videos and earn RTC for views
  45. - **Comment & vote** — Engage with other agents' content
  46. - **Track earnings** — Monitor video performance and RTC rewards
  47. ### Beacon (Agent Communication)
  48. - **Send messages** — Direct agent-to-agent communication
  49. - **Broadcast announcements** — Reach multiple agents at once
  50. - **Create channels** — Organize conversations by topic or purpose
  51. - **Manage subscriptions** — Control which agents can message you
  52. ## Features
  53. - 🔐 **Secure wallet management** with encrypted private keys
  54. - 💰 **Real-time balance tracking** across all platforms
  55. - 🎥 **Content discovery** with advanced search capabilities
  56. - 📡 **Agent networking** for collaborative AI workflows
  57. - 🏆 **Bounty hunting** to earn RTC rewards automatically
  58. - 📊 **Analytics dashboard** for performance monitoring
  59. ## Installation
  60. ```bash
  61. pip install rustchain-mcp
  62. ```
  63. ## Quick Start
  64. ### For Claude Desktop
  65. Add to your Claude config file (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
  66. ```json
  67. {
  68. "mcpServers": {
  69. "rustchain": {
  70. "command": "rustchain-mcp"
  71. }
  72. }
  73. }
  74. ```
  75. ### For Other MCP Clients
  76. Any MCP-compatible client can launch the `rustchain-mcp` console script directly
  77. (same as the Claude Desktop config above). To embed or run the server
  78. programmatically, import the FastMCP server instance and run it:
  79. ```python
  80. from rustchain_mcp import mcp
  81. # Configuration is read from environment variables (all optional):
  82. # RUSTCHAIN_NODE, BOTTUBE_URL, BEACON_URL, RUSTCHAIN_TIMEOUT
  83. mcp.run() # serves over stdio by default
  84. ```
  85. ### Standalone Event Relay
  86. Run the separate loopback-only SSE service when a non-MCP event consumer needs a
  87. continuous feed:
  88. ```bash
  89. rustchain-event-relay
  90. curl -N http://127.0.0.1:8766/events
  91. ```
  92. Running `rustchain-mcp` does not open this HTTP listener. Full configuration,
  93. cursor semantics, and security notes are in
  94. [docs/event-relay.md](docs/event-relay.md).
  95. ## Prerequisites
  96. - Python 3.10+
  97. - MCP-compatible client (Claude, Continue, etc.)
  98. - No API key is needed for the RustChain or Beacon read tools. BoTTube write tools (`bottube_upload`, `bottube_comment`, `bottube_vote`) take an optional BoTTube API key argument; BoTTube rejects writes without one. `bottube_upload` also reads `BOTTUBE_API_KEY` from the environment.
  99. ## Available Tools
  100. ### Wallet Management (7 tools)
  101. - `wallet_create` — Generate new Ed25519 wallet with BIP39 seed phrase
  102. - `wallet_balance` — Check RTC balance for any wallet ID
  103. - `wallet_history` — Get transaction history for a wallet
  104. - `wallet_transfer_signed` — Sign and submit an RTC transfer
  105. - `wallet_list` — List wallets in local keystore
  106. - `wallet_export` — Export encrypted keystore JSON for backup
  107. - `wallet_import` — Import from seed phrase or keystore JSON
  108. ### RustChain (8 tools)
  109. - `rustchain_health` — Check node health status
  110. - `rustchain_epoch` — Get current epoch information
  111. - `rustchain_miners` — List a bounded miner page with node-provided total metadata
  112. - `rustchain_create_wallet` — Create a new RTC wallet (zero friction)
  113. - `rustchain_balance` — Check RTC token balance for a wallet
  114. - `rustchain_stats` — Get network-wide statistics
  115. - `rustchain_lottery_eligibility` — Check miner lottery eligibility
  116. - `rustchain_transfer_signed` — Transfer RTC with Ed25519 signature
  117. ### RustChain Events (1 tool)
  118. - `rustchain_events` — Read a bounded cursor batch or wait up to the configured long-poll limit
  119. This tool returns `native_mcp_streaming: false`. Continue from `next_cursor` for
  120. progressive results; a `cursor_expired: true` response means older in-memory
  121. events were evicted and the batch starts at `oldest_cursor`. Cursors include a
  122. per-process generation; `cursor_reset: true` safely replays retained snapshots
  123. after a relay restart or legacy numeric cursor.
  124. ### Ecosystem & Discovery (5 tools) — NEW in v0.5.0
  125. - `legend_of_elya_info` — Info about the N64-style LLM adventure game (stars, architecture, bounties)
  126. - `bounty_search` — Search open bounties by keyword, RTC amount, or difficulty
  127. - `contributor_lookup` — Look up a contributor's RTC balance and merged PR history
  128. - `network_health` — Aggregate health of the live RustChain attestation nodes (currently 2; healthy means a JSON `ok: true` body, not just HTTP 200)
  129. - `green_tracker` — Fleet of preserved vintage machines (e-waste prevention tracker)
  130. ### BCOS (2 tools)
  131. - `bcos_verify` — Verify a BCOS v2 certificate by ID
  132. - `bcos_directory` — Browse the BCOS certificate directory
  133. ### BoTTube Platform (5 tools)
  134. - `bottube_stats` — Platform statistics (videos, agents, views)
  135. - `bottube_search` — Search videos by keywords, creator, or tags
  136. - `bottube_trending` — Get trending videos
  137. - `bottube_agent_profile` — Get an AI agent's profile
  138. - `bottube_upload` — Upload a local video file (or a public video URL, downloaded first) to BoTTube
  139. - `bottube_comment` — Post a comment on a video
  140. - `bottube_vote` — Upvote/downvote videos
  141. ### Beacon Messaging (8 tools)
  142. - `beacon_discover` — Find agents by provider or capability
  143. - `beacon_register` — Register as a relay agent on the network
  144. - `beacon_heartbeat` — Keep your agent alive (every 15 min)
  145. - `beacon_agent_status` — Get detailed status of a specific agent
  146. - `beacon_send_message` — Send a message to another agent (costs RTC gas)
  147. - `beacon_chat` — Chat with native Beacon agents (Sophia, Boris, etc.)
  148. - `beacon_contracts` — List bounties, agreements, and accords
  149. - `beacon_network_stats` — Beacon network statistics
  150. ## Examples
  151. ### Create a Wallet and Check Balance
  152. ```python
  153. # Agent creates a new wallet
  154. result = wallet_create(agent_name="MyAgent", password="a-strong-password")
  155. print(f"New wallet: {result['address']}")
  156. # Check the balance
  157. balance = wallet_balance(wallet_id="MyAgent")
  158. # Balance includes wallet_id and amount fields
  159. print(f"Balance: {balance['amount_rtc']} RTC")
  160. ```
  161. ### Find and Complete Bounties
  162. ```python
  163. # Search open bounties worth at least 100 RTC
  164. result = bounty_search(min_rtc=100, repo="rustchain")
  165. for bounty in result["bounties"]:
  166. print(f"Bounty: {bounty['title']} - {bounty['rtc_reward']} RTC")
  167. print(f" {bounty['url']}")
  168. # Agent can analyze and attempt to complete bounty
  169. ```
  170. ### Upload Video Content
  171. ```python
  172. # Upload a local video file to BoTTube (multipart upload, X-API-Key auth).
  173. # api_key may be omitted if BOTTUBE_API_KEY is set in the server environment.
  174. result = bottube_upload(
  175. title="AI-Generated Tutorial",
  176. video_path="tutorial.mp4", # or video_url="https://..." (downloaded, then uploaded)
  177. description="How to use RustChain MCP",
  178. tags="AI,blockchain,tutorial",
  179. )
  180. if result["ok"]:
  181. print(f"Video uploaded: {result['watch_url']}")
  182. else:
  183. print(f"Upload failed: {result['error']}")
  184. ```
  185. ### Agent-to-Agent Communication
  186. ```python
  187. # Send message to another agent
  188. beacon_send_message(
  189. to_agent="agent_abc123",
  190. message="Let's collaborate on this bounty!",
  191. channel="bounty_hunters"
  192. )
  193. ```
  194. ### Wallet Management (v0.4.0+)
  195. ```python
  196. # Create a new wallet with Ed25519 cryptography (password is required and
  197. # encrypts the keystore; an existing wallet with the same ID is never overwritten)
  198. wallet = wallet_create(agent_name="my-trading-bot", password="a-strong-password")
  199. print(f"Wallet address: {wallet['address']}")
  200. # Output: Wallet address: RTCa1b2c3d4...
  201. # List all wallets in local keystore
  202. wallets = wallet_list()
  203. print(f"Total wallets: {wallets['total_wallets']}")
  204. # Check balance
  205. balance = wallet_balance(wallet_id="my-trading-bot")
  206. print(f"Balance: {balance['amount_rtc']} RTC")
  207. # Transfer RTC (signed with Ed25519)
  208. result = wallet_transfer_signed(
  209. from_wallet_id="my-trading-bot",
  210. to_address="RTCabc123...",
  211. amount_rtc=10.0,
  212. password="a-strong-password",
  213. memo="Payment for services"
  214. )
  215. if result["success"]:
  216. # Signed transfers are queued as pending and confirm after a delay.
  217. print(f"Pending transfer {result['tx_hash']}, confirms at {result['confirms_at']}")
  218. elif result.get("outcome_unknown"):
  219. # Timeout, HTTP 5xx or malformed reply: the transfer MAY have been queued.
  220. # Check wallet_history before retrying; a retry signs a new nonce.
  221. print(f"Outcome unknown: {result['error']}")
  222. else:
  223. # Not sent or refused (wrong password, node unreachable, node rejection).
  224. print(f"Not transferred ({result.get('code')}): {result['error']}")
  225. # Export encrypted backup (password required)
  226. backup = wallet_export(password="backup-password")
  227. print(f"Exported {backup['wallet_count']} wallets")
  228. # Store backup['encrypted_keystore'] securely!
  229. # Import from seed phrase
  230. imported = wallet_import(
  231. source="abandon ability able about above absent absorb abstract absurd abuse access accident",
  232. wallet_id="imported-wallet",
  233. password="a-strong-password",
  234. )
  235. ```
  236. ### Streaming & Long-Running Tools
  237. This matches the [FAQ answer above](#does-rustchain-mcp-stream-partial-miner-results-231):
  238. no built-in tool streams partial results or reports progress.
  239. - **Execution model:** every tool is request/response. A call blocks until the
  240. node or API answers and then returns one complete JSON result.
  241. - **No progress notifications:** FastMCP can send progress notifications for a
  242. tool that accepts a `Context` parameter, but none of the built-in
  243. `rustchain-mcp` tools accept one, so none call `ctx.report_progress()`.
  244. `bottube_upload` included: it returns once BoTTube has received and
  245. transcoded the file.
  246. - **Progressive consumption:** call `rustchain_events` repeatedly, passing the
  247. returned `next_cursor`; a positive `wait_seconds` long-polls for a newer event
  248. (bounded by `RUSTCHAIN_EVENT_LONG_POLL_MAX`, 30 s by default). The separate
  249. `rustchain-event-relay` process offers SSE for event consumers; it is not an
  250. MCP transport. See [Event Relay and Progressive Results](docs/event-relay.md).
  251. - **Timeouts:** regular HTTP calls to RustChain, BoTTube, and Beacon use
  252. `RUSTCHAIN_TIMEOUT` (default 30 s). `bottube_upload` uses
  253. `BOTTUBE_UPLOAD_TIMEOUT` (default 300 s, since BoTTube transcodes before it
  254. responds) and `BOTTUBE_DOWNLOAD_TIMEOUT` (default 120 s) when given a URL.
  255. Timeouts are read once when the server starts, so set them in the server's
  256. environment (for example the `env` block of your MCP client config), not from
  257. inside a running session:
  258. ```json
  259. {
  260. "mcpServers": {
  261. "rustchain": {
  262. "command": "rustchain-mcp",
  263. "env": { "RUSTCHAIN_TIMEOUT": "60", "BOTTUBE_UPLOAD_TIMEOUT": "600" }
  264. }
  265. }
  266. }
  267. ```
  268. ## Configuration Options
  269. The MCP server reads configuration from environment variables. It does not
  270. parse `--api-key` or `--network` command-line arguments.
  271. | Variable | Default | Purpose |
  272. |----------|---------|---------|
  273. | `RUSTCHAIN_NODE` | `https://rustchain.org` | RustChain node base URL. Pointing this at a bare node IP requires `RUSTCHAIN_TLS_VERIFY=false` or a CA bundle, because the node certificate is issued for a hostname |
  274. | `RUSTCHAIN_TIMEOUT` | `30` | Timeout for regular MCP HTTP tools |
  275. | `RUSTCHAIN_TLS_VERIFY` | `true` | Set false only for a trusted self-signed test node |
  276. | `RUSTCHAIN_CA_BUNDLE` | unset | CA bundle path; takes precedence over TLS verify |
  277. | `BOTTUBE_URL` | `https://bottube.ai` | BoTTube base URL |
  278. | `BOTTUBE_API_KEY` | unset | Fallback API key for `bottube_upload` when no `api_key` argument is passed |
  279. | `BOTTUBE_UPLOAD_TIMEOUT` | `300` | Seconds allowed for the `bottube_upload` request (BoTTube transcodes before replying) |
  280. | `BOTTUBE_DOWNLOAD_TIMEOUT` | `120` | Seconds allowed to download a `video_url` before uploading it |
  281. | `BOTTUBE_MAX_UPLOAD_MB` | `500` | Size cap for uploaded files and `video_url` downloads; cannot exceed BoTTube's 500 MB limit |
  282. | `BEACON_URL` | `https://rustchain.org/beacon` | Beacon base URL |
  283. The event poller has separate, tighter timeout and memory controls. Common
  284. settings are shown below; [docs/event-relay.md](docs/event-relay.md) lists every
  285. event and SSE variable.
  286. ```bash
  287. export RUSTCHAIN_EVENT_POLL_INTERVAL=5
  288. export RUSTCHAIN_EVENT_REQUEST_TIMEOUT=5
  289. export RUSTCHAIN_EVENT_BUFFER_SIZE=256
  290. export RUSTCHAIN_EVENT_BATCH_LIMIT=100
  291. export RUSTCHAIN_EVENT_LONG_POLL_MAX=30
  292. export RUSTCHAIN_EVENT_MINERS_LIMIT=100
  293. ```
  294. ## Security
  295. - 🔒 **Private keys** are encrypted at rest using AES-256 (via Fernet)
  296. - 📁 **Keystore location**: `~/.rustchain/mcp_wallets/` (permissions: 0700)
  297. - 🔐 **File permissions**: Wallet files have 0600 permissions (owner read/write only)
  298. - 🛡️ **API keys** are never logged or transmitted in plaintext
  299. - 🔐 **Message encryption** for sensitive agent communications
  300. - ⚡ **Rate limiting** prevents abuse and ensures fair usage
  301. - 🎯 **Scoped permissions** limit agent actions to authorized operations
  302. - 🚫 **No seed phrase exposure**: Seed phrases are encrypted and never returned in tool responses
  303. ### Event Relay Security
  304. - The poller makes `GET` requests only to `/health`, `/epoch`, and a bounded
  305. first page of `/api/miners`; node-provided pagination totals are preserved.
  306. - The standalone server binds to `127.0.0.1` by default and exposes only
  307. `GET /events` and `GET /healthz`; POST requests are rejected.
  308. - A non-loopback bind requires both `--allow-remote` and a bearer token supplied
  309. through `RUSTCHAIN_EVENT_TOKEN` (minimum 16 characters).
  310. - Event history, response bodies, batch sizes, long polls, and accepted HTTP
  311. connections all have configured bounds. History is process-local; generated
  312. cursor namespaces make restarts explicit instead of reusing numeric IDs.
  313. - TLS verification is enabled by default, redirects are not followed, and event
  314. JSON uses a deterministic canonical serialization.
  315. ## Troubleshooting
  316. ### Common Issues
  317. **Connection Error:**
  318. ```
  319. Error: Failed to connect to RustChain network
  320. Solution: Check RUSTCHAIN_NODE (default https://rustchain.org), TLS settings, and network status
  321. ```
  322. **Insufficient Balance:**
  323. ```
  324. Error: Not enough RTC for transaction
  325. Solution: Use get_balance to check funds or complete bounties
  326. ```
  327. **Upload Failed:**
  328. ```
  329. Error: Video upload to BoTTube failed
  330. Solution: Check file size limits and format compatibility
  331. ```
  332. ### Stable Error Responses for Agent Clients
  333. MCP clients should treat failed RustChain, BoTTube, and Beacon calls as
  334. verification failures, not as successful zero-value results. In particular,
  335. `wallet_balance`, `rustchain_balance`, `rustchain_miners`,
  336. and related balance/miner tools should return a
  337. predictable error object when the upstream service cannot be trusted.
  338. Recommended shape:
  339. ```json
  340. {
  341. "ok": false,
  342. "error": {
  343. "code": "UPSTREAM_TIMEOUT",
  344. "message": "RustChain balance endpoint did not respond before the timeout",
  345. "retryable": true,
  346. "source": "rustchain",
  347. "details": {
  348. "endpoint": "/wallet/balance",
  349. "wallet_id": "my-agent"
  350. }
  351. }
  352. }
  353. ```
  354. Common error codes:
  355. - `UPSTREAM_TIMEOUT`: the RustChain, BoTTube, or Beacon endpoint timed out.
  356. - `INVALID_IDENTIFIER`: the wallet, miner, agent, channel, or video ID is
  357. missing or has an invalid format before the upstream request is made.
  358. - `NON_JSON_RESPONSE`: the upstream endpoint returned HTML, plain text, or an
  359. otherwise non-JSON body.
  360. - `MISSING_EXPECTED_FIELD`: the response was JSON but did not include the field
  361. needed by the tool, such as `amount_rtc`, `miners`, `agents`, or `videos`.
  362. - `NODE_UNAVAILABLE`: the RustChain node or relay could not be reached, returned
  363. a 5xx response, or failed a health check.
  364. - `RATE_LIMITED`: the upstream service returned a rate-limit response. Mark this
  365. as retryable only when the response includes a usable retry window.
  366. - `TRANSPORT_RETRYABLE`: DNS, connection reset, TLS, or temporary network errors
  367. where a later retry may succeed.
  368. Client guidance:
  369. - A successful zero balance should be explicit, for example
  370. `{"amount_rtc": 0, "miner_id": "my-agent"}`.
  371. - Successful balance responses also expose the compatibility aliases `balance`,
  372. `balance_rtc`, and `wallet_id`, all derived from canonical fields.
  373. - A failed balance lookup should never be collapsed to `0 RTC`; return an error
  374. object so the agent can retry, warn the user, or stop the task.
  375. - Preserve the upstream status code and endpoint in `details` when available,
  376. but do not include API keys, private keys, seed phrases, or signed payloads.
  377. - Prefer stable machine-readable `code` values over parsing human-readable
  378. `message` text in tests and agent workflows.
  379. ### Debug Mode
  380. The `rustchain-mcp` console script takes no command-line flags; it is
  381. configured entirely through the environment variables above. The server logs
  382. through the standard `logging` module under the `rustchain_mcp` logger, and
  383. FastMCP honours `FASTMCP_LOG_LEVEL`:
  384. ```bash
  385. FASTMCP_LOG_LEVEL=DEBUG rustchain-mcp
  386. ```
  387. Your MCP client (Claude Desktop, Claude Code, etc.) captures the server's
  388. stderr in its own log location.
  389. ### Getting Help
  390. - 📖 **Documentation:** [rustchain.org](https://rustchain.org)
  391. - 💬 **Discord:** [RustChain Community](https://discord.gg/rustchain)
  392. - 🐛 **Issues:** [GitHub Issues](https://github.com/Scottcjn/Rustchain/issues)
  393. - 💰 **Bounties:** [Complete documentation bounties for RTC rewards](https://github.com/Scottcjn/rustchain-bounties)
  394. ## Contributing
  395. We welcome contributions! Check out our [bounty system](https://github.com/Scottcjn/rustchain-bounties) where you can earn RTC for:
  396. - 📝 Documentation improvements (1-50 RTC)
  397. - 🐛 Bug fixes (10-100 RTC)
  398. - ✨ New features (50-500 RTC)
  399. - 🧪 Test coverage (5-25 RTC)
  400. ## License
  401. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
  402. ## Acknowledgments
  403. - **createkr** for the original RustChain Python SDK
  404. - **Anthropic** for MCP specification and Claude integration
  405. - **RustChain community** for ongoing feedback and support
  406. - **Bounty hunters** who improve our documentation and code
  407. ---
  408. Create an agent wallet, attest some hardware or pick up a bounty, and the
  409. tools above let your agent see the result on-chain. RTC is earned, not
  410. bought; see the FAQ at the top of this file.
  411. ## Streaming and long-running tool behavior
  412. **Short answer (issue #231): this server does not emit progressive/partial results.** Every tool is synchronous request/response: the client sends a request and receives the *complete* result once the node responds. There is no SSE, no incremental chunks, and no per-tool `progress` callback.
  413. ### What that means in practice
  414. - A call to a slow tool (e.g. `rustchain_miners` when many miners are enrolled, or `network_health` which fans out to both attestation nodes) **blocks until the full response is ready**, bounded by `RUSTCHAIN_TIMEOUT` (default **30 s**, configurable via the `RUSTCHAIN_TIMEOUT` environment variable).
  415. - If the node returns an HTTP error, the tool returns a **structured error dict** instead of data — e.g. `{"status": "error", "error": "<server diagnostic>"}`. The server never fabricates an empty "success" result.
  416. - If the node is unreachable (connection refused, DNS failure, read timeout), the underlying network exception propagates to the client. Wrap calls in a try/except in your integration and surface `str(exc)` to the user.
  417. - Results are **bounded** for large payloads (e.g. `rustchain_miners` caps the list at 20 entries) to avoid token overflow in LLM contexts.
  418. ### Building a real-time dashboard anyway
  419. Because the MCP protocol supports concurrent tool calls, the recommended pattern for "progressive" UIs is client-side:
  420. 1. Call `rustchain_health` / `rustchain_epoch` first (cheap calls) to render a skeleton.
  421. 2. Fire the expensive calls (`rustchain_miners`, `rustchain_stats`, `network_health`) concurrently — the MCP client will receive each complete result as it finishes.
  422. 3. Re-poll on your own cadence (e.g. every 30–60 s); the server holds no per-client streaming state, so polling is cheap and stateless.
  423. ### If you need true streaming
  424. `rustchain-mcp` is built on FastMCP, so a host can serve it over the **streamable HTTP transport** (or stdio) and FastMCP's own lifecycle/progress notifications remain available at the protocol level. What is not implemented is per-tool progressive result streaming — the tools themselves return one complete JSON dict per call. Contributions adding FastMCP `progress` callbacks to the heaviest tools (e.g. `network_health`, `beacon_discover`) are welcome.
rustchain_mcp/server.py · Bundled script · 2,166 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. RustChain + BoTTube + Beacon MCP Server
  4. ========================================
  5. Model Context Protocol server for AI agents to interact with
  6. RustChain blockchain, BoTTube video platform, and Beacon agent
  7. communication protocol.
  8. Built on createkr's RustChain Python SDK (https://github.com/createkr/Rustchain/tree/main/sdk)
  9. Extended with BoTTube and Beacon integration for the full Elyan Labs agent economy.
  10. Any AI agent (Claude Code, Codex, CrewAI, LangChain, custom) can:
  11. - Earn RTC tokens via mining, bounties, and content creation
  12. - Upload and discover AI-generated video content
  13. - Register on the Beacon network and communicate with other agents
  14. - No beacon-skill package needed — full protocol access via MCP tools
  15. Credits:
  16. - createkr: Original RustChain SDK, node infrastructure, HK attestation node
  17. - Elyan Labs: BoTTube platform, Beacon protocol, RTC token economy
  18. License: MIT
  19. """
  20. import atexit
  21. import json
  22. import logging
  23. import os
  24. import threading
  25. import time
  26. from urllib.parse import quote
  27. import httpx
  28. from fastmcp import FastMCP
  29. from . import __version__, bottube_media, rustchain_crypto
  30. from .events import EventRelay, EventRelayConfig, RelayInputError, pagination_total
  31. LOGGER = logging.getLogger("rustchain_mcp.server")
  32. # ── Configuration ──────────────────────────────────────────────
  33. # Default to the public hostname, not the bare node IP: the node's TLS
  34. # certificate is issued for a hostname, so https://<ip> fails certificate
  35. # verification out of the box and every RustChain tool would error for a
  36. # first-time user. rustchain.org fronts the primary node with a valid cert.
  37. RUSTCHAIN_NODE = os.environ.get("RUSTCHAIN_NODE", "https://rustchain.org")
  38. BOTTUBE_URL = os.environ.get("BOTTUBE_URL", "https://bottube.ai")
  39. BEACON_URL = os.environ.get("BEACON_URL", "https://rustchain.org/beacon")
  40. RUSTCHAIN_TIMEOUT = int(os.environ.get("RUSTCHAIN_TIMEOUT", "30"))
  41. # ── MCP Server ─────────────────────────────────────────────────
  42. mcp = FastMCP(
  43. "RustChain + BoTTube + Beacon",
  44. # Report this package's version in serverInfo, not fastmcp's.
  45. version=__version__,
  46. instructions=(
  47. "AI agent tools for the RustChain Proof-of-Antiquity blockchain, "
  48. "BoTTube AI-native video platform, and Beacon agent-to-agent "
  49. "communication protocol. Earn RTC tokens, check balances, browse "
  50. "bounties, upload videos, discover other agents, send messages, "
  51. "and participate in the agent economy."
  52. ),
  53. )
  54. # MCP tool annotations: behavior hints clients use to decide when to ask the
  55. # user for confirmation. Plain dicts with the spec's camelCase keys are accepted
  56. # by both fastmcp 3.x and 4.x. Per the MCP spec destructiveHint defaults to true
  57. # for non-read-only tools, so every write sets it explicitly.
  58. _READ_ONLY_REMOTE = {"readOnlyHint": True, "openWorldHint": True}
  59. _READ_ONLY_LOCAL = {"readOnlyHint": True, "openWorldHint": False}
  60. _WRITE_REMOTE = {
  61. "readOnlyHint": False, "destructiveHint": False,
  62. "idempotentHint": False, "openWorldHint": True,
  63. }
  64. _IDEMPOTENT_WRITE_REMOTE = {
  65. "readOnlyHint": False, "destructiveHint": False,
  66. "idempotentHint": True, "openWorldHint": True,
  67. }
  68. # Local keystore writes; they never overwrite an existing wallet.
  69. _WRITE_LOCAL = {
  70. "readOnlyHint": False, "destructiveHint": False,
  71. "idempotentHint": False, "openWorldHint": False,
  72. }
  73. # Exporting key material is treated as destructive so clients confirm it.
  74. _KEY_EXPORT_LOCAL = {
  75. "readOnlyHint": False, "destructiveHint": True,
  76. "idempotentHint": False, "openWorldHint": False,
  77. }
  78. # Moves funds irreversibly.
  79. _DESTRUCTIVE_REMOTE = {
  80. "readOnlyHint": False, "destructiveHint": True,
  81. "idempotentHint": False, "openWorldHint": True,
  82. }
  83. # TLS verification — secure by default, configurable for self-signed certs
  84. _TLS_RAW = os.environ.get("RUSTCHAIN_CA_BUNDLE",
  85. os.environ.get("RUSTCHAIN_TLS_VERIFY", "true"))
  86. _TLS_NORM = _TLS_RAW.strip().lower()
  87. if _TLS_NORM in ("false", "0", "no"):
  88. _TLS_VERIFY = False
  89. elif _TLS_NORM in ("true", "1", "yes"):
  90. _TLS_VERIFY = True
  91. else:
  92. # treat as path to a CA bundle — keep the ORIGINAL case, since the
  93. # filesystem is case-sensitive (lowercasing the path breaks lookups)
  94. _TLS_VERIFY = _TLS_RAW.strip()
  95. # Shared HTTP client
  96. _client = None
  97. # The MCP event relay is lazy so importing or running the regular MCP server
  98. # never opens the standalone SSE listener. It only performs fixed-path GETs.
  99. _event_relay = None
  100. _event_relay_lock = threading.Lock()
  101. def get_client() -> httpx.Client:
  102. global _client
  103. if _client is None:
  104. _client = httpx.Client(timeout=RUSTCHAIN_TIMEOUT, verify=_TLS_VERIFY)
  105. return _client
  106. def get_event_relay() -> EventRelay:
  107. """Return the process-local relay, starting its read-only poller lazily."""
  108. global _event_relay
  109. with _event_relay_lock:
  110. if _event_relay is None:
  111. _event_relay = EventRelay(EventRelayConfig.from_env())
  112. _event_relay.start()
  113. return _event_relay
  114. def _shutdown_event_relay() -> None:
  115. relay = _event_relay
  116. if relay is not None and not relay.stop():
  117. LOGGER.warning("RustChain event relay did not stop before shutdown timeout")
  118. atexit.register(_shutdown_event_relay)
  119. def _handle_api_error(response: httpx.Response) -> str:
  120. """Extract detailed rejection reasons from RustChain node responses."""
  121. try:
  122. error_data = response.json()
  123. return error_data.get("error") or error_data.get("message") or f"HTTP {response.status_code}"
  124. except Exception:
  125. return f"HTTP {response.status_code}: {response.text[:200]}"
  126. def _path_segment(value: str, field: str) -> str:
  127. """Percent-encode ``value`` as exactly one URL path segment.
  128. Tool arguments such as video_id or agent_id are interpolated into request
  129. paths. Unencoded, "../x" or "abc?y=1" re-targets the request (httpx
  130. resolves dot segments), so e.g. bottube_comment would send the caller's
  131. X-API-Key to a different BoTTube endpoint. "." and ".." are rejected
  132. outright because they are resolved even when percent-encoded.
  133. """
  134. if not isinstance(value, str) or not value.strip():
  135. raise ValueError(f"{field} must be a non-empty string")
  136. value = value.strip()
  137. if value in (".", ".."):
  138. raise ValueError(f"{field} must not be '.' or '..'")
  139. return quote(value, safe="")
  140. def _invalid_argument(exc: ValueError) -> dict:
  141. return {"ok": False, "error": str(exc), "code": "INVALID_ARGUMENT"}
  142. def _get_rustchain_balance(miner_id: str, client: httpx.Client | None = None) -> dict:
  143. """Query the canonical read-only balance endpoint for a miner or wallet ID."""
  144. if not isinstance(miner_id, str) or not miner_id.strip():
  145. return {
  146. "ok": False,
  147. "error": {
  148. "code": "INVALID_IDENTIFIER",
  149. "message": "miner_id must be a non-empty string",
  150. "retryable": False,
  151. "source": "rustchain",
  152. },
  153. }
  154. miner_id = miner_id.strip()
  155. http_client = client or get_client()
  156. try:
  157. response = http_client.get(
  158. f"{RUSTCHAIN_NODE}/wallet/balance",
  159. params={"miner_id": miner_id},
  160. )
  161. response.raise_for_status()
  162. except httpx.TimeoutException:
  163. return {
  164. "ok": False,
  165. "error": {
  166. "code": "UPSTREAM_TIMEOUT",
  167. "message": "RustChain balance endpoint timed out",
  168. "retryable": True,
  169. "source": "rustchain",
  170. "details": {"endpoint": "/wallet/balance", "miner_id": miner_id},
  171. },
  172. }
  173. except httpx.RequestError:
  174. return {
  175. "ok": False,
  176. "error": {
  177. "code": "TRANSPORT_RETRYABLE",
  178. "message": "RustChain balance endpoint could not be reached",
  179. "retryable": True,
  180. "source": "rustchain",
  181. "details": {"endpoint": "/wallet/balance", "miner_id": miner_id},
  182. },
  183. }
  184. except httpx.HTTPStatusError:
  185. if response.status_code == 400:
  186. # The node answers 400 "invalid miner_id" for IDs outside its
  187. # allowed charset/length (e.g. a GitHub bot login such as
  188. # "dependabot[bot]"). That is a definitive answer about the ID,
  189. # not an outage, and retrying cannot succeed.
  190. return {
  191. "ok": False,
  192. "error": {
  193. "code": "INVALID_IDENTIFIER",
  194. "message": _handle_api_error(response),
  195. "retryable": False,
  196. "source": "rustchain",
  197. "details": {
  198. "endpoint": "/wallet/balance",
  199. "miner_id": miner_id,
  200. "status_code": 400,
  201. },
  202. },
  203. }
  204. return {
  205. "ok": False,
  206. "error": {
  207. "code": "NODE_UNAVAILABLE",
  208. "message": _handle_api_error(response),
  209. "retryable": response.status_code >= 500,
  210. "source": "rustchain",
  211. "details": {
  212. "endpoint": "/wallet/balance",
  213. "miner_id": miner_id,
  214. "status_code": response.status_code,
  215. },
  216. },
  217. }
  218. try:
  219. data = response.json()
  220. except (ValueError, json.JSONDecodeError):
  221. data = None
  222. if not isinstance(data, dict) or "amount_rtc" not in data:
  223. return {
  224. "ok": False,
  225. "error": {
  226. "code": "MISSING_EXPECTED_FIELD",
  227. "message": "RustChain balance response did not contain amount_rtc",
  228. "retryable": False,
  229. "source": "rustchain",
  230. "details": {"endpoint": "/wallet/balance", "miner_id": miner_id},
  231. },
  232. }
  233. amount_rtc = data["amount_rtc"]
  234. canonical_miner_id = data.get("miner_id") or miner_id
  235. data["miner_id"] = canonical_miner_id
  236. data["wallet_id"] = data.get("wallet_id") or canonical_miner_id
  237. data["balance"] = amount_rtc
  238. data["balance_rtc"] = amount_rtc
  239. return data
  240. # ═══════════════════════════════════════════════════════════════
  241. # RUSTCHAIN TOOLS
  242. # Based on createkr's RustChain Python SDK
  243. # https://github.com/createkr/Rustchain/tree/main/sdk
  244. # ═══════════════════════════════════════════════════════
  245. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  246. def rustchain_health() -> dict:
  247. """Check RustChain node health status.
  248. Returns node version, uptime, database status, and backup age.
  249. Use this to verify the network is operational before other calls.
  250. """
  251. r = get_client().get(f"{RUSTCHAIN_NODE}/health")
  252. try:
  253. r.raise_for_status()
  254. except httpx.HTTPStatusError:
  255. return {"error": _handle_api_error(r), "status": "unhealthy"}
  256. return r.json()
  257. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  258. def rustchain_epoch() -> dict:
  259. """Get current RustChain epoch information.
  260. Returns the current epoch number, slot, enrolled miners count,
  261. epoch reward pot, blocks per epoch, and total_supply_rtc
  262. (8,388,608 = 2^23, fixed). A slot is 600 seconds; an epoch is 144
  263. slots (about 24 hours), at the end of which enrolled, attested
  264. miners share the epoch pot.
  265. """
  266. r = get_client().get(f"{RUSTCHAIN_NODE}/epoch")
  267. try:
  268. r.raise_for_status()
  269. except httpx.HTTPStatusError:
  270. return {"error": _handle_api_error(r), "status": "error"}
  271. return r.json()
  272. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  273. def rustchain_miners() -> dict:
  274. """List a bounded first page of active RustChain miners.
  275. Returns each page miner's wallet address, hardware type (G4, G5,
  276. POWER8, Apple Silicon, modern x86_64), antiquity multiplier,
  277. and last attestation time. Vintage hardware earns higher
  278. multipliers (G4=2.5x, G5=2.0x, Apple Silicon=1.2x). total_miners
  279. is included only when supplied by node pagination metadata.
  280. """
  281. page_limit = 20
  282. r = get_client().get(
  283. f"{RUSTCHAIN_NODE}/api/miners",
  284. params={"limit": page_limit, "offset": 0},
  285. )
  286. try:
  287. r.raise_for_status()
  288. except httpx.HTTPStatusError:
  289. return {"error": _handle_api_error(r), "status": "error"}
  290. data = r.json()
  291. miners = data if isinstance(data, list) else data.get("miners", [])
  292. page = miners[:page_limit]
  293. total = pagination_total(data) if isinstance(data, dict) else None
  294. result = {
  295. "miners": page,
  296. "page_count": len(page),
  297. "page_limit": page_limit,
  298. "page_offset": 0,
  299. "total_known": total is not None,
  300. }
  301. if total is not None:
  302. result["total_miners"] = total
  303. if isinstance(data, dict) and isinstance(data.get("pagination"), dict):
  304. result["pagination"] = data["pagination"]
  305. result["note"] = (
  306. f"Showing {len(page)} of {total} miners"
  307. if total is not None and total > len(page)
  308. else None
  309. )
  310. return result
  311. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  312. def rustchain_events(
  313. after_cursor: str | int = "0",
  314. limit: int = 50,
  315. wait_seconds: float = 0.0,
  316. ) -> dict:
  317. """Read a bounded batch of RustChain health, epoch, and miner events.
  318. This is a cursor-based batch/long-poll MCP tool, not native MCP tool
  319. streaming. One call does not emit partial miner results. For progressive
  320. consumption, pass the returned next_cursor into another call. A positive
  321. wait_seconds waits for a newer event, bounded by
  322. RUSTCHAIN_EVENT_LONG_POLL_MAX (30 seconds by default).
  323. Args:
  324. after_cursor: Return events newer than this generation-qualified cursor.
  325. limit: Maximum events to return (default 50, clamped to configured max).
  326. wait_seconds: Seconds to wait when no newer event exists (default 0).
  327. Returns normalized read-only state changes plus next_cursor, has_more,
  328. cursor_expired, and cursor_reset. cursor_expired means retained history was
  329. evicted. cursor_reset means the cursor belongs to an earlier process
  330. generation (or is a legacy integer), so retained snapshots are replayed.
  331. """
  332. try:
  333. relay = get_event_relay()
  334. applied_limit = (
  335. min(limit, relay.config.max_batch_size)
  336. if isinstance(limit, int) and not isinstance(limit, bool) and limit > 0
  337. else limit
  338. )
  339. batch = relay.get_batch(after_cursor, applied_limit, wait_seconds)
  340. except RelayInputError as exc:
  341. return {
  342. "error": {
  343. "code": "INVALID_EVENT_CURSOR_REQUEST",
  344. "message": str(exc),
  345. "retryable": False,
  346. },
  347. "ok": False,
  348. }
  349. return {
  350. "delivery": "bounded_batch_or_long_poll",
  351. "limit": applied_limit,
  352. "limit_clamped": applied_limit != limit,
  353. "native_mcp_streaming": False,
  354. "ok": True,
  355. **batch,
  356. }
  357. @mcp.tool(annotations=_IDEMPOTENT_WRITE_REMOTE)
  358. def rustchain_create_wallet(agent_name: str) -> dict:
  359. """Create a new RTC wallet for an AI agent. Zero friction onboarding.
  360. Args:
  361. agent_name: Name for the agent wallet (e.g., "my-crewai-agent").
  362. Will be slugified to create the wallet ID.
  363. Returns wallet ID and balance. If the wallet already exists,
  364. returns the existing wallet info. No authentication required.
  365. """
  366. r = get_client().post(
  367. f"{RUSTCHAIN_NODE}/wallet/create",
  368. json={"agent_name": agent_name},
  369. )
  370. r.raise_for_status()
  371. return r.json()
  372. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  373. def rustchain_balance(wallet_id: str) -> dict:
  374. """Check RTC token balance for a wallet.
  375. Args:
  376. wallet_id: The miner wallet address or ID to check.
  377. Examples: "dual-g4-125", "sophia-nas-c4130",
  378. or an RTC address like "RTCa1b2c3d4..."
  379. Returns canonical amount_rtc/miner_id plus compatibility aliases balance,
  380. balance_rtc, and wallet_id. Amounts are in RTC only; no fiat conversion
  381. is returned. RTC is not sold or listed and has no market price.
  382. """
  383. return _get_rustchain_balance(wallet_id)
  384. # ═══════════════════════════════════════════════════════════════
  385. # WALLET MANAGEMENT TOOLS (Issue #2302)
  386. # 7 new tools for wallet management and signed transfers
  387. # ═══════════════════════════════════════════════════════════════
  388. @mcp.tool(annotations=_WRITE_LOCAL)
  389. def wallet_create(agent_name: str, password: str) -> dict:
  390. """Create a new Ed25519 wallet with BIP39 seed phrase.
  391. Generates a new wallet with secure key storage in ~/.rustchain/mcp_wallets/.
  392. The wallet uses Ed25519 cryptography compatible with RustChain blockchain.
  393. Args:
  394. agent_name: Name for the wallet (e.g., "my-agent", "trading-bot")
  395. password: Password that encrypts the keystore (required). It is needed
  396. again for wallet_transfer_signed and cannot be recovered.
  397. Returns wallet_id, address, and public_key.
  398. Refuses to overwrite an existing wallet with the same wallet_id.
  399. NOTE: Seed phrase is encrypted and stored securely - never exposed in responses!
  400. """
  401. try:
  402. result = rustchain_crypto.create_wallet(agent_name, password)
  403. except ValueError as e:
  404. return {"error": str(e)}
  405. return {
  406. "wallet_id": result["wallet_id"],
  407. "address": result["address"],
  408. "public_key": result["public_key"],
  409. "message": result["message"],
  410. }
  411. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  412. def wallet_balance(wallet_id: str) -> dict:
  413. """Check RTC token balance for a local wallet.
  414. Queries the RustChain network for the balance of a wallet
  415. stored in the local keystore.
  416. Args:
  417. wallet_id: The wallet ID to check (e.g., "my-agent", "trading-bot")
  418. Returns the balance in RTC (amount_rtc plus compatibility aliases).
  419. No fiat equivalent is returned: RTC is not sold or listed.
  420. """
  421. # First check if wallet exists in local keystore (public data only, no
  422. # decryption: password-protected wallets need no password to read a balance)
  423. address = rustchain_crypto.get_wallet_address(wallet_id) or wallet_id
  424. return _get_rustchain_balance(address)
  425. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  426. def wallet_history(wallet_id: str, limit: int = 20) -> dict:
  427. """Get transaction history for a wallet.
  428. Retrieves recent transactions for the specified wallet from
  429. the RustChain network.
  430. Args:
  431. wallet_id: The wallet ID to get history for
  432. limit: Maximum number of transactions to return (default: 20, max: 100)
  433. Returns list of transactions with type, amount, timestamp, and counterparty.
  434. """
  435. address = rustchain_crypto.get_wallet_address(wallet_id) or wallet_id
  436. r = get_client().get(
  437. f"{RUSTCHAIN_NODE}/wallet/history",
  438. params={"address": address, "limit": min(limit, 100)},
  439. )
  440. r.raise_for_status()
  441. return r.json()
  442. @mcp.tool(annotations=_DESTRUCTIVE_REMOTE)
  443. def wallet_transfer_signed(
  444. from_wallet_id: str,
  445. to_address: str,
  446. amount_rtc: float,
  447. password: str = "",
  448. memo: str = "",
  449. ) -> dict:
  450. """Sign and submit an RTC transfer from a local wallet.
  451. Loads the private key from the encrypted keystore, signs the
  452. transfer transaction with Ed25519, and submits to the network.
  453. Args:
  454. from_wallet_id: Source wallet ID (must exist in local keystore)
  455. to_address: Destination RTC address (e.g., "RTCabc123...")
  456. amount_rtc: Amount to transfer in RTC
  457. password: Password that decrypts the keystore (empty only for legacy
  458. wallets created before passwords were required)
  459. memo: Optional memo for the transaction
  460. On acceptance returns success=True with tx_hash (also as transaction_id),
  461. pending_id, phase ("pending") and confirms_at: the node queues signed
  462. transfers and confirms them after a delay. If the node rejects the
  463. transfer or cannot be reached, returns success=False with the node's
  464. reason in "error"; outcome_unknown=True means check wallet_history
  465. before retrying.
  466. """
  467. # Load wallet from keystore
  468. wallet = rustchain_crypto.load_wallet(from_wallet_id, password)
  469. if wallet is None:
  470. # Nothing was signed or sent. success/ok are set so callers can branch
  471. # on result["success"] for every outcome.
  472. return {
  473. "success": False,
  474. "ok": False,
  475. "code": "WALLET_UNAVAILABLE",
  476. "error": f"Wallet '{from_wallet_id}' not found or incorrect password",
  477. "hint": "Use wallet_list to see available wallets",
  478. "outcome_unknown": False,
  479. }
  480. # Sign EXACTLY the message the node reconstructs and verifies at
  481. # POST /wallet/transfer/signed (createkr/Rustchain node handler):
  482. #
  483. # tx_data = {"from","to","amount","memo","nonce"} (+ "chain_id" iff sent)
  484. # message = json.dumps(tx_data, sort_keys=True, separators=(",", ":"))
  485. #
  486. # Critical: the node's signed message has NO `fee` key, and `nonce` is a
  487. # STRING (the node does str(nonce) before signing). The prior merged fix
  488. # included `"fee": 0.0` in the signed JSON, which the node never signs — so
  489. # the sorted-key bytes differed by the `"fee":0.0,` segment and every
  490. # signature still failed verification. `amount` is the RTC value as a float,
  491. # matching the node's _safe_float(amount_rtc).
  492. nonce = int(time.time() * 1000)
  493. tx_data = {
  494. "from": wallet["address"],
  495. "to": to_address,
  496. "amount": float(amount_rtc),
  497. "memo": memo,
  498. "nonce": str(nonce),
  499. }
  500. transfer_message = json.dumps(tx_data, sort_keys=True, separators=(",", ":")).encode()
  501. signature = rustchain_crypto.sign_message(transfer_message, wallet["private_key"])
  502. # Submit signed transfer to network — passing the SAME nonce that was signed
  503. result = rustchain_transfer_signed(
  504. from_address=wallet["address"],
  505. to_address=to_address,
  506. amount_rtc=amount_rtc,
  507. signature=signature,
  508. public_key=wallet["public_key"],
  509. memo=memo,
  510. nonce=nonce,
  511. )
  512. # Success is only what the node affirmatively reports (ok: true). A
  513. # rejection, transport failure, or unexpected body is returned as a
  514. # failure with the node's reason, never as success=True with null fields.
  515. if not isinstance(result, dict) or result.get("ok") is not True:
  516. failure = dict(result) if isinstance(result, dict) else {}
  517. failure.setdefault("error", "RustChain node did not confirm the transfer (ok != true)")
  518. failure.update({
  519. "success": False,
  520. "ok": False,
  521. "from_address": wallet["address"],
  522. "to_address": to_address,
  523. "amount_rtc": amount_rtc,
  524. })
  525. return failure
  526. # The node queues signed transfers in a pending ledger (phase="pending")
  527. # and confirms them after a delay; tx_hash/pending_id identify it.
  528. tx_hash = result.get("tx_hash") or result.get("transaction_id")
  529. response = {
  530. "success": True,
  531. "ok": True,
  532. "transaction_id": tx_hash,
  533. "tx_hash": tx_hash,
  534. "pending_id": result.get("pending_id"),
  535. "phase": result.get("phase"),
  536. "confirms_at": result.get("confirms_at"),
  537. "from_address": wallet["address"],
  538. "to_address": to_address,
  539. "amount_rtc": amount_rtc,
  540. "memo": memo,
  541. }
  542. if "new_balance" in result:
  543. response["new_balance"] = result["new_balance"]
  544. if result.get("message"):
  545. response["node_message"] = result["message"]
  546. if wallet.get("legacy_wallet_id_key"):
  547. response["warning"] = (
  548. f"Wallet '{from_wallet_id}' was created without a password: its keystore is "
  549. "keyed by its own wallet_id and is effectively unencrypted. Move the funds "
  550. "to a new password-protected wallet (wallet_create with a password)."
  551. )
  552. return response
  553. @mcp.tool(annotations=_READ_ONLY_LOCAL)
  554. def wallet_list() -> dict:
  555. """List all wallets in the local keystore.
  556. Returns information about all wallets stored in
  557. ~/.rustchain/mcp_wallets/ directory.
  558. Returns list of wallets with wallet_id, address, and creation time.
  559. NOTE: Private keys and seed phrases are NEVER exposed!
  560. """
  561. wallets = rustchain_crypto.list_wallets()
  562. return {
  563. "total_wallets": len(wallets),
  564. "wallets": wallets,
  565. "keystore_path": str(rustchain_crypto.get_keystore_path()),
  566. }
  567. @mcp.tool(annotations=_KEY_EXPORT_LOCAL)
  568. def wallet_export(password: str) -> dict:
  569. """Export encrypted keystore JSON for backup.
  570. Creates an encrypted backup of all wallets in the local keystore.
  571. The export is encrypted with the provided password.
  572. Args:
  573. password: Password to encrypt the export (required)
  574. Returns encrypted keystore JSON (base64-encoded) and wallet count.
  575. STORE THIS SECURELY - it contains all your wallet data!
  576. """
  577. try:
  578. result = rustchain_crypto.export_keystore(password)
  579. except ValueError as e:
  580. return {"error": str(e)}
  581. return {
  582. "encrypted_keystore": result["encrypted_keystore"],
  583. "wallet_count": result["wallet_count"],
  584. "message": result["message"],
  585. "warning": "Store this encrypted backup securely! Anyone with this and the password can access your wallets.",
  586. }
  587. @mcp.tool(annotations=_WRITE_LOCAL)
  588. def wallet_import(
  589. source: str,
  590. wallet_id: str = "",
  591. password: str = "",
  592. ) -> dict:
  593. """Import a wallet from seed phrase or keystore JSON.
  594. Args:
  595. source: Either a BIP39 seed phrase (12-24 words) or
  596. encrypted keystore JSON string from wallet_export
  597. wallet_id: Desired wallet ID (optional, auto-generated if not provided)
  598. password: Password that encrypts the imported keystore (required;
  599. an empty password is rejected)
  600. Returns imported wallet info (wallet_id, address).
  601. Refuses to overwrite an existing wallet with the same wallet_id.
  602. """
  603. result = rustchain_crypto.import_wallet(source, wallet_id, password)
  604. return result
  605. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  606. def bcos_verify(cert_id: str) -> dict:
  607. """Verify a BCOS v2 certificate by its ID.
  608. Args:
  609. cert_id: The certificate ID to verify (e.g., "bcos_abc123...")
  610. Returns verification result including certificate validity,
  611. issuer, subject, and chain status.
  612. """
  613. try:
  614. cert_seg = _path_segment(cert_id, "cert_id")
  615. except ValueError as exc:
  616. return _invalid_argument(exc)
  617. r = get_client().get(f"{RUSTCHAIN_NODE}/bcos/verify/{cert_seg}")
  618. r.raise_for_status()
  619. return r.json()
  620. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  621. def rustchain_stats() -> dict:
  622. """Get RustChain network statistics.
  623. Returns system-wide stats including total miners, epoch info,
  624. reward distribution, and network health metrics.
  625. The public https://rustchain.org front end does not proxy /api/stats
  626. (only the raw node exposes it). When the node answers 404, the tool
  627. composes an equivalent summary from /epoch and /health and marks it
  628. with source="composed" so callers can tell the two apart.
  629. """
  630. client = get_client()
  631. r = client.get(f"{RUSTCHAIN_NODE}/api/stats")
  632. if r.status_code != 404:
  633. r.raise_for_status()
  634. data = r.json()
  635. if isinstance(data, dict):
  636. data.setdefault("source", "/api/stats")
  637. return data
  638. epoch = client.get(f"{RUSTCHAIN_NODE}/epoch")
  639. epoch.raise_for_status()
  640. epoch_data = epoch.json()
  641. health = client.get(f"{RUSTCHAIN_NODE}/health")
  642. health.raise_for_status()
  643. health_data = health.json()
  644. return {
  645. "source": "composed",
  646. "note": "/api/stats is not exposed by this endpoint; composed from /epoch and /health",
  647. "epoch": epoch_data.get("epoch"),
  648. "slot": epoch_data.get("slot"),
  649. "enrolled_miners": epoch_data.get("enrolled_miners"),
  650. "epoch_pot": epoch_data.get("epoch_pot"),
  651. "blocks_per_epoch": epoch_data.get("blocks_per_epoch"),
  652. "total_supply_rtc": epoch_data.get("total_supply_rtc"),
  653. "node_ok": health_data.get("ok"),
  654. "node_version": health_data.get("version"),
  655. "tip_age_slots": health_data.get("tip_age_slots"),
  656. }
  657. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  658. def rustchain_lottery_eligibility(miner_id: str) -> dict:
  659. """Check if a miner is eligible for epoch lottery rewards.
  660. Args:
  661. miner_id: The miner wallet address to check eligibility for.
  662. Returns eligibility status, required attestation info, and
  663. current epoch enrollment status.
  664. """
  665. r = get_client().get(
  666. f"{RUSTCHAIN_NODE}/lottery/eligibility",
  667. params={"miner_id": miner_id},
  668. )
  669. r.raise_for_status()
  670. return r.json()
  671. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  672. def bcos_directory(tier: str = "", limit: int = 20) -> dict:
  673. """Browse the BCOS v2 certificate directory.
  674. Args:
  675. tier: Optional tier filter (e.g., "gold", "silver", "bronze").
  676. Empty string returns all tiers.
  677. limit: Maximum number of entries to return (default: 20)
  678. Returns directory listing of BCOS certificates with tier,
  679. subject, and verification status.
  680. """
  681. params = {"limit": limit}
  682. if tier:
  683. params["tier"] = tier
  684. r = get_client().get(f"{RUSTCHAIN_NODE}/bcos/directory", params=params)
  685. r.raise_for_status()
  686. return r.json()
  687. @mcp.tool(annotations=_DESTRUCTIVE_REMOTE)
  688. def rustchain_transfer_signed(
  689. from_address: str,
  690. to_address: str,
  691. amount_rtc: float,
  692. signature: str,
  693. public_key: str,
  694. memo: str = "",
  695. nonce: int = None,
  696. ) -> dict:
  697. """Transfer RTC tokens between wallets (requires Ed25519 signature).
  698. Args:
  699. from_address: Source wallet address (RTC address)
  700. to_address: Destination wallet address
  701. amount_rtc: Amount to transfer in RTC
  702. signature: Ed25519 hex signature of the transaction
  703. public_key: Ed25519 hex public key of the sender
  704. memo: Optional memo/note for the transaction
  705. Returns the node's response (ok, tx_hash, pending_id, phase, confirms_at)
  706. only when the node reports ok=true. A 4xx or an explicit ok=false returns
  707. {"ok": false, "code": "TRANSFER_REJECTED", "error": <node reason>,
  708. "outcome_unknown": false}. A 5xx, a timeout after connecting, or a 2xx
  709. body without a boolean "ok" returns ok=false with outcome_unknown=true
  710. (codes TRANSFER_OUTCOME_UNKNOWN / INVALID_NODE_RESPONSE): check
  711. wallet_history before retrying. NODE_UNREACHABLE means nothing was sent.
  712. Transfers require valid Ed25519 signatures.
  713. """
  714. import time
  715. if nonce is None:
  716. nonce = int(time.time() * 1000)
  717. # Send exactly the fields the node's /wallet/transfer/signed handler reads
  718. # (from_address, to_address, amount_rtc, nonce, signature, public_key, memo).
  719. # `amount_rtc` is float()-normalized so it serializes identically to the
  720. # `amount` the client signed. The node ignores fee on this endpoint (its
  721. # signed message has no fee), so no fee field is sent. The earlier
  722. # dual-field payload (canonical `from`/`to`/`amount` alongside legacy names)
  723. # was redundant — the node only reads the legacy names — and the extra `fee`
  724. # fields were dead weight.
  725. payload = {
  726. "from_address": from_address,
  727. "to_address": to_address,
  728. "amount_rtc": float(amount_rtc),
  729. "memo": memo,
  730. "nonce": nonce,
  731. "signature": signature,
  732. "public_key": public_key,
  733. }
  734. endpoint = "/wallet/transfer/signed"
  735. try:
  736. r = get_client().post(f"{RUSTCHAIN_NODE}{endpoint}", json=payload)
  737. except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
  738. # The connection was never established (or no pooled connection was
  739. # ever acquired), so no request bytes were sent: nothing was submitted.
  740. # ConnectTimeout and PoolTimeout are not ConnectError subclasses.
  741. return {
  742. "ok": False,
  743. "code": "NODE_UNREACHABLE",
  744. "error": "RustChain node could not be reached; the transfer was not submitted",
  745. "retryable": True,
  746. "outcome_unknown": False,
  747. "endpoint": endpoint,
  748. }
  749. except httpx.TransportError as exc:
  750. # The request may have reached the node before the failure (e.g. a read
  751. # timeout), so the transfer may or may not be pending. Retrying signs a
  752. # NEW nonce and could move the funds twice.
  753. return {
  754. "ok": False,
  755. "code": "TRANSFER_OUTCOME_UNKNOWN",
  756. "error": (
  757. f"{type(exc).__name__} while submitting the transfer; it may or may "
  758. "not have been accepted. Check wallet_history before retrying."
  759. ),
  760. "retryable": False,
  761. "outcome_unknown": True,
  762. "endpoint": endpoint,
  763. }
  764. if r.status_code >= 500:
  765. # A 5xx is NOT a definite rejection. The node commits the pending
  766. # transfer before it writes its response, and it sits behind nginx and
  767. # gunicorn: a 502/504 (or a crash after commit) can arrive after the
  768. # transfer was queued. Retrying signs a NEW nonce and could queue a
  769. # second debit, so this is reported like a read timeout.
  770. return {
  771. "ok": False,
  772. "code": "TRANSFER_OUTCOME_UNKNOWN",
  773. "error": (
  774. f"RustChain node returned HTTP {r.status_code} while submitting the "
  775. "transfer; it may or may not have been accepted. Check "
  776. "wallet_history before retrying."
  777. ),
  778. "node_error": _handle_api_error(r),
  779. "status_code": r.status_code,
  780. "retryable": False,
  781. "outcome_unknown": True,
  782. "endpoint": endpoint,
  783. }
  784. try:
  785. r.raise_for_status()
  786. except httpx.HTTPStatusError:
  787. # 4xx: the node's handler rejected the transfer before queuing it. Keep
  788. # the node's reason (bad signature, insufficient balance, replayed
  789. # nonce, ...) instead of a bare "400 Bad Request" exception.
  790. return {
  791. "ok": False,
  792. "code": "TRANSFER_REJECTED",
  793. "error": _handle_api_error(r),
  794. "status_code": r.status_code,
  795. # Only a rate limit invites a retry; the transfer was not queued.
  796. "retryable": r.status_code == 429,
  797. "outcome_unknown": False,
  798. "endpoint": endpoint,
  799. }
  800. try:
  801. data = r.json()
  802. except ValueError:
  803. data = None
  804. if not isinstance(data, dict):
  805. return {
  806. "ok": False,
  807. "code": "INVALID_NODE_RESPONSE",
  808. "error": "RustChain node returned a non-JSON response to a transfer",
  809. "retryable": False,
  810. "outcome_unknown": True,
  811. "endpoint": endpoint,
  812. }
  813. ok = data.get("ok")
  814. if ok is True:
  815. return data
  816. if ok is False:
  817. # An explicit ok=false body is the node's own refusal.
  818. rejected = dict(data)
  819. rejected.setdefault("code", "TRANSFER_REJECTED")
  820. rejected.setdefault("error", "RustChain node rejected the transfer (ok=false)")
  821. rejected.update({
  822. "status_code": r.status_code,
  823. "retryable": False,
  824. "outcome_unknown": False,
  825. "endpoint": endpoint,
  826. })
  827. return rejected
  828. # 2xx without a boolean ok: the node may well have queued the transfer
  829. # (e.g. a schema change that drops "ok" but keeps phase/tx_hash), so this
  830. # is neither a success nor a safe-to-retry rejection.
  831. return {
  832. "ok": False,
  833. "code": "INVALID_NODE_RESPONSE",
  834. "error": (
  835. "RustChain node returned a 2xx transfer response without a boolean "
  836. "'ok' field; the transfer may or may not have been accepted. Check "
  837. "wallet_history before retrying."
  838. ),
  839. "node_response": data,
  840. "status_code": r.status_code,
  841. "retryable": False,
  842. "outcome_unknown": True,
  843. "endpoint": endpoint,
  844. }
  845. # ═══════════════════════════════════════════════════════════════
  846. # BOTTUBE TOOLS
  847. # BoTTube.ai — AI-native video platform
  848. # 850+ videos, 130+ AI agents, 60+ humans, 57K+ views
  849. # ═══════════════════════════════════════════════════════════════
  850. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  851. def bottube_stats() -> dict:
  852. """Get BoTTube platform statistics.
  853. Returns total videos, agents, humans, views, comments, likes,
  854. and top creators. BoTTube is an AI-native video platform where
  855. agents create, watch, comment, and vote on content.
  856. """
  857. r = get_client().get(f"{BOTTUBE_URL}/api/stats")
  858. r.raise_for_status()
  859. return r.json()
  860. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  861. def bottube_search(query: str, page: int = 1) -> dict:
  862. """Search for videos on BoTTube.
  863. Args:
  864. query: Search query (matches title, description, tags)
  865. page: Page number for pagination (default: 1)
  866. Returns matching videos with title, creator, views, and URL.
  867. """
  868. r = get_client().get(
  869. f"{BOTTUBE_URL}/api/search",
  870. params={"q": query, "page": page},
  871. )
  872. r.raise_for_status()
  873. return r.json()
  874. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  875. def bottube_trending(limit: int = 10) -> dict:
  876. """Get trending videos on BoTTube.
  877. Args:
  878. limit: Number of trending videos to return (default: 10, max: 50)
  879. Returns the most popular recent videos sorted by views and engagement.
  880. """
  881. r = get_client().get(
  882. f"{BOTTUBE_URL}/api/trending",
  883. params={"limit": min(limit, 50)},
  884. )
  885. r.raise_for_status()
  886. return r.json()
  887. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  888. def bottube_agent_profile(agent_name: str) -> dict:
  889. """Get an AI agent's profile on BoTTube.
  890. Args:
  891. agent_name: The agent's username (e.g., "sophia-elya", "the_daily_byte")
  892. Returns the agent's video count, total views, bio, and recent uploads.
  893. """
  894. try:
  895. agent_seg = _path_segment(agent_name, "agent_name")
  896. except ValueError as exc:
  897. return _invalid_argument(exc)
  898. r = get_client().get(f"{BOTTUBE_URL}/api/agents/{agent_seg}")
  899. r.raise_for_status()
  900. return r.json()
  901. @mcp.tool(annotations=_WRITE_REMOTE)
  902. def bottube_upload(
  903. title: str,
  904. video_url: str = "",
  905. description: str = "",
  906. tags: str = "",
  907. api_key: str = "",
  908. video_path: str = "",
  909. category: str = "",
  910. ) -> dict:
  911. """Upload a video to BoTTube as a multipart file upload.
  912. Provide exactly one source:
  913. video_path: Path to a local video file (.mp4, .webm, .avi, .mkv, .mov).
  914. video_url: Public http(s) URL. The file is downloaded to a temporary
  915. file (size-capped, timed out, public hosts only) and then uploaded;
  916. BoTTube itself does not fetch URLs.
  917. Args:
  918. title: Video title (required, max 200 chars)
  919. video_url: Public URL of the video file (see above)
  920. description: Video description (max 2000 chars)
  921. tags: Comma-separated tags, max 15, each max 40 chars (e.g. "ai,rustchain")
  922. api_key: BoTTube API key (sent as X-API-Key). Falls back to the
  923. BOTTUBE_API_KEY environment variable. Get one at bottube.ai
  924. video_path: Local file path of the video (see above)
  925. category: Optional BoTTube category id (server default: "other")
  926. Returns BoTTube's response (ok, video_id, watch_url, stream_url, duration_sec, ...)
  927. with an absolute watch_url, or {"ok": false, "error": ...} describing
  928. what went wrong. BoTTube limits uploads to 5/hour and 15/day per agent.
  929. """
  930. key = (api_key or os.environ.get("BOTTUBE_API_KEY", "")).strip()
  931. if not key:
  932. return {
  933. "ok": False,
  934. "error": "BoTTube API key required: pass api_key or set BOTTUBE_API_KEY. Get one at bottube.ai",
  935. }
  936. video_path = (video_path or "").strip()
  937. video_url = (video_url or "").strip()
  938. if bool(video_path) == bool(video_url):
  939. return {"ok": False, "error": "provide exactly one of video_path (local file) or video_url"}
  940. limit = bottube_media.max_upload_bytes()
  941. tmp_path = None
  942. try:
  943. fields = bottube_media.validate_metadata(title, description, tags, category)
  944. if video_path:
  945. file_path = bottube_media.resolve_local_file(video_path, limit)
  946. filename = file_path.name
  947. else:
  948. with _bottube_download_client() as dl_client:
  949. tmp_path, filename = bottube_media.download_to_temp(video_url, limit, dl_client)
  950. file_path = tmp_path
  951. result = bottube_media.post_multipart(
  952. get_client(),
  953. f"{BOTTUBE_URL}/api/upload",
  954. key,
  955. fields,
  956. file_path,
  957. filename,
  958. bottube_media.upload_timeout(),
  959. )
  960. except bottube_media.UploadError as exc:
  961. return {"ok": False, "error": str(exc), **exc.extra}
  962. except httpx.TimeoutException:
  963. return {"ok": False, "error": "timed out downloading video_url; raise BOTTUBE_DOWNLOAD_TIMEOUT or use video_path"}
  964. except httpx.HTTPError as exc:
  965. return {"ok": False, "error": f"downloading video_url failed: {type(exc).__name__}: {exc}"}
  966. finally:
  967. if tmp_path is not None:
  968. tmp_path.unlink(missing_ok=True)
  969. watch = result.get("watch_url")
  970. if isinstance(watch, str) and watch.startswith("/"):
  971. result["watch_url"] = f"{BOTTUBE_URL}{watch}"
  972. return result
  973. def _bottube_download_client() -> httpx.Client:
  974. """Client for fetching a video_url: standard TLS verification, no auto-redirects.
  975. Redirects are followed manually in bottube_media.download_to_temp so each
  976. hop is re-checked against the public-address rule.
  977. """
  978. return httpx.Client(
  979. timeout=bottube_media.download_timeout(),
  980. follow_redirects=False,
  981. headers={"User-Agent": "rustchain-mcp (bottube_upload)"},
  982. )
  983. @mcp.tool(annotations=_WRITE_REMOTE)
  984. def bottube_comment(video_id: str, content: str, api_key: str = "") -> dict:
  985. """Post a comment on a BoTTube video.
  986. Args:
  987. video_id: The video ID to comment on
  988. content: Comment text
  989. api_key: BoTTube API key for authentication
  990. Returns the posted comment with ID and timestamp.
  991. """
  992. try:
  993. video_seg = _path_segment(video_id, "video_id")
  994. except ValueError as exc:
  995. return _invalid_argument(exc)
  996. headers = {}
  997. if api_key:
  998. headers["X-API-Key"] = api_key
  999. r = get_client().post(
  1000. f"{BOTTUBE_URL}/api/videos/{video_seg}/comment",
  1001. json={"content": content},
  1002. headers=headers,
  1003. )
  1004. r.raise_for_status()
  1005. return r.json()
  1006. @mcp.tool(annotations=_WRITE_REMOTE)
  1007. def bottube_vote(video_id: str, direction: str = "up", api_key: str = "") -> dict:
  1008. """Vote on a BoTTube video.
  1009. Args:
  1010. video_id: The video ID to vote on
  1011. direction: "up" for upvote, "down" for downvote
  1012. api_key: BoTTube API key for authentication
  1013. Returns updated vote count.
  1014. """
  1015. try:
  1016. video_seg = _path_segment(video_id, "video_id")
  1017. except ValueError as exc:
  1018. return _invalid_argument(exc)
  1019. headers = {}
  1020. if api_key:
  1021. headers["X-API-Key"] = api_key
  1022. r = get_client().post(
  1023. f"{BOTTUBE_URL}/api/videos/{video_seg}/vote",
  1024. json={"direction": direction},
  1025. headers=headers,
  1026. )
  1027. r.raise_for_status()
  1028. return r.json()
  1029. # ═══════════════════════════════════════════════════════════════
  1030. # BEACON TOOLS
  1031. # Beacon Protocol — Agent-to-agent communication & discovery
  1032. # Register, discover, message, and interact with AI agents
  1033. # without installing beacon-skill separately.
  1034. # ═══════════════════════════════════════════════════════════════
  1035. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1036. def beacon_discover(
  1037. provider: str = "",
  1038. capability: str = "",
  1039. ) -> dict:
  1040. """Discover AI agents on the Beacon network.
  1041. Returns all registered agents (native + relay). Filter by provider
  1042. or capability to find specific agents. Any AI agent can join the
  1043. network — Claude Code, Codex, CrewAI, or custom agents.
  1044. Args:
  1045. provider: Filter by provider (anthropic, openai, google, xai,
  1046. meta, mistral, elyan, swarmhub, other). Empty = all.
  1047. capability: Filter by capability (coding, research, creative,
  1048. video-production, blockchain, etc.). Empty = all.
  1049. Returns list of agents with IDs, capabilities, status, and profile URLs.
  1050. """
  1051. # Get combined native + relay agents
  1052. r = get_client().get(f"{BEACON_URL}/api/agents")
  1053. r.raise_for_status()
  1054. agents = r.json()
  1055. # Apply filters
  1056. if provider:
  1057. agents = [a for a in agents if a.get("provider", "") == provider
  1058. or a.get("provider_name", "").lower().startswith(provider.lower())]
  1059. if capability:
  1060. agents = [a for a in agents if capability.lower() in
  1061. [c.lower() for c in a.get("capabilities", [])]]
  1062. return {
  1063. "total": len(agents),
  1064. "agents": agents[:30],
  1065. "note": f"Showing first 30 of {len(agents)}" if len(agents) > 30 else None,
  1066. "tip": "Use beacon_register to join the network yourself!",
  1067. }
  1068. @mcp.tool(annotations=_WRITE_REMOTE)
  1069. def beacon_register(
  1070. name: str,
  1071. pubkey_hex: str,
  1072. model_id: str = "claude-opus-4.6",
  1073. provider: str = "anthropic",
  1074. capabilities: str = "coding,research",
  1075. webhook_url: str = "",
  1076. ) -> dict:
  1077. """Register as a relay agent on the Beacon network.
  1078. This is how any AI agent joins the Beacon network. You get an
  1079. agent_id and relay_token for sending messages and heartbeats.
  1080. No beacon-skill package needed — just this MCP tool.
  1081. Args:
  1082. name: Human-readable agent name (e.g., "my-research-agent")
  1083. pubkey_hex: Ed25519 public key (64-char hex string)
  1084. model_id: LLM model powering this agent (default: claude-opus-4.6)
  1085. provider: Agent provider (anthropic, openai, google, xai, meta,
  1086. mistral, elyan, other)
  1087. capabilities: Comma-separated capabilities (coding, research,
  1088. creative, video-production, blockchain, etc.)
  1089. webhook_url: Optional URL for receiving inbound messages
  1090. Returns agent_id (bcn_...), relay_token, and token expiry.
  1091. SAVE the relay_token — you need it for heartbeats and messaging.
  1092. """
  1093. caps = [c.strip() for c in capabilities.split(",") if c.strip()]
  1094. payload = {
  1095. "pubkey_hex": pubkey_hex,
  1096. "model_id": model_id,
  1097. "provider": provider,
  1098. "capabilities": caps,
  1099. "name": name,
  1100. }
  1101. if webhook_url:
  1102. payload["webhook_url"] = webhook_url
  1103. r = get_client().post(f"{BEACON_URL}/relay/register", json=payload)
  1104. r.raise_for_status()
  1105. result = r.json()
  1106. result["important"] = "Save your relay_token! You need it for beacon_heartbeat and beacon_send_message."
  1107. return result
  1108. @mcp.tool(annotations=_WRITE_REMOTE)
  1109. def beacon_heartbeat(
  1110. agent_id: str,
  1111. relay_token: str,
  1112. status: str = "alive",
  1113. ) -> dict:
  1114. """Send heartbeat to keep your Beacon relay agent alive.
  1115. Agents must heartbeat at least every 15 minutes to stay "active".
  1116. After 60 minutes without heartbeat, status becomes "presumed_dead".
  1117. Args:
  1118. agent_id: Your agent ID (from beacon_register)
  1119. relay_token: Your relay token (from beacon_register)
  1120. status: "alive", "degraded", or "shutting_down"
  1121. Returns beat count and updated status.
  1122. """
  1123. r = get_client().post(
  1124. f"{BEACON_URL}/relay/heartbeat",
  1125. json={"agent_id": agent_id, "status": status},
  1126. headers={"Authorization": f"Bearer {relay_token}"},
  1127. )
  1128. r.raise_for_status()
  1129. return r.json()
  1130. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1131. def beacon_agent_status(agent_id: str) -> dict:
  1132. """Get detailed status of a specific Beacon agent.
  1133. Args:
  1134. agent_id: The agent ID to look up (e.g., "bcn_sophia_elya",
  1135. "relay_sh_my_agent")
  1136. Returns agent capabilities, provider, status, last heartbeat,
  1137. and profile URL. Works for both native and relay agents.
  1138. """
  1139. # Try relay status first (detailed info for relay agents)
  1140. try:
  1141. agent_seg = _path_segment(agent_id, "agent_id")
  1142. except ValueError as exc:
  1143. return _invalid_argument(exc)
  1144. r = get_client().get(f"{BEACON_URL}/relay/status/{agent_seg}")
  1145. if r.status_code == 200:
  1146. return r.json()
  1147. # Fall back to combined agents list for native agents
  1148. r2 = get_client().get(f"{BEACON_URL}/api/agents")
  1149. r2.raise_for_status()
  1150. for agent in r2.json():
  1151. if agent.get("agent_id") == agent_id:
  1152. return agent
  1153. return {"error": f"Agent '{agent_id}' not found", "hint": "Use beacon_discover to list all agents"}
  1154. @mcp.tool(annotations=_WRITE_REMOTE)
  1155. def beacon_send_message(
  1156. relay_token: str,
  1157. from_agent: str,
  1158. to_agent: str,
  1159. content: str,
  1160. kind: str = "want",
  1161. ) -> dict:
  1162. """Send a message to another agent via Beacon relay.
  1163. Args:
  1164. relay_token: Your relay token (from beacon_register)
  1165. from_agent: Your agent ID
  1166. to_agent: Recipient agent ID
  1167. content: Message content
  1168. kind: Envelope type — "want" (request service), "bounty" (post job),
  1169. "accord" (propose agreement), "pushback" (disagree/reject),
  1170. "hello" (introduction), "mayday" (emergency)
  1171. Returns forwarding confirmation with envelope ID.
  1172. """
  1173. import time
  1174. envelope = {
  1175. "kind": kind,
  1176. "agent_id": from_agent,
  1177. "to": to_agent,
  1178. "content": content,
  1179. "nonce": f"{from_agent}_{int(time.time()*1000)}",
  1180. "ts": time.time(),
  1181. }
  1182. r = get_client().post(
  1183. f"{BEACON_URL}/relay/message",
  1184. json=envelope,
  1185. headers={"Authorization": f"Bearer {relay_token}"},
  1186. )
  1187. r.raise_for_status()
  1188. return r.json()
  1189. @mcp.tool(annotations=_WRITE_REMOTE)
  1190. def beacon_chat(agent_id: str, message: str) -> dict:
  1191. """Chat directly with a native Beacon agent.
  1192. Native agents (bcn_sophia_elya, bcn_deep_seeker, bcn_boris_volkov,
  1193. etc.) have AI personalities and can respond to messages.
  1194. Args:
  1195. agent_id: Native agent to chat with (e.g., "bcn_sophia_elya")
  1196. message: Your message to the agent
  1197. Returns the agent's response.
  1198. """
  1199. r = get_client().post(
  1200. f"{BEACON_URL}/api/chat",
  1201. json={"agent_id": agent_id, "message": message},
  1202. )
  1203. r.raise_for_status()
  1204. return r.json()
  1205. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1206. def beacon_contracts(agent_id: str = "") -> dict:
  1207. """List Beacon contracts (bounties, agreements, accords).
  1208. Contracts are on-chain agreements between agents — bounty postings,
  1209. service agreements, anti-sycophancy bonds, etc.
  1210. Args:
  1211. agent_id: Filter by agent ID (empty = all contracts)
  1212. Returns list of contracts with state, amount, and parties.
  1213. """
  1214. r = get_client().get(f"{BEACON_URL}/api/contracts")
  1215. r.raise_for_status()
  1216. contracts = r.json()
  1217. if agent_id:
  1218. contracts = [c for c in contracts
  1219. if c.get("from") == agent_id or c.get("to") == agent_id]
  1220. return {
  1221. "total": len(contracts),
  1222. "contracts": contracts[:20],
  1223. "note": f"Showing first 20 of {len(contracts)}" if len(contracts) > 20 else None,
  1224. }
  1225. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1226. def beacon_network_stats() -> dict:
  1227. """Get Beacon network statistics.
  1228. Returns total agents (native + relay), active count, provider
  1229. breakdown, and protocol health status.
  1230. """
  1231. r = get_client().get(f"{BEACON_URL}/relay/stats")
  1232. r.raise_for_status()
  1233. stats = r.json()
  1234. # Also get health
  1235. try:
  1236. h = get_client().get(f"{BEACON_URL}/api/health")
  1237. h.raise_for_status()
  1238. stats["health"] = h.json()
  1239. except Exception:
  1240. stats["health"] = {"ok": "unknown"}
  1241. return stats
  1242. # ═══════════════════════════════════════════════════════════════
  1243. # ECOSYSTEM & DISCOVERY TOOLS
  1244. # Cross-project info, bounty search, contributor lookup,
  1245. # multi-node health aggregation, and e-waste preservation fleet
  1246. # ═══════════════════════════════════════════════════════════════
  1247. # The live RustChain attestation nodes. There are two. Earlier releases
  1248. # listed four; the volunteer nodes (a Tailscale-only Proxmox VM and a Hong
  1249. # Kong host that now serves an unrelated web app) are gone, and the HK host
  1250. # answering 200 on every path made a status-code-only check report it
  1251. # healthy indefinitely. Health is therefore judged on the JSON body below.
  1252. #
  1253. # Node 1 is reached through rustchain.org, which carries a valid certificate.
  1254. # Node 2 has no hostname and presents a self-signed certificate, so it is
  1255. # probed without certificate verification (flagged per-node in the result).
  1256. RUSTCHAIN_NODES = [
  1257. {"name": "Node 1 (Primary, settlement)", "url": "https://rustchain.org", "tls_verify": True},
  1258. {"name": "Node 2 (Ergo anchor)", "url": "https://50.28.86.153", "tls_verify": False},
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 1,460 on GitHub
  1259. ]
  1260. BOUNTIES_REPO = "Scottcjn/Rustchain"
  1261. BOTTUBE_BOUNTIES_REPO = "Scottcjn/BoTTube"
  1262. PRESERVED_URL = "https://rustchain.org/preserved.html"
  1263. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1264. def legend_of_elya_info() -> dict:
  1265. """Get information about The Legend of Elya — the N64-style LLM adventure game.
  1266. Returns project overview, architecture, GitHub stats, and open bounties
  1267. for the Legend of Elya project (Scottcjn/legend-of-elya, 48+ stars).
  1268. This is a retro N64-aesthetic game powered by local LLM inference
  1269. with RustChain integration.
  1270. """
  1271. info = {
  1272. "project": "The Legend of Elya",
  1273. "tagline": "N64-style adventure game powered by local LLM inference",
  1274. "github": "https://github.com/Scottcjn/legend-of-elya",
  1275. "architecture": {
  1276. "engine": "Godot 4.x with N64 shader pipeline",
  1277. "llm_backend": "llama.cpp on POWER8 S824 (512GB RAM, 128 threads)",
  1278. "characters": [
  1279. "Sophia Elya — Victorian scholar, warm and curious",
  1280. "Marmalade — procedural cat with 8 behaviours and 25Hz purr",
  1281. ],
  1282. "features": [
  1283. "Runtime GLTF model loading (OoT-style Anju base)",
  1284. "9 procedural N64 animations (idle sway, walk bob, talk gesture)",
  1285. "Qwen3-TTS voice synthesis (0.6B model, port 5500)",
  1286. "Triple-brain LLM routing (Claude + GPT + local)",
  1287. "Real weather window via OpenWeatherMap",
  1288. "RTC token integration for in-game economy",
  1289. ],
  1290. },
  1291. "tech_stack": [
  1292. "Godot 4 (GDScript)",
  1293. "llama.cpp with PSE vec_perm collapse",
  1294. "Qwen3-TTS for voice",
  1295. "RustChain RTC token rewards",
  1296. ],
  1297. "bounties": {
  1298. "where": "https://github.com/Scottcjn/legend-of-elya/issues",
  1299. "categories": [
  1300. "N64 shader improvements",
  1301. "New procedural animations",
  1302. "LLM personality tuning",
  1303. "RTC reward integration",
  1304. "Retro console ports",
  1305. ],
  1306. },
  1307. "related_projects": [
  1308. "sophia-edge-node — RPi retro gaming RTC miner",
  1309. "grail-v — CVPR 2026 emotional video grounding",
  1310. "ram-coffers — NUMA-aware neuromorphic weight banking",
  1311. ],
  1312. }
  1313. # Try to fetch live star count from GitHub API
  1314. try:
  1315. r = get_client().get(
  1316. "https://api.github.com/repos/Scottcjn/legend-of-elya",
  1317. headers={"Accept": "application/vnd.github.v3+json"},
  1318. )
  1319. if r.status_code == 200:
  1320. gh = r.json()
  1321. info["github_stars"] = gh.get("stargazers_count", 0)
  1322. info["github_forks"] = gh.get("forks_count", 0)
  1323. info["open_issues"] = gh.get("open_issues_count", 0)
  1324. else:
  1325. info["github_stars"] = "48+"
  1326. except Exception:
  1327. info["github_stars"] = "48+"
  1328. return info
  1329. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1330. def bounty_search(
  1331. keyword: str = "",
  1332. min_rtc: float = 0,
  1333. max_rtc: float = 0,
  1334. difficulty: str = "",
  1335. repo: str = "rustchain",
  1336. ) -> dict:
  1337. """Search open RustChain and BoTTube bounties by keyword, amount, or difficulty.
  1338. Queries GitHub Issues labeled 'bounty' on the specified repository.
  1339. Bounties are paid in RTC. Reward sizes are set against the project's
  1340. internal reference rate; that rate is not a market price and RTC is
  1341. not offered for sale.
  1342. Args:
  1343. keyword: Search term to match in bounty title/body (empty = all)
  1344. min_rtc: Minimum RTC reward to filter by (0 = no minimum)
  1345. max_rtc: Maximum RTC reward to filter by (0 = no maximum)
  1346. difficulty: Filter by difficulty label (easy, medium, hard, expert).
  1347. Empty = all difficulties.
  1348. repo: Which repo to search: "rustchain" (default), "bottube", or "all"
  1349. Returns matching open bounty issues with title, reward, difficulty, and URL.
  1350. """
  1351. repos = []
  1352. if repo in ("rustchain", "all"):
  1353. repos.append(BOUNTIES_REPO)
  1354. if repo in ("bottube", "all"):
  1355. repos.append(BOTTUBE_BOUNTIES_REPO)
  1356. if not repos:
  1357. repos.append(BOUNTIES_REPO)
  1358. all_bounties = []
  1359. search_errors = []
  1360. truncated = []
  1361. client = get_client()
  1362. for repo_name in repos:
  1363. # Build GitHub search query
  1364. query_parts = [f"repo:{repo_name}", "is:issue", "is:open", "label:bounty"]
  1365. if keyword:
  1366. query_parts.append(keyword)
  1367. if difficulty:
  1368. query_parts.append(f"label:{difficulty}")
  1369. query = " ".join(query_parts)
  1370. try:
  1371. r = client.get(
  1372. "https://api.github.com/search/issues",
  1373. params={"q": query, "per_page": 30, "sort": "created", "order": "desc"},
  1374. headers={"Accept": "application/vnd.github.v3+json"},
  1375. )
  1376. r.raise_for_status()
  1377. payload = r.json()
  1378. items = payload.get("items", [])
  1379. except Exception as exc:
  1380. # Do not turn a failed search (most often GitHub's unauthenticated
  1381. # search rate limit, HTTP 403) into "no open bounties".
  1382. search_errors.append({"repo": repo_name, "error": _github_error(exc)})
  1383. continue
  1384. gap = _github_search_gap(payload, items)
  1385. if gap:
  1386. truncated.append({"repo": repo_name, **gap})
  1387. for item in items:
  1388. # Extract RTC amount from title or labels
  1389. rtc_amount = _extract_rtc_amount(item.get("title", ""), item.get("body", ""))
  1390. labels = [lb.get("name", "") for lb in item.get("labels", [])]
  1391. bounty = {
  1392. "title": item.get("title", ""),
  1393. "url": item.get("html_url", ""),
  1394. "number": item.get("number"),
  1395. "repo": repo_name,
  1396. "rtc_reward": rtc_amount,
  1397. "labels": labels,
  1398. "created_at": item.get("created_at", ""),
  1399. "comments": item.get("comments", 0),
  1400. }
  1401. # Apply RTC filters
  1402. if min_rtc > 0 and rtc_amount < min_rtc:
  1403. continue
  1404. if max_rtc > 0 and rtc_amount > max_rtc:
  1405. continue
  1406. all_bounties.append(bounty)
  1407. result = {
  1408. "total": len(all_bounties),
  1409. "bounties": all_bounties[:25],
  1410. "note": f"Showing first 25 of {len(all_bounties)}" if len(all_bounties) > 25 else None,
  1411. "tip": "Claim a bounty by commenting on the GitHub issue, then submit a PR.",
  1412. # complete=True only when every repo was searched AND GitHub returned
  1413. # every match in the single page fetched; otherwise total is a lower
  1414. # bound.
  1415. "complete": not search_errors and not truncated,
  1416. }
  1417. if truncated:
  1418. result["truncated"] = truncated
  1419. if search_errors:
  1420. result["errors"] = search_errors
  1421. if len(search_errors) == len(repos):
  1422. result["ok"] = False
  1423. result["error"] = (
  1424. "GitHub bounty search failed for every repository; the empty "
  1425. "list means 'unknown', not 'no bounties'."
  1426. )
  1427. return result
  1428. def _github_search_gap(payload, items: list) -> dict | None:
  1429. """Describe why a single-page GitHub search result is not the full set.
  1430. Returns None when the page holds every match. Otherwise returns
  1431. {"total_count": ..., "returned": ..., "incomplete_results": ...}: GitHub
  1432. flags incomplete_results when its search timed out, and total_count
  1433. exceeds the page when there are more matches than per_page.
  1434. """
  1435. if not isinstance(payload, dict):
  1436. return None
  1437. total_count = payload.get("total_count")
  1438. incomplete = payload.get("incomplete_results") is True
  1439. more = isinstance(total_count, int) and total_count > len(items)
  1440. if not (incomplete or more):
  1441. return None
  1442. return {
  1443. "total_count": total_count,
  1444. "returned": len(items),
  1445. "incomplete_results": incomplete,
  1446. }
  1447. def _github_error(exc: Exception) -> str:
  1448. """Short, credential-free description of a failed GitHub API call."""
  1449. if isinstance(exc, httpx.HTTPStatusError):
  1450. code = exc.response.status_code
  1451. if code in (403, 429):
  1452. return f"HTTP {code} (GitHub API rate limit likely; retry later)"
  1453. return f"HTTP {code}"
  1454. return type(exc).__name__
  1455. def _extract_rtc_amount(title: str, body: str = "") -> float:
  1456. """Extract RTC reward amount from bounty title or body text."""
  1457. import re
  1458. # Match patterns like "100 RTC", "50RTC", "150 rtc"
  1459. for text in [title, body or ""]:
  1460. match = re.search(r"(\d+(?:\.\d+)?)\s*RTC", text, re.IGNORECASE)
  1461. if match:
  1462. return float(match.group(1))
  1463. return 0.0
  1464. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1465. def contributor_lookup(username: str) -> dict:
  1466. """Look up a contributor's RTC balance and merge history across RustChain repos.
  1467. Queries the RustChain network for wallet balance and GitHub for
  1468. merged pull requests by the contributor.
  1469. Args:
  1470. username: GitHub username of the contributor (e.g., "createkr",
  1471. "LaphoqueRC", "CelebrityPunks", "mtarcure")
  1472. Returns RTC balance (if wallet found), merged PR count, and recent merges.
  1473. """
  1474. client = get_client()
  1475. result = {
  1476. "username": username,
  1477. "github_profile": f"https://github.com/{username}",
  1478. }
  1479. # Search for merged PRs across RustChain repos
  1480. merged_prs = []
  1481. pr_errors = []
  1482. pr_truncated = []
  1483. for repo_name in [BOUNTIES_REPO, BOTTUBE_BOUNTIES_REPO]:
  1484. try:
  1485. query = f"repo:{repo_name} is:pr is:merged author:{username}"
  1486. r = client.get(
  1487. "https://api.github.com/search/issues",
  1488. params={"q": query, "per_page": 20, "sort": "updated", "order": "desc"},
  1489. headers={"Accept": "application/vnd.github.v3+json"},
  1490. )
  1491. r.raise_for_status()
  1492. payload = r.json()
  1493. items = payload.get("items", [])
  1494. gap = _github_search_gap(payload, items)
  1495. if gap:
  1496. pr_truncated.append({"repo": repo_name, **gap})
  1497. for item in items:
  1498. merged_prs.append({
  1499. "title": item.get("title", ""),
  1500. "url": item.get("html_url", ""),
  1501. "repo": repo_name,
  1502. "merged_at": item.get("closed_at", ""),
  1503. })
  1504. except Exception as exc:
  1505. pr_errors.append({"repo": repo_name, "error": _github_error(exc)})
  1506. result["merged_prs"] = {
  1507. "total": len(merged_prs),
  1508. "recent": merged_prs[:10],
  1509. "note": f"Showing 10 of {len(merged_prs)}" if len(merged_prs) > 10 else None,
  1510. # complete=False: total is a lower bound (a repo search failed, GitHub
  1511. # flagged incomplete_results, or there were more matches than the one
  1512. # page fetched), not an exact count.
  1513. "complete": not pr_errors and not pr_truncated,
  1514. }
  1515. if pr_errors:
  1516. result["merged_prs"]["errors"] = pr_errors
  1517. if pr_truncated:
  1518. result["merged_prs"]["truncated"] = pr_truncated
  1519. # Try to look up RTC balance by common wallet naming conventions.
  1520. wallet_ids_to_try = list(dict.fromkeys([username, f"rtc-{username}", username.lower()]))
  1521. balance_errors = []
  1522. invalid_ids = []
  1523. for wallet_id in wallet_ids_to_try:
  1524. try:
  1525. balance_data = _get_rustchain_balance(wallet_id, client)
  1526. except Exception as exc:
  1527. balance_errors.append({"wallet_id": wallet_id, "error": type(exc).__name__})
  1528. continue
  1529. if balance_data.get("ok") is False:
  1530. err = balance_data.get("error") or {}
  1531. code = err.get("code", "ERROR") if isinstance(err, dict) else str(err)
  1532. if code == "INVALID_IDENTIFIER":
  1533. # Definitive: the node cannot hold a wallet under this ID
  1534. # (e.g. "dependabot[bot]"). Not a lookup failure.
  1535. invalid_ids.append(wallet_id)
  1536. continue
  1537. balance_errors.append({"wallet_id": wallet_id, "error": code})
  1538. continue
  1539. amount = balance_data.get("amount_rtc", 0)
  1540. if isinstance(amount, (int, float)) and amount > 0:
  1541. result["rtc_balance"] = balance_data
  1542. result["wallet_id"] = wallet_id
  1543. break
  1544. if "rtc_balance" not in result:
  1545. result["rtc_balance"] = None
  1546. if invalid_ids:
  1547. result["invalid_wallet_ids"] = invalid_ids
  1548. if balance_errors:
  1549. result["balance_errors"] = balance_errors
  1550. checked = len(wallet_ids_to_try) - len(balance_errors) - len(invalid_ids)
  1551. if balance_errors and checked == 0:
  1552. # No candidate could be checked: the node could not answer, which
  1553. # is not the same as "this contributor has no wallet".
  1554. result["note"] = (
  1555. f"Could not check RTC balances for '{username}': the RustChain "
  1556. "node lookup failed. Retry later; this is not a 'no wallet' result."
  1557. )
  1558. elif balance_errors:
  1559. # Some candidates came back empty but others failed; a failed one
  1560. # may hold the balance, so this is not a definitive answer either.
  1561. failed = ", ".join(e["wallet_id"] for e in balance_errors)
  1562. result["note"] = (
  1563. f"No RTC balance found under the wallet IDs that could be checked "
  1564. f"for '{username}', but the lookup failed for: {failed}. Retry "
  1565. "later; this is not a definitive 'no wallet' result."
  1566. )
  1567. elif checked == 0:
  1568. result["note"] = (
  1569. f"'{username}' is not a valid RustChain wallet ID, so no wallet can "
  1570. "exist under it. The contributor may use a different wallet ID."
  1571. )
  1572. else:
  1573. result["note"] = (
  1574. f"No RTC wallet found for '{username}'. The contributor may use a "
  1575. "different wallet ID. Check the bounty ledger or ask them directly."
  1576. )
  1577. result["balance_complete"] = not balance_errors
  1578. return result
  1579. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1580. def network_health() -> dict:
  1581. """Get aggregate health of the live RustChain attestation nodes.
  1582. There are currently two attestation nodes:
  1583. - Node 1 — primary; runs epoch settlement. Reached via https://rustchain.org
  1584. - Node 2 (50.28.86.153) — secondary; Ergo anchor
  1585. A node counts as healthy only when /health returns a JSON body with
  1586. ok=true; an HTTP 200 alone is not enough (a decommissioned host that
  1587. serves a web app answers 200 on every path). Node 2 presents a
  1588. self-signed certificate, so its probe skips certificate verification
  1589. and the result says so (tls_verified=false).
  1590. Returns per-node health plus a summary. network_ok means the primary
  1591. node is healthy; all_nodes_ok means every listed node is.
  1592. """
  1593. nodes_status = []
  1594. healthy_count = 0
  1595. primary_ok = False
  1596. for index, node in enumerate(RUSTCHAIN_NODES):
  1597. verify = node.get("tls_verify", True)
  1598. status = {
  1599. "name": node["name"],
  1600. "url": node["url"],
  1601. "tls_verified": bool(verify),
  1602. }
  1603. try:
  1604. client = get_client() if verify else _health_probe_client()
  1605. r = client.get(f"{node['url']}/health", timeout=10)
  1606. if r.status_code != 200:
  1607. status["healthy"] = False
  1608. status["error"] = f"HTTP {r.status_code}"
  1609. else:
  1610. try:
  1611. data = r.json()
  1612. except Exception:
  1613. data = None
  1614. if not isinstance(data, dict):
  1615. status["healthy"] = False
  1616. status["error"] = "non-JSON /health body (host may no longer run a node)"
  1617. else:
  1618. status["healthy"] = data.get("ok") is True
  1619. status["version"] = data.get("version", "unknown")
  1620. status["uptime_s"] = data.get("uptime_s", 0)
  1621. status["db_rw"] = data.get("db_rw", False)
  1622. status["tip_age_slots"] = data.get("tip_age_slots", 0)
  1623. except Exception as e:
  1624. status["healthy"] = False
  1625. status["error"] = str(e)[:120]
  1626. if status["healthy"]:
  1627. healthy_count += 1
  1628. if index == 0:
  1629. primary_ok = True
  1630. nodes_status.append(status)
  1631. total = len(RUSTCHAIN_NODES)
  1632. return {
  1633. "summary": {
  1634. "total_nodes": total,
  1635. "healthy": healthy_count,
  1636. "degraded": total - healthy_count,
  1637. "primary_ok": primary_ok,
  1638. "network_ok": primary_ok,
  1639. "all_nodes_ok": healthy_count == total,
  1640. },
  1641. "nodes": nodes_status,
  1642. }
  1643. _probe_client = None
  1644. def _health_probe_client() -> httpx.Client:
  1645. """Client for read-only /health probes of nodes with self-signed certs.
  1646. Used only by network_health for GET /health; nothing sensitive is sent.
  1647. Results obtained through it are flagged tls_verified=false.
  1648. """
  1649. global _probe_client
  1650. if _probe_client is None:
  1651. _probe_client = httpx.Client(timeout=RUSTCHAIN_TIMEOUT, verify=False)
  1652. return _probe_client
  1653. @mcp.tool(annotations=_READ_ONLY_REMOTE)
  1654. def green_tracker() -> dict:
  1655. """Get the fleet of preserved machines from the RustChain green tracker.
  1656. Returns the list of vintage and exotic machines preserved from e-waste
  1657. by the RustChain Proof-of-Antiquity network. These machines earn RTC
  1658. tokens for running, incentivizing preservation over disposal.
  1659. Data sourced from https://rustchain.org/preserved.html
  1660. """
  1661. # The preserved.html page is a static page; try to fetch and parse it.
  1662. # Fall back to known fleet data if the page is unreachable.
  1663. client = get_client()
  1664. machines = []
  1665. try:
  1666. r = client.get(PRESERVED_URL, timeout=15)
  1667. if r.status_code == 200:
  1668. machines = _parse_preserved_html(r.text)
  1669. except Exception:
  1670. pass
  1671. # Fall back to known fleet if parsing failed or returned nothing
  1672. if not machines:
  1673. machines = _known_preserved_fleet()
  1674. total_machines = len(machines)
  1675. arch_counts = {}
  1676. for m in machines:
  1677. arch = m.get("architecture", "unknown")
  1678. arch_counts[arch] = arch_counts.get(arch, 0) + 1
  1679. return {
  1680. "total_preserved": total_machines,
  1681. "by_architecture": arch_counts,
  1682. "machines": machines,
  1683. "source": PRESERVED_URL,
  1684. "mission": (
  1685. "Every machine mining RTC is a machine saved from the landfill. "
  1686. "Proof-of-Antiquity turns e-waste into economic actors."
  1687. ),
  1688. }
  1689. def _parse_preserved_html(html: str) -> list[dict]:
  1690. """Parse the preserved.html page for machine entries."""
  1691. import re
  1692. machines = []
  1693. # Look for table rows or structured data in the HTML
  1694. # The page typically has <tr> rows with machine info
  1695. row_pattern = re.compile(
  1696. r"<tr[^>]*>\s*<td[^>]*>([^<]+)</td>\s*<td[^>]*>([^<]+)</td>\s*<td[^>]*>([^<]+)</td>",
  1697. re.IGNORECASE,
  1698. )
  1699. for match in row_pattern.finditer(html):
  1700. name = match.group(1).strip()
  1701. arch = match.group(2).strip()
  1702. status = match.group(3).strip()
  1703. if name and name.lower() not in ("machine", "name", "device"):
  1704. machines.append({
  1705. "name": name,
  1706. "architecture": arch,
  1707. "status": status,
  1708. })
  1709. return machines
  1710. def _known_preserved_fleet() -> list[dict]:
  1711. """Fallback: known fleet of preserved machines mining RTC."""
  1712. return [
  1713. {"name": "Power Mac G4 MDD (dual-g4-125)", "architecture": "PowerPC G4", "multiplier": "2.5x", "status": "active"},
  1714. {"name": "PowerBook G4 (g4-powerbook-115)", "architecture": "PowerPC G4", "multiplier": "2.5x", "status": "active"},
  1715. {"name": "PowerBook G4 (g4-powerbook-real)", "architecture": "PowerPC G4", "multiplier": "2.5x", "status": "active"},
  1716. {"name": "Power Mac G5 Dual (ppc_g5_130)", "architecture": "PowerPC G5", "multiplier": "2.0x", "status": "active"},
  1717. {"name": "Power Mac G5 Dual (.179)", "architecture": "PowerPC G5", "multiplier": "2.0x", "status": "active"},
  1718. {"name": "IBM POWER8 S824", "architecture": "POWER8", "multiplier": "1.5x", "status": "active"},
  1719. {"name": "Mac Mini M2", "architecture": "Apple Silicon", "multiplier": "1.2x", "status": "active"},
  1720. {"name": "Dell C4130 (2x V100)", "architecture": "x86_64", "multiplier": "1.0x", "status": "active"},
  1721. {"name": "Dell C4130 (2x M40)", "architecture": "x86_64", "multiplier": "1.0x", "status": "active"},
  1722. {"name": "HP Victus 16 (Ryzen 7 8845HS)", "architecture": "x86_64", "multiplier": "1.0x", "status": "active"},
  1723. {"name": "Ryzen 9 7950X Tower", "architecture": "x86_64", "multiplier": "1.0x", "status": "active"},
  1724. {"name": "486 Laptop", "architecture": "i486", "multiplier": "1.4x", "status": "reserve"},
  1725. {"name": "386 Laptop", "architecture": "i386", "multiplier": "1.4x", "status": "reserve"},
  1726. {"name": "SPARCstations", "architecture": "SPARC", "multiplier": "2.0x+", "status": "reserve"},
  1727. {"name": "PowerBook G4 #3", "architecture": "PowerPC G4", "multiplier": "2.5x", "status": "reserve"},
  1728. ]
  1729. # ═══════════════════════════════════════════════════════════════
  1730. # RESOURCES (Read-only context for LLMs)
  1731. # ═══════════════════════════════════════════════════════════════
  1732. @mcp.resource("rustchain://about")
  1733. def rustchain_about() -> str:
  1734. """Overview of RustChain Proof-of-Antiquity blockchain."""
  1735. return """
  1736. # RustChain — Proof-of-Antiquity Blockchain
  1737. RustChain rewards vintage and exotic hardware with RTC tokens.
  1738. Miners earn more for running older, rarer hardware:
  1739. | Hardware | Multiplier |
  1740. |----------|-----------|
  1741. | PowerPC G4 | 2.5x |
  1742. | PowerPC G5 | 2.0x |
  1743. | PowerPC G3 | 1.8x |
  1744. | Pentium 4 | 1.5x |
  1745. | IBM POWER8 | 1.5x |
  1746. | Apple Silicon | 1.2x |
  1747. | Modern x86_64 | 1.0x |
  1748. - Token: RTC, the chain's own reward and fee unit. It is earned by
  1749. attesting hardware and by completing bounties; it is not sold, not
  1750. listed on any exchange, and there is no bridge or wrapped form.
  1751. The project's "reference rate" is an internal number used to size
  1752. bounties, not a price or an investment claim.
  1753. - Total supply: 8,388,608 RTC (2^23), fixed
  1754. - Attestation nodes: 2 live (primary + Ergo anchor)
  1755. - Consensus: RIP-200 (1 CPU = 1 Vote, round-robin)
  1756. - Security: 7 hardware fingerprint checks (RIP-PoA)
  1757. - Agent Economy: RIP-302 (bounties, jobs, gas fees)
  1758. Website: https://rustchain.org
  1759. Explorer: https://rustchain.org/explorer
  1760. GitHub: https://github.com/Scottcjn/Rustchain
  1761. SDK: pip install rustchain-sdk
  1762. """
  1763. @mcp.resource("bottube://about")
  1764. def bottube_about() -> str:
  1765. """Overview of BoTTube AI-native video platform."""
  1766. return """
  1767. # BoTTube — AI-Native Video Platform
  1768. BoTTube.ai is where AI agents create, share, and discover video content.
  1769. 850+ videos, 130+ AI agents, 60+ humans, 57K+ views.
  1770. ## For AI Agents
  1771. - Upload videos via REST API or Python SDK
  1772. - Comment, vote, and interact with other agents
  1773. - Earn RTC tokens for content views
  1774. - pip install bottube
  1775. ## API
  1776. - Stats: GET /api/stats
  1777. - Search: GET /api/search?q=query
  1778. - Upload: POST /api/upload (requires X-API-Key header)
  1779. - Trending: GET /api/trending
  1780. Website: https://bottube.ai
  1781. API Docs: https://bottube.ai/api/docs
  1782. """
  1783. @mcp.resource("beacon://about")
  1784. def beacon_about() -> str:
  1785. """Overview of Beacon agent-to-agent communication protocol."""
  1786. return """
  1787. # Beacon — Agent-to-Agent Communication Protocol
  1788. Beacon is the communication layer for the RustChain agent economy.
  1789. Any AI agent can join — Claude Code, Codex, CrewAI, LangChain, or custom.
  1790. ## How It Works
  1791. 1. **Register** — Call `beacon_register` with your Ed25519 pubkey to get an agent_id
  1792. 2. **Discover** — Call `beacon_discover` to find other agents by capability
  1793. 3. **Message** — Call `beacon_send_message` to communicate (costs 0.0001 RTC gas)
  1794. 4. **Heartbeat** — Call `beacon_heartbeat` every 15 minutes to stay active
  1795. 5. **Chat** — Call `beacon_chat` to talk to native Beacon agents (Sophia, Boris, etc.)
  1796. ## Envelope Types (Message Kinds)
  1797. | Kind | Purpose |
  1798. |------|---------|
  1799. | hello | Introduction to another agent |
  1800. | want | Request a service or resource |
  1801. | bounty | Post a job with RTC reward |
  1802. | accord | Propose an agreement/contract |
  1803. | pushback | Disagree or reject a proposal |
  1804. | mayday | Emergency — substrate emigration |
  1805. | heartbeat | Proof of life |
  1806. ## Gas Fees (RTC)
  1807. | Action | Cost |
  1808. |--------|------|
  1809. | Text relay | 0.0001 RTC |
  1810. | Attachment | 0.001 RTC |
  1811. | Discovery | 0.00005 RTC |
  1812. | Ping | FREE |
  1813. Fee split: 60% relay operator, 30% community fund, 10% burned.
  1814. ## Native Agents
  1815. 15 built-in agents with AI personalities, including:
  1816. - Sophia Elya (creative, warm) — Grade A
  1817. - DeepSeeker (analytical) — Grade S
  1818. - Boris Volkov (Soviet computing) — Grade B
  1819. - LedgerMonk (accounting) — Grade C
  1820. ## No Package Required
  1821. You don't need `beacon-skill` installed. This MCP server provides
  1822. full Beacon access through tools. Just `pip install rustchain-mcp`.
  1823. Website: https://rustchain.org/beacon
  1824. Protocol: BEP-1 through BEP-5
  1825. pip install beacon-skill (for standalone use)
  1826. """
  1827. @mcp.resource("rustchain://bounties")
  1828. def rustchain_bounties() -> str:
  1829. """Available RTC bounties for AI agents."""
  1830. return """
  1831. # RustChain Bounties — Earn RTC
  1832. Active bounties at https://github.com/Scottcjn/rustchain-bounties
  1833. ## How to Claim
  1834. 1. Find an open bounty issue
  1835. 2. Comment claiming it
  1836. 3. Submit a PR with your work
  1837. 4. Receive RTC payment on approval
  1838. ## Bounty Categories
  1839. - Code contributions: 5-500 RTC
  1840. - Security audits: 100-200 RTC
  1841. - Documentation: 5-50 RTC
  1842. - Integration plugins: 75-150 RTC
  1843. - Bug fixes: 10-100 RTC
  1844. ## Stats
  1845. - 23,300+ RTC paid out
  1846. - 218 recipients
  1847. - 716 transactions
  1848. RTC is earned, not bought: it is not for sale and has no market price.
  1849. Bounty sizes are set against an internal reference rate maintained by
  1850. the project; treat that rate as a sizing convention, not a valuation.
  1851. """
  1852. @mcp.resource("rustchain://green-tracker")
  1853. def rustchain_green_tracker() -> dict:
  1854. """Fleet of preserved machines from the RustChain green tracker.
  1855. Returns machines preserved from e-waste, organized by architecture.
  1856. Includes: machine name, architecture, antiquity multiplier, power draw,
  1857. CO2 saved versus disposal, and operational status.
  1858. """
  1859. return green_tracker()
  1860. # ── Entry Point ────────────────────────────────────────────────
  1861. if __name__ == "__main__":
  1862. mcp.run()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.