Skip to content

Commit 0af4a2d

Browse files
authored
Merge pull request #12 from xueyuanying/feature/ai
Feature/ai
2 parents eedbfe5 + f7e3a70 commit 0af4a2d

9 files changed

Lines changed: 2653 additions & 2655 deletions
Lines changed: 376 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,376 @@
1+
# MCP Server TronLink
2+
3+
## Overview
4+
5+
**GitHub**: [https://github.com/TronLink/mcp-server-tronlink](https://github.com/TronLink/mcp-server-tronlink)
6+
7+
**mcp-server-tronlink** is a production-ready Model Context Protocol (MCP) server that enables AI agents (Claude, GPT, etc.) to interact with the TRON blockchain through natural language. Built on `@tronlink/tronlink-mcp-core`, it provides **56+ tools** across two complementary operation modes.
8+
9+
**Key Highlights:**
10+
- Dual-mode architecture: **Playwright** (browser automation) + **Direct API** (on-chain operations)
11+
- 32 built-in Flow Recipes with pre-checks and dependency resolution
12+
- Non-custodial local transaction signing via `@noble/curves`
13+
- Multi-signature management with real-time WebSocket monitoring
14+
- Gas-free TRC20 transfers via GasFree service integration
15+
16+
---
17+
18+
## Architecture
19+
20+
```
21+
AI Agent (Claude Desktop / Claude Code)
22+
| (MCP Protocol — stdio / JSON-RPC 2.0)
23+
v
24+
TronLink MCP Server
25+
├── Playwright Mode ─── TronLinkSessionManager
26+
│ └── Browser automation + TronLink extension UI control
27+
├── Direct API Mode
28+
│ ├── TronLinkOnChainCapability (14 tools)
29+
│ ├── TronLinkMultiSigCapability (5 tools)
30+
│ └── TronLinkGasFreeCapability (3 tools)
31+
├── Utility Capabilities
32+
│ ├── TronLinkBuildCapability (extension build)
33+
│ ├── TronLinkStateSnapshotCapability (UI state extraction)
34+
│ └── TRON Crypto Utils (address derivation, signing, Base58)
35+
└── Flow Recipes (32 built-in recipes with pre-checks)
36+
|
37+
v
38+
TronGrid API / Multi-Sig Service / GasFree Service
39+
|
40+
v
41+
TRON Blockchain
42+
```
43+
44+
Both modes can run simultaneously and tools are auto-enabled based on configuration.
45+
46+
---
47+
48+
## Dual-Mode Operation
49+
50+
### Mode 1: Playwright (Browser Automation)
51+
52+
Controls the TronLink Chrome extension via Playwright Chromium. Ideal for **E2E testing, UI validation, and DApp interaction**.
53+
54+
**Capabilities:**
55+
- Launch browser with `--load-extension` flag for TronLink
56+
- Auto-detect extension ID from Chrome API
57+
- Multi-tab tracking with automatic role classification (extension / notification / dapp / other)
58+
- DOM-based state extraction (TRON address, TRX balance, network detection)
59+
- Screenshot capture with base64 encoding
60+
- Automatic browser dialog handling (alerts, confirms, prompts)
61+
62+
**27 Playwright tools include:** `tl_launch`, `tl_cleanup`, `tl_navigate`, `tl_click`, `tl_type`, `tl_screenshot`, `tl_accessibility_snapshot`, `tl_describe_screen`, etc.
63+
64+
### Mode 2: Direct API (On-Chain)
65+
66+
Operates directly against TronGrid REST API — no browser required. Ideal for **account queries, transfers, swaps, staking, and multi-sig management**.
67+
68+
**22 API tools grouped into:**
69+
70+
| Group | Tools | Description |
71+
|-------|-------|-------------|
72+
| On-Chain | 14 | Transfer, stake, swap, query, multisig setup |
73+
| Multi-Signature | 5 | Permission query, tx submit, WebSocket monitoring |
74+
| GasFree | 3 | Zero-gas TRC20 transfers |
75+
76+
---
77+
78+
## Core Components
79+
80+
### 1. TronLinkSessionManager
81+
82+
Full browser lifecycle management:
83+
84+
| Method | Description |
85+
|--------|-------------|
86+
| `launch()` | Initialize browser with TronLink extension |
87+
| `getExtensionState()` | Extract wallet state from UI |
88+
| `navigateToUrl()` | Navigate to a specific URL |
89+
| `navigateToNotification()` | Open TronLink notification popup |
90+
| `screenshot()` | Capture current UI state |
91+
| `getTrackedPages()` | List all open browser tabs |
92+
| `cleanup()` | Graceful shutdown of all resources |
93+
94+
**Screen Detection:** Auto-detects 15 TronLink screens: `home`, `login`, `settings`, `send`, `receive`, `sign`, `broadcast`, `assets`, `address_book`, `node_management`, `dapp_list`, `create_wallet`, `import_wallet`, `notification`, `unknown`.
95+
96+
### 2. TronLinkOnChainCapability (14 Tools)
97+
98+
Direct API wrapper for TronGrid:
99+
100+
**Query Operations:**
101+
- `getAddress()` — Derive TRON address from configured private key
102+
- `getAccount()` — Balance, bandwidth, energy, permissions
103+
- `getTokens()` — TRC10 and TRC20 token balances
104+
- `getTransaction()` — Transaction details by txID
105+
- `getHistory()` — Transaction history with pagination
106+
- `getStakingInfo()` — Staking status (frozen amounts, votes, unfreezing)
107+
108+
**Transaction Operations:**
109+
- `send()` — Transfer TRX, TRC10, or TRC20 tokens
110+
- `stake()` — Freeze/unfreeze TRX for bandwidth or energy (Stake 2.0)
111+
- `resource()` — Delegate/undelegate bandwidth or energy
112+
- `swap()` — Token swap via SunSwap V2
113+
- `swapV3()` — Token swap via SunSwap V3 Smart Router
114+
115+
**Multi-Sig Operations:**
116+
- `setupMultisig()` — Configure multi-sig permissions
117+
- `createMultisigTx()` — Create unsigned multi-sig transaction
118+
- `signMultisigTx()` — Sign multi-sig transaction
119+
120+
### 3. TronLinkMultiSigCapability (5 Tools)
121+
122+
REST + WebSocket API for TRON multi-signature service:
123+
124+
- `queryAuth()` — Query multi-sig permissions (owner/active, thresholds, weights)
125+
- `submitTransaction()` — Submit signed transaction (auto-broadcast when threshold reached)
126+
- `queryTransactionList()` — List transactions with filtering
127+
- `connectWebSocket()` — Real-time transaction monitoring
128+
- `disconnectWebSocket()` — Stop monitoring
129+
130+
**Implementation:** HmacSHA256 signature generation for API auth, UUID-based request signing, supports both Nile testnet and Mainnet credentials.
131+
132+
### 4. TronLinkGasFreeCapability (3 Tools)
133+
134+
Zero-gas TRC20 transfers via GasFree service:
135+
136+
- `getAccount()` — Query eligibility, supported tokens, daily quota
137+
- `getTransactions()` — Query gas-free transaction history
138+
- `send()` — Send TRC20 with zero gas fee
139+
140+
### 5. TRON Cryptography Utils
141+
142+
Pure cryptographic functions — no external service calls:
143+
144+
```
145+
privateKeyToAddress() 64-char hex → TRON address (base58 + hex)
146+
signTransaction() raw_data_hex → 65-byte signature
147+
base58CheckEncode() Payload → base58check address
148+
base58CheckDecode() TRON address → 21-byte payload
149+
addressToHex() T-address → 0x41... hex
150+
hexToAddress() 0x41... → T-address
151+
```
152+
153+
Uses `@noble/curves` (secp256k1 ECDSA) and `@noble/hashes` (Keccak-256, SHA256).
154+
155+
---
156+
157+
## Flow Recipes (32 Built-In)
158+
159+
Pre-configured multi-step workflows with dependency checks and parameter templates.
160+
161+
### Playwright Flows
162+
| Flow | Description |
163+
|------|-------------|
164+
| `importWalletFlow` | Import wallet with seed phrase |
165+
| `switchNetworkFlow` | Switch to Mainnet/Nile/Shasta |
166+
| `enableTestNetworksFlow` | Enable testnet visibility |
167+
| `transferTrxFlow` | TRX transfer via UI |
168+
| `transferTokenFlow` | Token transfer via UI |
169+
170+
### On-Chain Flows (11)
171+
| Flow | Description |
172+
|------|-------------|
173+
| `chainCheckBalanceFlow` | Query balance |
174+
| `chainTransferTrxFlow` | TRX transfer with pre-checks |
175+
| `chainTransferTrc20Flow` | TRC20 transfer with pre-checks |
176+
| `chainStakeFlow` | Stake TRX |
177+
| `chainUnstakeFlow` | Unstake TRX |
178+
| `chainGetStakingFlow` | Query staking info |
179+
| `chainDelegateResourceFlow` | Delegate bandwidth/energy |
180+
| `chainUndelegateResourceFlow` | Undelegate resources |
181+
| `chainSetupMultisigFlow` | Setup multi-sig permissions |
182+
| `chainCreateMultisigTxFlow` | Create unsigned multi-sig tx |
183+
| `chainSwapV3Flow` | SunSwap V3 token swap |
184+
185+
### Multi-Sig Flows (6)
186+
| Flow | Description |
187+
|------|-------------|
188+
| `multisigQueryAuthFlow` | Query permissions |
189+
| `multisigListTransactionsFlow` | List pending transactions |
190+
| `multisigMonitorFlow` | WebSocket real-time monitoring |
191+
| `multisigStopMonitorFlow` | Stop monitoring |
192+
| `multisigSubmitTxFlow` | Submit signed transaction |
193+
| `multisigCheckFlow` | Full status check |
194+
195+
### GasFree Flows (3)
196+
| Flow | Description |
197+
|------|-------------|
198+
| `gasfreeCheckAccountFlow` | Query eligibility |
199+
| `gasfreeTransactionHistoryFlow` | Query history |
200+
| `gasfreeSendFlow` | Gas-free TRC20 transfer |
201+
202+
---
203+
204+
## Configuration
205+
206+
### Environment Variables
207+
208+
**Playwright Mode:**
209+
210+
| Variable | Description |
211+
|----------|-------------|
212+
| `TRONLINK_EXTENSION_PATH` | TronLink extension build directory |
213+
| `TRONLINK_SOURCE_PATH` | Enable build capability |
214+
| `TL_MODE` | `e2e` (test) or `prod` (production) |
215+
| `TL_HEADLESS` | Browser headless mode |
216+
| `TL_SLOW_MO` | Playwright slow-motion delay (ms) |
217+
218+
**TronGrid API:**
219+
220+
| Variable | Description |
221+
|----------|-------------|
222+
| `TL_TRONGRID_URL` | Full-node API URL |
223+
| `TL_TRONGRID_API_KEY` | API key (required for Mainnet) |
224+
| `TL_CHAIN_PRIVATE_KEY` | 64-char hex private key |
225+
| `TL_SUNSWAP_ROUTER` | SunSwap V2 router address |
226+
| `TL_SUNSWAP_V3_ROUTER` | SunSwap V3 smart router address |
227+
| `TL_WTRX_ADDRESS` | WTRX contract address |
228+
229+
**Multi-Signature Service:**
230+
231+
| Variable | Description |
232+
|----------|-------------|
233+
| `TL_MULTISIG_BASE_URL` | API base URL |
234+
| `TL_MULTISIG_SECRET_ID` | Project credential |
235+
| `TL_MULTISIG_SECRET_KEY` | HmacSHA256 signing key |
236+
| `TL_MULTISIG_CHANNEL` | Channel/project name |
237+
| `TL_MULTISIG_OWNER_KEY` | Owner private key |
238+
| `TL_MULTISIG_COSIGNER_KEY` | Co-signer private key |
239+
240+
**GasFree Service:**
241+
242+
| Variable | Description |
243+
|----------|-------------|
244+
| `TL_GASFREE_BASE_URL` | Service URL |
245+
| `TL_GASFREE_API_KEY` | API key |
246+
| `TL_GASFREE_API_SECRET` | API secret |
247+
248+
### Integration Options
249+
250+
**1. Project-Level MCP Config (`.mcp.json`)**
251+
252+
Auto-detected by Claude Code:
253+
```json
254+
{
255+
"mcpServers": {
256+
"tronlink": {
257+
"command": "node",
258+
"args": ["./dist/index.js"],
259+
"env": {
260+
"TL_TRONGRID_URL": "https://nile.trongrid.io",
261+
"TL_CHAIN_PRIVATE_KEY": "your-64-char-hex-key"
262+
}
263+
}
264+
}
265+
}
266+
```
267+
268+
**2. Claude Desktop**
269+
270+
Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
271+
```json
272+
{
273+
"mcpServers": {
274+
"tronlink": {
275+
"command": "node",
276+
"args": ["/absolute/path/to/dist/index.js"],
277+
"env": { ... }
278+
}
279+
}
280+
}
281+
```
282+
283+
**3. Claude Code Global Settings**
284+
285+
Edit `~/.claude/settings.json` or `.claude/settings.json`.
286+
287+
**4. Any MCP Client**
288+
289+
Supports stdio transport protocol — compatible with any MCP-compliant client.
290+
291+
---
292+
293+
## Project Structure
294+
295+
```
296+
mcp-server-tronlink/
297+
├── src/
298+
│ ├── index.ts # Server entry, config, capability registration
299+
│ ├── session-manager.ts # Browser lifecycle (TronLinkSessionManager)
300+
│ ├── capabilities/
301+
│ │ ├── on-chain.ts # 14 on-chain operations (TronGrid)
302+
│ │ ├── multisig.ts # 5 multi-sig operations (REST + WS)
303+
│ │ ├── gasfree.ts # 3 gas-free transfer operations
304+
│ │ ├── build.ts # Extension webpack build
305+
│ │ ├── state-snapshot.ts # UI state extraction
306+
│ │ └── tron-crypto.ts # Address derivation, signing, Base58
307+
│ └── flows/
308+
│ ├── index.ts # Flow registry (32 recipes)
309+
│ ├── import-wallet.ts # Wallet import flow
310+
│ ├── switch-network.ts # Network switching flows
311+
│ ├── transfer-trx.ts # Transfer flows
312+
│ ├── multisig.ts # 6 multi-sig flows
313+
│ ├── onchain.ts # 11 on-chain flows
314+
│ └── gasfree.ts # 3 gas-free flows
315+
├── dist/ # Compiled output
316+
├── .mcp.json # MCP configuration
317+
├── .env.example # Environment variable reference
318+
├── package.json
319+
├── tsconfig.json
320+
└── README.md
321+
```
322+
323+
---
324+
325+
## Dependencies
326+
327+
| Package | Version | Purpose |
328+
|---------|---------|---------|
329+
| `@noble/curves` | ^2.0.1 | secp256k1 ECDSA signing |
330+
| `@noble/hashes` | ^2.0.1 | Keccak-256, SHA256 |
331+
| `@tronlink/tronlink-mcp-core` | local | Core MCP server framework |
332+
| `playwright` | ^1.49.0 | Browser automation |
333+
| `ws` | ^8.18.0 | WebSocket (multi-sig monitoring) |
334+
335+
---
336+
337+
## Security Model
338+
339+
| Aspect | Implementation |
340+
|--------|----------------|
341+
| Key storage | Injected via MCP JSON `env` field, never in `.env` files |
342+
| Key exposure | No key material logged to stderr |
343+
| Signing | Local transaction signing — keys never transmitted |
344+
| Pre-checks | All transactions validate before execution |
345+
| Git safety | Config files in `.gitignore` prevent accidental commits |
346+
| Default network | Nile testnet with safe defaults |
347+
348+
---
349+
350+
## Typical Usage Scenarios
351+
352+
1. **Wallet Automation** — Import wallet, check balance, send transfers
353+
2. **DApp Testing** — Launch browser, connect wallet, sign transactions, verify state
354+
3. **On-Chain Trading** — Direct API swaps, staking, token transfers without browser
355+
4. **Multi-Sig Workflows** — Set up permissions, submit/monitor transactions
356+
5. **Gas-Free Operations** — TRC20 transfers without TRX balance requirements
357+
6. **Infrastructure Testing** — Contract deployment, fixture management, mock servers
358+
359+
---
360+
361+
## Quick Start
362+
363+
```bash
364+
# 1. Build
365+
npm install && npm run build
366+
367+
# 2. Configure (Nile testnet example)
368+
export TL_TRONGRID_URL="https://nile.trongrid.io"
369+
export TL_CHAIN_PRIVATE_KEY="your-64-char-hex-private-key"
370+
371+
# 3. Run with Claude Code
372+
# Add to .mcp.json and use naturally:
373+
# "Check my TRX balance"
374+
# "Send 10 TRX to TAddress..."
375+
# "Swap 100 TRX for USDT on SunSwap V3"
376+
```

0 commit comments

Comments
 (0)