-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
241 lines (203 loc) · 7.63 KB
/
server.py
File metadata and controls
241 lines (203 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python3
"""
RustChain MCP Server
====================
Query the RustChain network directly from Claude Code or any MCP-compatible client.
Install & Register:
pip install mcp
claude mcp add rustchain -- python3 /path/to/server.py
Primary node: https://rustchain.org (50.28.86.131)
Fallback node: https://50.28.86.153
"""
import httpx
import json
from mcp.server.fastmcp import FastMCP
# ---------------------------------------------------------------------------
# Node config
# ---------------------------------------------------------------------------
PRIMARY_NODE = "https://rustchain.org"
FALLBACK_NODES = ["https://50.28.86.153"]
TIMEOUT = 8 # seconds
mcp = FastMCP("RustChain")
def _get(path: str, params: dict | None = None) -> dict:
"""GET from primary node, fall back to secondary nodes on failure."""
nodes = [PRIMARY_NODE] + FALLBACK_NODES
last_err = None
for base in nodes:
try:
r = httpx.get(f"{base}{path}", params=params, timeout=TIMEOUT)
r.raise_for_status()
return r.json()
except Exception as e:
last_err = e
raise RuntimeError(f"All nodes unreachable. Last error: {last_err}")
def _post(path: str, payload: dict) -> dict:
"""POST to primary node, fall back on failure."""
nodes = [PRIMARY_NODE] + FALLBACK_NODES
last_err = None
for base in nodes:
try:
r = httpx.post(f"{base}{path}", json=payload, timeout=TIMEOUT)
r.raise_for_status()
return r.json()
except Exception as e:
last_err = e
raise RuntimeError(f"All nodes unreachable. Last error: {last_err}")
# ---------------------------------------------------------------------------
# Required tools
# ---------------------------------------------------------------------------
@mcp.tool()
def rustchain_health() -> str:
"""Check the health of the RustChain primary node. Returns epoch, enrolled miners, and supply."""
try:
data = _get("/epoch")
miners = _get("/api/miners")
return json.dumps({
"status": "healthy",
"epoch": data.get("epoch"),
"slot": data.get("slot"),
"enrolled_miners": data.get("enrolled_miners"),
"blocks_per_epoch": data.get("blocks_per_epoch"),
"epoch_pot_rtc": data.get("epoch_pot"),
"total_supply_rtc": data.get("total_supply_rtc"),
"active_miners": len(miners) if isinstance(miners, list) else 0,
}, indent=2)
except Exception as e:
return json.dumps({"status": "unreachable", "error": str(e)})
@mcp.tool()
def rustchain_epoch() -> str:
"""Get current RustChain epoch information: epoch number, slot, pot, supply."""
try:
data = _get("/epoch")
return json.dumps(data, indent=2)
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_miners(limit: int = 20) -> str:
"""
List active RustChain miners with their hardware, scores, and last attestation.
Args:
limit: Maximum number of miners to return (default 20, max 100).
"""
try:
data = _get("/api/miners")
if isinstance(data, list):
data = data[:min(limit, 100)]
return json.dumps({"count": len(data), "miners": data}, indent=2)
return json.dumps(data, indent=2)
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_balance(address: str) -> str:
"""
Get the RTC balance for a wallet address.
Args:
address: RustChain wallet address (starts with RTC1...).
"""
try:
# Try direct balance lookup
data = _get(f"/api/balance/{address}")
return json.dumps(data, indent=2)
except Exception:
try:
# Fallback: scan balances list
all_balances = _get("/api/balances")
if isinstance(all_balances, list):
for entry in all_balances:
if entry.get("address", "").lower() == address.lower():
return json.dumps(entry, indent=2)
return json.dumps({"address": address, "balance_rtc": None, "note": "Address not found in balances"})
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_transfer(from_address: str, to_address: str, amount: float, signed_tx: str) -> str:
"""
Submit a signed RTC transfer transaction.
NOTE: Requires a pre-signed transaction payload. Does not hold private keys.
Args:
from_address: Sender wallet address.
to_address: Recipient wallet address.
amount: Amount of RTC to transfer.
signed_tx: Hex-encoded signed transaction payload.
"""
try:
payload = {
"from": from_address,
"to": to_address,
"amount": amount,
"signed_tx": signed_tx,
}
data = _post("/wallet/transfer/signed", payload)
return json.dumps(data, indent=2)
except Exception as e:
return json.dumps({"error": str(e), "note": "Transfer requires a valid pre-signed transaction."})
# ---------------------------------------------------------------------------
# Bonus tools
# ---------------------------------------------------------------------------
@mcp.tool()
def rustchain_ledger(limit: int = 50) -> str:
"""
Get recent RustChain transaction or epoch ledger entries.
Args:
limit: Number of entries to return (default 50).
"""
try:
data = _get("/api/fee_pool")
return json.dumps(data, indent=2)
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_register_wallet(public_key: str, signature: str | None = None) -> str:
"""
Register or resolve a RustChain wallet address.
Args:
public_key: The wallet public key to register or resolve.
signature: Optional signature for verified registration.
"""
try:
data = _get("/wallet/resolve", params={"key": public_key})
return json.dumps(data, indent=2)
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_bounties() -> str:
"""List open RustChain bounties and their reward amounts."""
try:
# Fetch from GitHub bounties repo
r = httpx.get(
"https://api.github.com/repos/Scottcjn/rustchain-bounties/issues",
params={"state": "open", "labels": "bounty", "per_page": 30},
timeout=TIMEOUT,
)
r.raise_for_status()
issues = r.json()
bounties = [
{
"number": i["number"],
"title": i["title"],
"url": i["html_url"],
"created_at": i["created_at"],
}
for i in issues
]
return json.dumps({"open_bounties": len(bounties), "bounties": bounties}, indent=2)
except Exception as e:
return json.dumps({"error": str(e)})
@mcp.tool()
def rustchain_nodes() -> str:
"""Get the list of known RustChain network nodes and their status."""
try:
data = _get("/api/nodes")
return json.dumps(data, indent=2)
except Exception:
# Return known hardcoded fallback
return json.dumps({
"primary": PRIMARY_NODE,
"fallback": FALLBACK_NODES,
"note": "Node list endpoint unavailable; using known topology.",
}, indent=2)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
mcp.run()