Tron MCP
MCP server: Tron MCP
Installation
npx tron-mcpAsk AI about Tron MCP
Powered by Claude Β· Grounded in docs
I know everything about Tron MCP. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
TRON MCP Server
A Model Context Protocol (MCP) server that provides access to TRON blockchain data via the TronScan API. This server allows you to query account information, transaction history, token balances, and transaction details for TRON addresses.
Features
- Account Information: Get detailed account data including TRX balance, bandwidth, energy, and transaction count
- Transaction History: Retrieve transaction history for any TRON address with pagination support
- Token Balances: Query TRC20 token balances for an address
- Transaction Details: Get detailed information about specific transactions
Installation
Prerequisites
- Python 3.11 or higher
- Windows, macOS, or Linux
- uv or pip package manager
Step-by-Step Installation
-
Clone or download this project
git clone <repository-url> cd TRON -
Install dependencies using uv (recommended)
# Using uv (recommended for Windows) uv sync # Or using pip pip install -e . -
Configure your API key (highly recommended for better performance)
a. Copy the example environment file:
copy .env.example .envb. Get your API key:
- Visit TronScan API Keys page
- Log in to your TronScan account
- Click "Add" to create a new API key
- Copy the generated API key
c. Edit
.envfile and replaceyour_api_key_herewith your actual API key:TRON_PRO_API_KEY=your_actual_api_key_here DEBUG=false -
Test the installation
# Test dependencies python -c "import mcp, httpx, dotenv; print('All dependencies installed!')" # Test API connection python -c "import asyncio; from main import fetch_from_tronscan; print('Testing API...'); asyncio.run(fetch_from_tronscan('accountv2', {'address': 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'})); print('API test successful!')"
Usage
Standalone Server Usage
To start the TRON MCP server directly:
# Using uv (recommended)
uv run main.py
# Or using Python directly
python main.py
The server will display:
INFO:tron-mcp-server:Starting TRON MCP Server...
INFO:tron-mcp-server:API key configured: d60633a9...
INFO:tron-mcp-server:Higher rate limits and better performance enabled
The server is now running and listening for MCP protocol messages via stdin/stdout.
Claude Desktop Integration
Configuration
-
Locate your Claude Desktop config file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
- Windows:
-
Add the TRON MCP server to your configuration:
For Windows (using uv - recommended):
{ "mcpServers": { "tron-blockchain": { "command": "C:\\Users\\YourUsername\\anaconda3\\Scripts\\uv.exe", "args": [ "--directory", "C:\\path\\to\\your\\TRON\\project", "run", "main.py" ], "env": { "TRON_PRO_API_KEY": "your_api_key_here", "DEBUG": "false" } } } }Alternative Windows configuration (direct Python):
{ "mcpServers": { "tron-blockchain": { "command": "C:\\path\\to\\your\\TRON\\project\\.venv\\Scripts\\python.exe", "args": ["C:\\path\\to\\your\\TRON\\project\\main.py"], "env": { "TRON_PRO_API_KEY": "your_api_key_here", "DEBUG": "false" } } } }For macOS/Linux:
{ "mcpServers": { "tron-blockchain": { "command": "uv", "args": [ "--directory", "/path/to/your/TRON/project", "run", "main.py" ], "env": { "TRON_PRO_API_KEY": "your_api_key_here", "DEBUG": "false" } } } } -
Restart Claude Desktop to load the new configuration
-
Verify the connection - Look for the TRON blockchain tools in Claude Desktop's interface
Using with Claude Desktop
Once configured, you can ask Claude to interact with the TRON blockchain:
Example queries:
- "What's the balance of TRON address TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t?"
- "Show me recent transactions for this TRON address"
- "What tokens does this address hold?"
- "Check the status of the TRON API connection"
- "Get details for transaction hash [hash]"
Testing the Server
Run the included test script to verify all functionality:
python test_server.py
Expected output:
=== TRON MCP Server Test ===
1. Testing list_tools...
β
Found 5 tools
2. Testing check_api_status...
β
API Status check successful
3. Testing get_account_info...
β
Account info retrieval successful
4. Testing get_token_balances...
β
Token balances retrieval successful
5. Testing get_account_transactions...
β
Transaction history retrieval successful
=== Test Complete ===
β
TRON MCP Server is working correctly!
Available Tools
1. get_account_info
Get detailed account information for a TRON address.
Parameters:
address(required): TRON address in Base58 format (e.g., TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t)
Example:
{
"name": "get_account_info",
"arguments": {
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
}
}
2. get_account_transactions
Get transaction history for a TRON address.
Parameters:
address(required): TRON address to querylimit(optional): Number of transactions to retrieve (default: 20, max: 200)start(optional): Starting index for pagination (default: 0)
Example:
{
"name": "get_account_transactions",
"arguments": {
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"limit": 10,
"start": 0
}
}
3. get_token_balances
Get token balances for a TRON address.
Parameters:
address(required): TRON address to query token balances for
Example:
{
"name": "get_token_balances",
"arguments": {
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
}
}
4. get_transaction_info
Get detailed information about a specific transaction.
Parameters:
hash(required): Transaction hash to query
Example:
{
"name": "get_transaction_info",
"arguments": {
"hash": "4c3c7849c72287d6d18a7e5f0f5e4b2e8d3e5f9a8b7c6d5e4f3a2b1c0d9e8f7a6"
}
}
5. check_api_status
Check API key status and rate limit information.
Parameters: None
Example:
{
"name": "check_api_status",
"arguments": {}
}
API Authentication
This server supports TronScan API key authentication for better performance and higher rate limits:
- Without API key: Limited to public rate limits
- With API key: Higher rate limits and better performance
Getting an API Key
- Visit the TronScan API Keys page
- Log in to your account
- Click "Add" to create a new API key
- Enter your application name and configure security options
- Copy the generated API key
- Add it to your
.envfile asTRON_PRO_API_KEY=your_actual_api_key
Environment Variables
Create a .env file in the project root with the following variables:
# Required: Your TronScan API key
TRON_PRO_API_KEY=your_actual_api_key_here
# Optional: Enable debug logging
DEBUG=false
API Endpoints Used
The server uses the following TronScan API endpoints:
/api/account- Account information/api/transaction- Transaction history/api/account/tokens- Token balances/api/transaction-info- Transaction details
Configuration
Environment Variables
The server uses the following environment variables (defined in .env file):
-
TRON_PRO_API_KEY: Your TronScan API key for authenticated requests- Required: For production use (recommended)
- Optional: For testing (uses public rate limits)
- Format: String (e.g.,
d60633a9-fa98-4f8f-a501-2952b2d86374)
-
DEBUG: Enable debug logging- Optional: Set to
trueto enable verbose logging - Default:
false - Format: Boolean string (
trueorfalse)
- Optional: Set to
API Rate Limits
| API Type | Rate Limit | Performance | Authentication |
|---|---|---|---|
| Public API | Lower limits | May be throttled | None required |
| Authenticated API | Higher limits | Better performance | API key required |
The server automatically includes the API key in request headers as TRON-PRO-API-KEY when configured.
TronScan API Endpoints Used
| Endpoint | Purpose | Example |
|---|---|---|
/api/accountv2 | Account information | Balance, transaction count |
/api/transaction | Transaction history | Recent transactions |
/api/account/tokens | Token balances | TRC20 token holdings |
/api/transaction-info | Transaction details | Specific transaction data |
Supported TRON Address Formats
- Base58 format:
TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t(recommended) - Hex format: Automatically converted to Base58 if needed
Data Conversion
- TRX amounts: Automatically converted from SUN to TRX (Γ· 1,000,000)
- Token amounts: Converted based on token decimals
- Timestamps: Unix timestamp format
- Addresses: Standardized to Base58 format
Error Handling
The server includes comprehensive error handling for:
API Errors
- 401 Unauthorized: Invalid or missing API key
- 404 Not Found: Invalid address or transaction hash
- 429 Rate Limited: Too many requests (upgrade to API key)
- 500 Server Error: TronScan API issues
Data Validation Errors
- Invalid TRON addresses: Automatic format validation
- Missing parameters: Clear error messages for required fields
- Network timeouts: Configurable timeout handling (30 seconds)
- JSON parsing errors: Robust data parsing with fallbacks
Connection Issues
- Network connectivity: Automatic retry logic
- DNS resolution: Clear error reporting
- SSL/TLS errors: Certificate validation
Example Error Responses
{
"error": "Invalid TRON address format",
"address": "invalid_address",
"expected_format": "Base58 (e.g., TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t)"
}
Troubleshooting
Common Issues
1. "Server disconnected" in Claude Desktop
Solution:
- Check that the Python path in
claude_desktop_config.jsonis correct - Verify the project directory path exists
- Ensure all dependencies are installed
- Try using
uvinstead of direct Python
2. "TRON_PRO_API_KEY not set" warning
Solution:
- Create
.envfile in project root - Add your API key:
TRON_PRO_API_KEY=your_key_here - Restart the server
3. "HTTP 401 Unauthorized" error
Solution:
- Verify your API key is correct
- Check API key hasn't expired
- Ensure no extra spaces in
.envfile
4. "No transactions found" for active address
Solution:
- Verify the address format is correct
- Check if address has any transactions on TronScan website
- Try a different address for testing
5. Python import errors
Solution:
# Reinstall dependencies
pip uninstall mcp httpx python-dotenv
pip install -e .
# Or using uv
uv sync --reinstall
Debug Mode
Enable debug logging for detailed troubleshooting:
- Set
DEBUG=truein.envfile - Restart the server
- Check logs for detailed API calls and responses
Logging Levels
| Level | When to Use | What You'll See |
|---|---|---|
INFO | Normal operation | API key status, server startup |
DEBUG | Troubleshooting | Full API requests/responses |
WARNING | Potential issues | Missing API key, rate limits |
ERROR | Failed operations | API errors, connection issues |
Example MCP Client Integration
Claude Desktop Integration (Complete Example)
Full claude_desktop_config.json with multiple MCP servers:
{
"mcpServers": {
"tron-blockchain": {
"command": "C:\\Users\\YourUsername\\anaconda3\\Scripts\\uv.exe",
"args": [
"--directory",
"C:\\Users\\YourUsername\\Downloads\\TRON",
"run",
"main.py"
],
"env": {
"TRON_PRO_API_KEY": "your_api_key_here",
"DEBUG": "false"
}
}
}
}
Other MCP Clients
1. Custom Python MCP Client
import asyncio
import json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def test_tron_server():
server_params = StdioServerParameters(
command="python",
args=["main.py"],
cwd="/path/to/TRON/project"
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Available tools:", [tool.name for tool in tools.tools])
# Call a tool
result = await session.call_tool("get_account_info", {
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
})
print("Result:", result.content[0].text)
if __name__ == "__main__":
asyncio.run(test_tron_server())
2. Node.js MCP Client
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
async function testTronServer() {
const transport = new StdioClientTransport({
command: 'python',
args: ['main.py'],
cwd: '/path/to/TRON/project'
});
const client = new Client({
name: "tron-test-client",
version: "1.0.0"
}, {
capabilities: {}
});
await client.connect(transport);
// List tools
const tools = await client.listTools();
console.log('Available tools:', tools.tools.map(t => t.name));
// Call tool
const result = await client.callTool({
name: "get_account_info",
arguments: {
address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
}
});
console.log('Result:', result.content[0].text);
await client.close();
}
testTronServer().catch(console.error);
Integration Examples
Real-world Usage Scenarios
-
DeFi Portfolio Tracker
# Track multiple TRON addresses addresses = ["TR7NHq...", "TKzxdS...", "TMuA6Y..."] for addr in addresses: balance = await call_tool("get_account_info", {"address": addr}) tokens = await call_tool("get_token_balances", {"address": addr}) -
Transaction Monitoring Bot
# Monitor recent transactions while True: txs = await call_tool("get_account_transactions", { "address": monitor_address, "limit": 10 }) # Process new transactions await asyncio.sleep(60) # Check every minute -
Blockchain Analytics Dashboard
# Comprehensive address analysis account_info = await call_tool("get_account_info", {"address": addr}) token_holdings = await call_tool("get_token_balances", {"address": addr}) recent_txs = await call_tool("get_account_transactions", {"address": addr})
Development
Project Structure
TRON/
βββ main.py # Main MCP server implementation
βββ test_server.py # Test script for all tools
βββ pyproject.toml # Dependencies and project metadata
βββ .env # Environment variables (API key)
βββ .env.example # Template for environment setup
βββ .gitignore # Git ignore rules
βββ README.md # This documentation
βββ .venv/ # Virtual environment (auto-created)
Adding New Tools
To extend the server with additional TRON blockchain functionality:
1. Add Tool Definition
@server.list_tools()
async def handle_list_tools() -> list[Tool]:
return [
# ...existing tools...
Tool(
name="get_block_info",
description="Get information about a specific block",
inputSchema={
"type": "object",
"properties": {
"block_number": {
"type": "integer",
"description": "Block number to query"
}
},
"required": ["block_number"]
}
)
]
2. Implement Tool Logic
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict | None) -> list[TextContent]:
# ...existing tool handlers...
elif name == "get_block_info":
block_number = arguments.get("block_number")
if not block_number:
return [TextContent(type="text", text="Error: Block number is required")]
try:
block_data = await fetch_from_tronscan("block", {"num": block_number})
# Process and return block data
return [TextContent(
type="text",
text=f"Block Information:\n{json.dumps(block_data, indent=2)}"
)]
except Exception as e:
return [TextContent(type="text", text=f"Error: {str(e)}")]
3. Add API Helper Functions
async def fetch_block_data(block_number: int) -> dict:
"""Fetch block data with additional processing"""
raw_data = await fetch_from_tronscan("block", {"num": block_number})
# Add custom processing logic here
processed_data = {
"block_number": raw_data.get("number"),
"timestamp": raw_data.get("timestamp"),
"transaction_count": len(raw_data.get("transactions", [])),
# ... additional processing
}
return processed_data
Testing New Features
1. Unit Testing
Create test cases for new tools:
# test_new_tools.py
import asyncio
from main import handle_call_tool
async def test_new_tool():
result = await handle_call_tool("get_block_info", {"block_number": 12345})
assert len(result) > 0
assert "Block Information" in result[0].text
print("β
New tool test passed!")
if __name__ == "__main__":
asyncio.run(test_new_tool())
2. Integration Testing
Add to test_server.py:
# Test new tool
print("6. Testing get_block_info...")
try:
result = await handle_call_tool("get_block_info", {"block_number": 12345})
print("β
Block info retrieval successful")
except Exception as e:
print(f"β Error getting block info: {e}")
API Documentation
TronScan API Reference
- Base URL:
https://apilist.tronscanapi.com/api - Authentication: Header
TRON-PRO-API-KEY: your_key - Rate Limits: Vary by endpoint and authentication status
Available Endpoints
| Endpoint | Method | Parameters | Description |
|---|---|---|---|
/accountv2 | GET | address | Account details |
/transaction | GET | address, limit, start | Transaction history |
/account/tokens | GET | address | Token balances |
/transaction-info | GET | hash | Transaction details |
/block | GET | num | Block information |
/contract | GET | contract | Smart contract data |
Code Style Guidelines
- Type hints: Use Python type hints for all functions
- Error handling: Comprehensive try-catch blocks
- Logging: Use appropriate log levels (DEBUG, INFO, WARNING, ERROR)
- Documentation: Docstrings for all functions
- Naming: Clear, descriptive variable and function names
Performance Optimization
1. Caching Responses
from functools import lru_cache
import time
@lru_cache(maxsize=100)
async def cached_account_info(address: str, cache_time: int):
"""Cache account info for 1 minute"""
return await fetch_from_tronscan("accountv2", {"address": address})
# Usage with cache timeout
cache_key = int(time.time() // 60) # 1-minute cache
account_data = await cached_account_info(address, cache_key)
2. Batch Requests
async def fetch_multiple_accounts(addresses: list[str]) -> dict:
"""Fetch multiple accounts concurrently"""
tasks = [
fetch_from_tronscan("accountv2", {"address": addr})
for addr in addresses
]
results = await asyncio.gather(*tasks, return_exceptions=True)
return dict(zip(addresses, results))
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-tool - Add your changes following the code style guidelines
- Add tests for new functionality
- Update documentation in README.md
- Submit a pull request with clear description
Versioning
- Major version: Breaking API changes
- Minor version: New features (backward compatible)
- Patch version: Bug fixes
Current version: 0.1.0 (defined in pyproject.toml)
License
This project is open source and available under the MIT License.
Support
Getting Help
- GitHub Issues: Report bugs or request features
- Documentation: Refer to this README for detailed instructions
- TronScan API: Official TronScan API Documentation
- MCP Protocol: Model Context Protocol Specification
Frequently Asked Questions
Q: Do I need an API key to use this server?
A: No, but it's highly recommended. Without an API key, you'll be limited to public rate limits which may be insufficient for production use.
Q: Can I use this with other AI clients besides Claude Desktop?
A: Yes! This server implements the standard MCP protocol and works with any MCP-compatible client.
Q: How do I get better performance?
A: 1) Get a TronScan API key, 2) Use the uv package manager, 3) Enable caching if you've modified the code.
Q: Is this server secure?
A: Yes, the API key is stored locally in your .env file and transmitted securely over HTTPS to TronScan's API.
Q: Can I modify this server for other blockchains?
A: Absolutely! The structure is designed to be extensible. You can adapt it for Ethereum, Bitcoin, or other blockchain APIs.
Changelog
Version 0.1.0 (Initial Release)
- β Account information queries
- β Transaction history retrieval
- β Token balance checking
- β Transaction detail lookup
- β API status monitoring
- β Comprehensive error handling
- β Windows/macOS/Linux support
- β Claude Desktop integration
- β TronScan API key authentication
Roadmap
Planned Features
- π Smart contract interaction tools
- π Block explorer functionality
- π DeFi protocol integrations
- π Real-time transaction monitoring
- π Multi-address portfolio tracking
- π Historical price data integration
- π Advanced analytics and reporting
Built with β€οΈ for the TRON ecosystem
This project is not affiliated with the TRON Foundation or TronScan. It's a community-driven tool for blockchain developers and enthusiasts.
