Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tronlink-mcp-core

License: MIT TRON Network TypeScript MCP TronLink npm

TronLink MCP Core Library — the foundational framework for building TronLink MCP servers.

Provides the MCP protocol layer, 56+ tool definitions, session manager interface (ISessionManager), cross-session knowledge store, and an extensible capability system. This is a core package — it does not run standalone. Consumers must implement ISessionManager to inject TronLink extension logic.

The library supports two operation modes:

  • Playwright Mode — browser automation tools for controlling the TronLink Chrome extension UI
  • Direct API Mode — on-chain operations, multi-signature management, and gas-free transfers via direct API calls (no browser required)

Architecture

┌──────────────────────────────────────┐
│       AI Agent (Claude, GPT, etc.)   │
└──────────────────┬───────────────────┘
                   │ MCP Protocol (stdio / JSON-RPC 2.0)
┌──────────────────▼───────────────────┐
│         MCP Server Instance          │
│  (created by createMcpServer())      │
│  ┌─────────────────────────────────┐ │
│  │  56+ tl_* tools                 │ │
│  │  ├─ Session (launch/cleanup)    │ │
│  │  ├─ State & Discovery           │ │
│  │  ├─ Navigation & Tabs           │ │
│  │  ├─ UI Interaction              │ │
│  │  ├─ Screenshot & Clipboard      │ │
│  │  ├─ Contract Seeding (e2e)      │ │
│  │  ├─ Knowledge Store             │ │
│  │  ├─ On-Chain (14 tools)  ←─ Direct API │ │
│  │  ├─ Multi-Sig (5 tools)  ←─ Direct API │ │
│  │  ├─ GasFree (3 tools)   ←─ Direct API │ │
│  │  └─ Batch (run_steps)           │ │
│  └─────────────────────────────────┘ │
│  ┌─────────────────────────────────┐ │
│  │  ISessionManager (interface)    │ │
│  │  Consumer must implement this   │ │
│  └─────────────────────────────────┘ │
│  ┌─────────────────────────────────┐ │
│  │  KnowledgeStore                 │ │
│  │  Disk-persistent, cross-session │ │
│  └─────────────────────────────────┘ │
└──────────────────┬───────────────────┘
                   │ Playwright (optional, for UI tools)
┌──────────────────▼───────────────────┐
│     Chrome + TronLink Extension      │
└──────────────────────────────────────┘

Installation

npm install @tronlink/mcp-core

Quick Start

import {
  createMcpServer,
  setSessionManager,
  type ISessionManager,
} from '@tronlink/mcp-core';

// 1. Implement the ISessionManager interface (consumer provides concrete logic)
class MyTronLinkSessionManager implements ISessionManager {
  // Session lifecycle
  hasActiveSession() { ... }
  launch(input) { ... }
  cleanup() { ... }
  // Page management
  getPage() { ... }
  getTrackedPages() { ... }
  // Extension state
  getExtensionState() { ... }
  // Navigation
  navigateToHome() { ... }
  navigateToSettings() { ... }
  // ... see full method list below
}

// 2. Register the SessionManager
setSessionManager(new MyTronLinkSessionManager());

// 3. Create and start the MCP server
const server = createMcpServer({
  name: 'TronLink MCP Server',
  version: '1.0.0',
});

await server.start(); // Listens for MCP requests via stdio

Feature Categories

1. MCP Server Foundation

  • stdio transport implementing the MCP protocol (AI Agent ↔ Server, JSON-RPC 2.0)
  • createMcpServer(config) factory to create server instances
  • Supports e2e (test) and prod (production) modes
  • Standardized tool response format: each response includes ok (success/failure), result/error, and meta (timestamp, sessionId, durationMs)
// Success response
{
  ok: true,
  result: { currentScreen: "home", accountAddress: "TXyz...", balanceTrx: "100" },
  meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1741504523", durationMs: 234 }
}

// Error response
{
  ok: false,
  error: { code: "TL_CLICK_FAILED", message: "Element not found", details: {...} },
  meta: { timestamp: "...", durationMs: 120 }
}

2. Browser & TronLink Session Management (Playwright Mode)

Tool Description
tl_launch Launch Chrome with TronLink extension (default: headed mode)
tl_cleanup Safely close browser and all services (chain node, fixture server, mock server)

Fixture presets:

  • default — unlocked wallet with TRX balance
  • onboarding — fresh install state (create/import wallet flow)
  • Custom — pass custom state via fixtureData
tl_launch({ fixture: "default", startChain: true, headless: false })
// → { sessionId: "tl-1741504523", extensionId: "abc...", extensionUrl: "chrome-extension://..." }

3. Navigation & Tab Management (Playwright Mode)

Tool Description
tl_navigate Navigate to TronLink screens: home, settings, send, receive, swap, assets, notification, address_book, node_management, dapp_list, or custom URL
tl_switch_to_tab Switch tabs by role (extension/dapp/notification) or URL pattern
tl_close_tab Close tabs by role or URL pattern
tl_wait_for_notification Wait for TronLink confirmation popup (transaction signing, connection requests)

Supported navigation targets (TronLink routes):

Target Route Description
home #/home Asset home page
settings #/settings Settings
send #/transfer/step1 Transfer
receive #/receive Receive
assets #/assets_management/my_assets Asset management
address_book #/address_book Address book
node_management #/node_management Node management
dapp_list #/dapp_list DApp browser

4. UI Interaction & Element Targeting (Playwright Mode)

Tool Description
tl_click Click element (3 targeting methods: a11yRef, testId, CSS selector)
tl_type Type text into input fields (supports clearing existing content)
tl_wait_for Wait for element state (visible / hidden / attached / detached)
tl_clipboard Read/write browser clipboard (copy addresses, mnemonics, etc.)

Three element targeting methods:

// Method 1: Accessibility reference (recommended, most AI-friendly)
tl_click({ a11yRef: "e5" })           // ref from tl_accessibility_snapshot

// Method 2: data-testid
tl_click({ testId: "send-button" })

// Method 3: CSS selector
tl_click({ selector: ".confirm-btn" })

5. Element Discovery & State Capture (Playwright Mode)

Tool Description
tl_get_state Get full wallet state: current screen, account address, network, TRX balance, energy, bandwidth
tl_list_testids List all data-testid attributes on current page with visibility
tl_accessibility_snapshot Get trimmed accessibility tree (ARIA) with deterministic refs (e1, e2, e3...)
tl_describe_screen Comprehensive screen description: wallet state + testIds + a11y tree + optional screenshot
tl_screenshot Capture TronLink or DApp screen (supports extension/dapp/active targets)

tl_accessibility_snapshot output example:

{
  "tree": {
    "role": "document",
    "children": [
      { "role": "heading", "name": "TronLink", "ref": "e1" },
      { "role": "button", "name": "Send", "ref": "e2" },
      { "role": "button", "name": "Receive", "ref": "e3" },
      { "role": "textbox", "name": "Search", "ref": "e4" }
    ]
  },
  "refCount": 4
}

Screen detection (auto-identifies 15 TronLink screens): home / login / settings / send / receive / sign / broadcast / assets / address_book / node_management / dapp_list / create_wallet / import_wallet / notification / unknown

6. On-Chain Operations (Direct API Mode)

Direct blockchain interactions via TronGrid REST API. No browser required. Requires OnChainCapability implementation from the consumer.

Tool Description
tl_chain_get_address Derive TRON address from configured private key
tl_chain_get_account Query account: TRX balance, bandwidth, energy, permissions
tl_chain_get_tokens Query TRC10 + TRC20 token balances for an address
tl_chain_send Send TRX, TRC10, or TRC20 tokens (signs locally, broadcasts)
tl_chain_get_tx Get transaction details by transaction ID
tl_chain_get_history Query transaction history with pagination
tl_chain_stake Freeze/unfreeze TRX for bandwidth or energy (Stake 2.0)
tl_chain_get_staking Query staking status: frozen amounts, votes, pending unfreezing
tl_chain_resource Delegate/undelegate bandwidth or energy resources
tl_chain_swap Estimate or execute token swap via SunSwap V2 router
tl_chain_swap_v3 Execute token swap via SunSwap V3 Smart Router
tl_chain_setup_multisig Configure multi-sig permissions (accountPermissionUpdate, costs 100 TRX)
tl_chain_create_multisig_tx Create unsigned multi-sig transaction with permission ID
tl_chain_sign_multisig_tx Sign multi-sig transaction with owner or co-signer key

Pre-checks: All transaction tools validate balances, permissions, and quotas before execution.

7. Multi-Signature Management (Direct API Mode)

REST + WebSocket integration with the TronLink multi-signature service. Requires MultiSigCapability implementation from the consumer.

Tool Description
tl_multisig_query_auth Query address multi-sig permissions (owner/active, thresholds, signer weights)
tl_multisig_submit_tx Submit signed multi-sig transaction (auto-broadcasts when threshold met)
tl_multisig_list_tx Query transaction list (pending/success/failed) with signature progress
tl_multisig_connect_ws Connect WebSocket for real-time pending tx notifications
tl_multisig_disconnect_ws Disconnect WebSocket listener

8. GasFree Transfers (Direct API Mode)

TRC20 token transfers where gas fees are paid by the GasFree service provider. Requires GasFreeCapability implementation from the consumer.

Tool Description
tl_gasfree_get_account Query account eligibility, supported tokens, and daily quota remaining
tl_gasfree_get_transactions Query gas-free transaction history with pagination
tl_gasfree_send Send TRC20 token with zero gas fee (pre-checks: eligibility, token support, quota, balance)

9. Local Blockchain & Contract Deployment (e2e Mode)

Tool Description
tl_seed_contract Deploy a single smart contract (e2e mode only)
tl_seed_contracts Batch deploy multiple contracts
tl_get_contract_address Query deployed contract address
tl_list_contracts List all deployed contracts

Supported contract types:

Contract Standard Description
trc20 TRC-20 Fungible token (like ERC-20)
trc721 TRC-721 NFT (like ERC-721)
trc1155 TRC-1155 Multi-token standard
trc10 TRC-10 TRON native token standard
multisig Multi-signature wallet contract
staking Staking contract
energy_rental Energy rental contract

Managed through ChainCapability which controls the local chain node (e.g., tron-quickstart) with test accounts and TRX balance allocation.

10. Cross-Session Knowledge Store

Automatically records every tool invocation (with timestamp, screen, target, result labels) for AI learning and optimization.

Tool Description
tl_knowledge_last Get the last N steps (supports session/global scope)
tl_knowledge_search Search history by tool name, screen, testId, or a11y name
tl_knowledge_summarize Auto-summarize session into a reusable "recipe" (step sequence)
tl_knowledge_sessions List recent sessions with metadata

Storage structure:

test-artifacts/llm-knowledge/
├── tl-1741504523/
│   ├── session.json
│   └── steps/
│       ├── 2026-03-09T10-15-23-456Z-tl_click.json
│       └── 2026-03-09T10-15-25-789Z-tl_type.json
└── tl-1741504600/
    └── ...

Sensitive data protection: Automatically redacts password, mnemonic, private key, and seed fields before recording.

11. Batch & Advanced Execution

Tool Description
tl_run_steps Execute multiple tool steps sequentially; supports stopOnError
tl_run_steps({
  steps: [
    { tool: "navigate", input: { target: "send" } },
    { tool: "type", input: { selector: "#address", text: "TXyz..." } },
    { tool: "type", input: { selector: "#amount", text: "100" } },
    { tool: "click", input: { selector: ".send-btn" } },
  ],
  stopOnError: true,
})

12. Context Switching

Tool Description
tl_set_context Switch between e2e (test, with local chain/fixture) and prod (real network)
tl_get_context Get current context, available capabilities, and session info

Extensible Capability System

Modular capability injection — consumers implement and inject as needed. The tool layer auto-detects available capabilities:

Capability Interface Description
BuildCapability build() / getExtensionPath() / isBuilt() Build TronLink extension from source
FixtureCapability start() / stop() / getDefaultState() / getOnboardingState() Manage wallet state JSON (preset state injection)
ChainCapability start() / stop() / isRunning() / getRpcUrl() / getTestAccounts() Control local TRON node
ContractSeedingCapability deployContract() / deployContracts() / listDeployedContracts() Contract deployment and registry
StateSnapshotCapability getState() / detectCurrentScreen() Extract high-level wallet state from UI
MockServerCapability start() / stop() / isRunning() Mock API server (isolated testing)
OnChainCapability getAddress() / getAccount() / send() / stake() / ... Direct on-chain operations via TronGrid API
MultiSigCapability queryAuth() / submitTx() / listTx() / connectWs() / ... Multi-signature service integration
GasFreeCapability getAccount() / getTransactions() / send() Gas-free TRC20 transfer service

ISessionManager Interface

The core interface consumers must implement (6 categories, 25+ methods):

interface ISessionManager {
  // Session lifecycle
  hasActiveSession(): boolean;
  getSessionId(): string | undefined;
  launch(input: SessionLaunchInput): Promise<SessionLaunchResult>;
  cleanup(): Promise<boolean>;

  // Page management
  getPage(): Page;                           // Get current active page
  setActivePage(page: Page): void;
  getTrackedPages(): TrackedPage[];          // All pages (extension/notification/dapp/other)
  classifyPageRole(page: Page): TabRole;
  getContext(): BrowserContext;

  // Extension state
  getExtensionState(): Promise<StateSnapshot>;

  // Accessibility ref mapping
  setRefMap(map: Map<string, string>): void;
  resolveA11yRef(ref: string): string | undefined;

  // Navigation
  navigateToHome(): Promise<void>;
  navigateToSettings(): Promise<void>;
  navigateToUrl(url: string): Promise<Page>;
  navigateToNotification(): Promise<Page>;
  waitForNotificationPage(timeoutMs: number): Promise<Page>;

  // Screenshot
  screenshot(options: SessionScreenshotOptions): Promise<ScreenshotResult>;

  // Capability injection (optional)
  getBuildCapability?(): BuildCapability | undefined;
  getFixtureCapability?(): FixtureCapability | undefined;
  getChainCapability?(): ChainCapability | undefined;
  getContractSeedingCapability?(): ContractSeedingCapability | undefined;
  getStateSnapshotCapability?(): StateSnapshotCapability | undefined;
  getMockServerCapability?(): MockServerCapability | undefined;
  getOnChainCapability?(): OnChainCapability | undefined;
  getMultiSigCapability?(): MultiSigCapability | undefined;
  getGasFreeCapability?(): GasFreeCapability | undefined;

  // Environment mode
  getEnvironmentMode(): EnvironmentMode;
  setContext(context: 'e2e' | 'prod'): void;
  getContextInfo(): { currentContext, hasSession, capabilities, canSwitchContext };
}

Complete Tool Reference

# Tool Category Mode Description
1 tl_launch Session Playwright Launch Chrome with TronLink extension
2 tl_cleanup Session Playwright Safely close browser and services
3 tl_get_state State Playwright Get wallet state: screen, account, network, balance, energy, bandwidth
4 tl_describe_screen State Playwright Comprehensive screen description (state + testIds + a11y + screenshot)
5 tl_list_testids Discovery Playwright List all data-testid attributes on page
6 tl_accessibility_snapshot Discovery Playwright Get trimmed a11y tree with deterministic refs
7 tl_navigate Navigation Playwright Navigate to TronLink screen or URL
8 tl_switch_to_tab Navigation Playwright Switch tab by role or URL
9 tl_close_tab Navigation Playwright Close tab by role or URL
10 tl_wait_for_notification Navigation Playwright Wait for confirmation popup
11 tl_click Interaction Playwright Click element (a11yRef / testId / selector)
12 tl_type Interaction Playwright Type text (supports clear)
13 tl_wait_for Interaction Playwright Wait for element state
14 tl_scroll Interaction Playwright Scroll page or element
15 tl_keyboard Interaction Playwright Send keyboard events
16 tl_evaluate Interaction Playwright Execute JavaScript in page context
17 tl_screenshot Screenshot Playwright Capture screen
18 tl_clipboard Utility Playwright Read/write clipboard
19 tl_seed_contract Contract Playwright (e2e) Deploy single contract
20 tl_seed_contracts Contract Playwright (e2e) Batch deploy contracts
21 tl_get_contract_address Contract Playwright (e2e) Query deployed contract address
22 tl_list_contracts Contract Playwright (e2e) List all deployed contracts
23 tl_set_context Context Both Switch e2e / prod mode
24 tl_get_context Context Both Get current context info
25 tl_knowledge_last Knowledge Both Get last N steps
26 tl_knowledge_search Knowledge Both Search step history
27 tl_knowledge_summarize Knowledge Both Generate reusable session recipe
28 tl_knowledge_sessions Knowledge Both List recent sessions
29 tl_run_steps Batch Both Execute multiple steps sequentially
30 tl_list_flows Flows Both List built-in flow recipes
31 tl_chain_get_address On-Chain Direct API Derive address from private key
32 tl_chain_get_account On-Chain Direct API Query account details
33 tl_chain_get_tokens On-Chain Direct API Query TRC10 + TRC20 balances
34 tl_chain_send On-Chain Direct API Send TRX/TRC10/TRC20
35 tl_chain_get_tx On-Chain Direct API Get transaction details
36 tl_chain_get_history On-Chain Direct API Query transaction history
37 tl_chain_stake On-Chain Direct API Freeze/unfreeze TRX (Stake 2.0)
38 tl_chain_get_staking On-Chain Direct API Query staking status
39 tl_chain_resource On-Chain Direct API Delegate/undelegate resources
40 tl_chain_swap On-Chain Direct API SunSwap V2 token swap
41 tl_chain_swap_v3 On-Chain Direct API SunSwap V3 token swap
42 tl_chain_setup_multisig On-Chain Direct API Configure multi-sig permissions
43 tl_chain_create_multisig_tx On-Chain Direct API Create unsigned multi-sig tx
44 tl_chain_sign_multisig_tx On-Chain Direct API Sign multi-sig transaction
45 tl_multisig_query_auth Multi-Sig Direct API Query multi-sig permissions
46 tl_multisig_submit_tx Multi-Sig Direct API Submit signed multi-sig tx
47 tl_multisig_list_tx Multi-Sig Direct API List multi-sig transactions
48 tl_multisig_connect_ws Multi-Sig Direct API Connect WebSocket for notifications
49 tl_multisig_disconnect_ws Multi-Sig Direct API Disconnect WebSocket
50 tl_gasfree_get_account GasFree Direct API Query account eligibility & quota
51 tl_gasfree_get_transactions GasFree Direct API Query gas-free tx history
52 tl_gasfree_send GasFree Direct API Send TRC20 with zero gas

Use Cases

  • AI agent automated testing: TronLink transfer, signing, DApp connection flows
  • On-chain operations: Direct TRX/token transfers, staking, and swaps without browser
  • Multi-sig management: Set up permissions, create/sign transactions, monitor via WebSocket
  • Gas-free transfers: Zero-cost TRC20 transfers for end-user applications
  • UI validation: Screenshot + state comparison to verify new features
  • Contract testing: Auto-deploy TRC-20/721 contracts → interact → verify transactions
  • LLM-controlled wallet: Natural language step-by-step wallet control with path memory
  • Regression testing: Replay verified flows via knowledge store recipes

Project Structure

tronlink-mcp-core/
├── src/
│   ├── index.ts                          # Main entry, all public exports
│   ├── capabilities/
│   │   ├── types.ts                      # 9 capability interface definitions
│   │   ├── context.ts                    # Environment config (e2e/prod)
│   │   └── index.ts
│   ├── launcher/
│   │   ├── extension-id-resolver.ts      # Resolve extension ID from browser
│   │   ├── extension-readiness.ts        # Detect extension load / login / onboarding
│   │   └── index.ts
│   ├── mcp-server/
│   │   ├── server.ts                     # createMcpServer() main factory
│   │   ├── session-manager.ts            # ISessionManager interface + global holder
│   │   ├── knowledge-store.ts            # Cross-session knowledge persistence
│   │   ├── discovery.ts                  # Page inspection (testId collection, a11y snapshot)
│   │   ├── schemas.ts                    # Zod input validation schemas (all tools)
│   │   ├── constants.ts                  # Timeouts, limits, URL constants
│   │   ├── types/                        # All type definitions
│   │   │   ├── responses.ts              # McpResponse / SuccessResponse / ErrorResponse
│   │   │   ├── errors.ts                 # ErrorCodes enum (20 error codes)
│   │   │   ├── tool-inputs.ts            # Tool input types
│   │   │   ├── tool-outputs.ts           # Tool output types
│   │   │   ├── session.ts                # Session state types
│   │   │   ├── step-record.ts            # Step record types
│   │   │   ├── knowledge.ts              # Prior knowledge types
│   │   │   └── discovery.ts              # TestIdItem / A11yNodeTrimmed
│   │   ├── tools/                        # Tool handlers
│   │   │   ├── definitions.ts            # Tool registry + routing
│   │   │   ├── run-tool.ts               # Execution wrapper (auto-logs to knowledge store)
│   │   │   ├── helpers.ts                # Observation collection, screen detection, data redaction
│   │   │   ├── launch.ts                 # tl_launch
│   │   │   ├── cleanup.ts                # tl_cleanup
│   │   │   ├── state.ts                  # tl_get_state
│   │   │   ├── navigation.ts             # tl_navigate / switch_to_tab / close_tab / wait_for_notification
│   │   │   ├── interaction.ts            # tl_click / tl_type / tl_wait_for
│   │   │   ├── screenshot.ts             # tl_screenshot
│   │   │   ├── discovery-tools.ts        # tl_list_testids / accessibility_snapshot / describe_screen
│   │   │   ├── clipboard.ts              # tl_clipboard
│   │   │   ├── seeding.ts                # tl_seed_contract / seed_contracts / get_contract_address
│   │   │   ├── context.ts                # tl_set_context / tl_get_context
│   │   │   ├── knowledge.ts              # tl_knowledge_last / search / summarize / sessions
│   │   │   ├── on-chain.ts               # tl_chain_* (14 tools with pre-checks)
│   │   │   ├── multisig.ts               # tl_multisig_* (5 tools)
│   │   │   ├── gasfree.ts                # tl_gasfree_* (3 tools)
│   │   │   └── batch.ts                  # tl_run_steps + tool registry
│   │   └── utils/
│   │       ├── response.ts               # createSuccessResponse / createErrorResponse
│   │       ├── errors.ts                 # extractErrorMessage
│   │       ├── targets.ts                # validateTargetSelection
│   │       └── zod-to-json-schema.ts     # Zod → JSON Schema conversion (MCP compatible)
│   └── utils/
│       └── index.ts                      # generateSessionId / generateFilesafeTimestamp
├── package.json
├── tsconfig.json
└── tsconfig.build.json

Requirements

  • Node.js >= 20
  • Playwright >= 1.49 (peer dependency, only needed for Playwright mode tools)
  • TypeScript >= 5.3
  • Dependencies: @modelcontextprotocol/sdk ^1.12.0, zod ^3.23.0

License

MIT License Copyright (c) 2026 TronLink

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages