Skip to content

Fukuii MCP Enhancement Plan

Complete Agent Control via Model Context Protocol

Version: 1.0.0
Date: 2025-12-12
Status: Planning Phase
Goal: Enable complete agent control over Fukuii node through MCP interface

Table of Contents


Executive Summary

This plan outlines the roadmap to transform Fukuii's MCP integration from basic read-only capabilities to complete agent-controlled node management. The goal is to enable AI agents to fully operate, monitor, troubleshoot, and optimize an Ethereum Classic node through the Model Context Protocol.

Key Metrics: - Current MCP Coverage: 7.2% (7/97 endpoints) - Target MCP Coverage: 85% (critical production endpoints) - Implementation Timeline: 6 phases over 12-16 weeks - New MCP Components: 45+ tools, 20+ resources, 15+ prompts

Benefits: 1. Autonomous Operations: Agents can start, stop, and configure node operations 2. Proactive Monitoring: Continuous health checks and anomaly detection 3. Intelligent Troubleshooting: Automated diagnosis and remediation 4. Performance Optimization: Dynamic configuration tuning based on conditions 5. Enhanced Security: Secure, auditable agent access with granular permissions


Current State Analysis

Existing MCP Implementation

Namespace: MCP
Endpoints: 7
Tools: 5 (mostly unimplemented)
Resources: 5 (mostly returning placeholder data)
Prompts: 3 (diagnostic guidance)

Current Tools

  1. mcp_node_info - Returns static build information
  2. ⚠️ mcp_node_status - Placeholder (TODO: implement actor queries)
  3. ⚠️ mcp_blockchain_info - Placeholder (TODO: implement)
  4. ⚠️ mcp_sync_status - Placeholder (TODO: implement)
  5. ⚠️ mcp_peer_list - Placeholder (TODO: implement)

Current Resources

  1. ⚠️ fukuii://node/status - Returns placeholder JSON
  2. ⚠️ fukuii://node/config - Returns placeholder JSON
  3. ⚠️ fukuii://blockchain/latest - Returns placeholder JSON
  4. ⚠️ fukuii://peers/connected - Returns placeholder JSON
  5. ⚠️ fukuii://sync/status - Returns placeholder JSON

Current Prompts

  1. mcp_node_health_check - Guides comprehensive health check
  2. mcp_sync_troubleshooting - Guides sync issue diagnosis
  3. mcp_peer_management - Guides peer connection management

Strengths

  • ✅ Solid MCP protocol foundation (JSON-RPC integration)
  • ✅ Clean modular architecture (Tools/Resources/Prompts separation)
  • ✅ Good documentation structure
  • ✅ Security-conscious design patterns

Weaknesses

  • ❌ Most tools return placeholder data (not querying actual node state)
  • ❌ No write operations (cannot control node)
  • ❌ Limited observability (missing key metrics)
  • ❌ No mining control capabilities
  • ❌ No transaction management
  • ❌ No peer management tools
  • ❌ Missing configuration management

Vision for Complete Agent Control

Definition of "Complete Control"

An AI agent has complete control when it can autonomously:

  1. Monitor Node State
  2. Query all relevant blockchain data
  3. Access real-time sync status
  4. Monitor peer connections
  5. Track resource utilization
  6. Retrieve transaction and block data

  7. Manage Operations

  8. Start/stop mining
  9. Configure mining parameters
  10. Manage peer connections
  11. Control sync modes
  12. Adjust resource limits

  13. Handle Transactions

  14. Query transaction status
  15. Estimate gas costs
  16. Monitor pending transactions
  17. Query account balances and nonces

  18. Troubleshoot Issues

  19. Diagnose sync problems
  20. Identify performance bottlenecks
  21. Detect network issues
  22. Analyze error patterns
  23. Recommend remediation steps

  24. Optimize Performance

  25. Tune configuration parameters
  26. Manage peer quality
  27. Optimize resource allocation
  28. Adjust sync strategies

  29. Ensure Security

  30. Monitor for security issues
  31. Manage blacklists
  32. Control access
  33. Audit operations

Agent Capabilities Model

┌─────────────────────────────────────────────────┐
│              AI Agent                           │
│         (Claude, GPT, etc.)                     │
└───────────────┬─────────────────────────────────┘
                │ MCP Protocol (JSON-RPC 2.0)
┌───────────────▼─────────────────────────────────┐
│          MCP Server (Fukuii)                    │
│  ┌──────────────────────────────────────────┐   │
│  │  Tools (Actions)                         │   │
│  │  - Query operations                      │   │
│  │  - Control operations                    │   │
│  │  - Management operations                 │   │
│  └──────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────┐   │
│  │  Resources (Data)                        │   │
│  │  - Real-time state                       │   │
│  │  - Historical data                       │   │
│  │  - Configuration                         │   │
│  └──────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────┐   │
│  │  Prompts (Guidance)                      │   │
│  │  - Diagnostic workflows                  │   │
│  │  - Operational procedures                │   │
│  │  - Best practices                        │   │
│  └──────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────┐   │
│  │  Security Layer                          │   │
│  │  - Authentication                        │   │
│  │  - Authorization                         │   │
│  │  - Audit logging                         │   │
│  │  - Rate limiting                         │   │
│  └──────────────────────────────────────────┘   │
└───────────────┬─────────────────────────────────┘
                │ Internal APIs
┌───────────────▼─────────────────────────────────┐
│        Fukuii Node Components                   │
│  - PeerManagerActor                             │
│  - SyncController                               │
│  - MiningCoordinator                            │
│  - Blockchain                                   │
│  - TxPool                                       │
└─────────────────────────────────────────────────┘

Gap Analysis

Critical Gaps for Node Control

1. Real Data Access (High Priority)

Current: All MCP tools return placeholder data
Needed: Integration with actual node actors and state - Query PeerManagerActor for peer information - Query SyncController for sync status - Query Blockchain for block data - Query TxPool for transaction status - Query MiningCoordinator for mining status

2. Write Operations (High Priority)

Current: All operations are read-only
Needed: Control capabilities - Start/stop mining - Connect/disconnect peers - Add/remove peer blacklist entries - Configure node parameters - Trigger maintenance operations

3. Comprehensive Monitoring (Medium Priority)

Current: Limited status information
Needed: Full observability - Detailed performance metrics - Resource utilization tracking - Historical trend data - Error and warning logs - Network statistics

4. Transaction Management (Medium Priority)

Current: No transaction tools
Needed: Transaction observability - Query transaction status - Monitor pending transactions - Estimate gas costs - Query account states

5. Configuration Management (Medium Priority)

Current: Placeholder config data
Needed: Configuration access and validation - Read current configuration - Validate configuration changes - Report configuration issues - Recommend optimal settings

6. Diagnostic Capabilities (Low Priority)

Current: Basic prompt guidance
Needed: Advanced diagnostics - Automated health checks - Performance profiling - Root cause analysis - Predictive issue detection


Proposed MCP Enhancements

Phase 1: Core Node Control

Timeline: Weeks 1-3
Goal: Enable basic node state monitoring and control

New Tools (8)

Read Operations
  1. mcp_node_status_detailed
  2. Description: Get comprehensive node status with real actor data
  3. Queries: PeerManagerActor, SyncController, Blockchain, TxPool
  4. Returns: JSON with sync state, peer count, best block, network health
  5. Input Schema: None
  6. Example:

    {
      "syncing": true,
      "currentBlock": 19500000,
      "targetBlock": 19500100,
      "peerCount": 25,
      "pendingTransactions": 1234,
      "chainId": 61,
      "protocolVersion": 65
    }
    

  7. mcp_blockchain_latest_block

  8. Description: Get latest block details with full transaction info
  9. Queries: Blockchain
  10. Returns: Complete block data with transactions
  11. Input Schema: { includeTransactions: boolean }

  12. mcp_sync_progress

  13. Description: Get detailed sync progress metrics
  14. Queries: SyncController
  15. Returns: Sync mode, progress percentage, ETA, speed metrics
  16. Input Schema: None

  17. mcp_network_health

  18. Description: Assess overall network health
  19. Queries: PeerManagerActor, SyncController
  20. Returns: Health score, peer diversity, sync reliability
  21. Input Schema: None
Write Operations
  1. mcp_node_config_validate
  2. Description: Validate configuration without applying
  3. Validates: Configuration syntax and semantics
  4. Returns: Validation results, warnings, recommendations
  5. Input Schema: { config: object }
  6. Safety: 🟢 Safe (read-only validation)

  7. mcp_health_check

  8. Description: Run comprehensive automated health check
  9. Checks: Sync status, peer quality, disk space, performance
  10. Returns: Health report with issues and recommendations
  11. Input Schema: { deep: boolean }

  12. mcp_metrics_snapshot

  13. Description: Capture current metrics snapshot
  14. Captures: All key performance indicators
  15. Returns: Timestamped metrics bundle
  16. Input Schema: None

  17. mcp_logs_recent

  18. Description: Get recent log entries
  19. Queries: Log system
  20. Returns: Filtered log entries
  21. Input Schema: { level: string, count: int, since: timestamp }

Enhanced Resources (7)

  1. fukuii://node/status/live
  2. Real-time node status with actor queries
  3. Auto-refresh capability
  4. WebSocket notification support

  5. fukuii://node/config/current

  6. Current running configuration
  7. Read from actual config system
  8. Include defaults and overrides

  9. fukuii://blockchain/chain-head

  10. Latest block with full details
  11. Transaction summaries
  12. State root information

  13. fukuii://sync/progress

  14. Detailed sync progress
  15. Historical sync rate
  16. ETA calculation

  17. fukuii://metrics/current

  18. Current performance metrics
  19. CPU, memory, disk usage
  20. Network bandwidth

  21. fukuii://logs/errors

  22. Recent error logs
  23. Filtered by severity
  24. With context

  25. fukuii://health/report

  26. Automated health assessment
  27. Issue prioritization
  28. Remediation suggestions

Implementation Notes

  • Complete actor integration for all existing placeholder tools
  • Add proper error handling and timeout management
  • Implement caching for expensive queries
  • Add metrics collection for tool usage

Phase 2: Mining & Block Production

Timeline: Weeks 4-5
Goal: Full mining lifecycle management

New Tools (7)

  1. mcp_mining_status
  2. Get current mining status and configuration
  3. Query MiningCoordinator for real status
  4. Return hashrate, coinbase, block count
  5. Input: None
  6. Safety: 🟢 Safe

  7. mcp_mining_start

  8. Start mining operation
  9. Validate pre-conditions (sync status, config)
  10. Return success status
  11. Input: { threads?: number, coinbase?: address }
  12. Safety: 🟡 Caution (state modification)

  13. mcp_mining_stop

  14. Stop mining operation gracefully
  15. Wait for current block to complete
  16. Return final statistics
  17. Input: { graceful: boolean }
  18. Safety: 🟡 Caution (state modification)

  19. mcp_mining_configure

  20. Update mining parameters
  21. Validate configuration
  22. Apply without restart if possible
  23. Input: { coinbase?: address, extraData?: string, gasFloor?: number, gasCeil?: number }
  24. Safety: 🟡 Caution (configuration change)

  25. mcp_mining_statistics

  26. Get detailed mining statistics
  27. Include hashrate history, block production, rewards
  28. Return last 24h, 7d, 30d statistics
  29. Input: { period?: string }
  30. Safety: 🟢 Safe

  31. mcp_block_production_rate

  32. Calculate block production rate
  33. Compare to network average
  34. Identify performance issues
  35. Input: { blocks?: number }
  36. Safety: 🟢 Safe

  37. mcp_mining_profitability

  38. Estimate mining profitability
  39. Consider electricity, hashrate, difficulty
  40. Return ROI estimate
  41. Input: { electricityCost?: number, hashpower?: number }
  42. Safety: 🟢 Safe

Enhanced Resources (4)

  1. fukuii://mining/status
  2. Current mining status
  3. Live hashrate
  4. Recent blocks mined

  5. fukuii://mining/config

  6. Mining configuration
  7. Coinbase address
  8. Gas limits

  9. fukuii://mining/statistics

  10. Historical mining data
  11. Block production over time
  12. Reward calculations

  13. fukuii://mining/profitability

  14. Profitability calculations
  15. Network difficulty trends
  16. Cost/benefit analysis

New Prompts (2)

  1. mcp_mining_optimization
  2. Guide for optimizing mining setup
  3. Hardware recommendations
  4. Configuration tuning
  5. Profitability improvement

  6. mcp_mining_troubleshooting

  7. Diagnose mining issues
  8. Low hashrate investigation
  9. Block production problems
  10. Network difficulty analysis

Phase 3: Transaction & Account Management

Timeline: Weeks 6-7
Goal: Complete transaction lifecycle visibility

New Tools (8)

  1. mcp_transaction_get
  2. Get transaction details by hash
  3. Include receipt if mined
  4. Show pending status if not mined
  5. Input: { hash: string }
  6. Safety: 🟢 Safe

  7. mcp_transaction_pending_list

  8. List pending transactions
  9. Filter by age, gas price, from/to
  10. Sort by priority
  11. Input: { limit?: number, filter?: object }
  12. Safety: 🟢 Safe

  13. mcp_transaction_trace

  14. Get transaction execution trace
  15. Show all internal calls
  16. Include gas usage details
  17. Input: { hash: string }
  18. Safety: 🟢 Safe

  19. mcp_account_balance

  20. Get account balance at block
  21. Support historical queries
  22. Include pending balance
  23. Input: { address: string, block?: string }
  24. Safety: 🟢 Safe

  25. mcp_account_transactions

  26. List transactions for account
  27. Support pagination
  28. Filter by type (sent/received)
  29. Input: { address: string, limit?: number, offset?: number }
  30. Safety: 🟢 Safe

  31. mcp_gas_price_estimate

  32. Estimate optimal gas price
  33. Consider network congestion
  34. Provide fast/medium/slow options
  35. Input: { priority?: string }
  36. Safety: 🟢 Safe

  37. mcp_gas_limit_estimate

  38. Estimate gas limit for transaction
  39. Use eth_estimateGas internally
  40. Add safety margin
  41. Input: { from: string, to: string, data?: string, value?: string }
  42. Safety: 🟢 Safe

  43. mcp_contract_info

  44. Get contract information
  45. Show bytecode size
  46. Detect contract type if possible
  47. Input: { address: string }
  48. Safety: 🟢 Safe

Enhanced Resources (5)

  1. fukuii://transaction/{hash}
  2. Transaction details by hash
  3. Receipt information
  4. Execution trace

  5. fukuii://transactions/pending

  6. All pending transactions
  7. Mempool statistics
  8. Fee market data

  9. fukuii://account/{address}/balance

  10. Account balance
  11. Historical balance
  12. Pending transactions

  13. fukuii://account/{address}/transactions

  14. Transaction history
  15. Paginated results
  16. Filter capabilities

  17. fukuii://gas/price-oracle

  18. Gas price recommendations
  19. Network congestion data
  20. Historical price trends

New Prompts (2)

  1. mcp_transaction_stuck
  2. Diagnose stuck transaction
  3. Recommend solutions
  4. Guide replacement/cancellation

  5. mcp_gas_optimization

  6. Optimize gas usage
  7. Find gas-efficient patterns
  8. Avoid common pitfalls

Phase 4: Network & Peer Management

Timeline: Weeks 8-9
Goal: Full peer lifecycle control

New Tools (10)

  1. mcp_peers_list_detailed
  2. List all peers with full details
  3. Include connection quality metrics
  4. Show geographic distribution
  5. Input: None
  6. Safety: 🟢 Safe

  7. mcp_peer_info

  8. Get detailed info about specific peer
  9. Show connection stats
  10. Protocol version info
  11. Input: { peerId: string }
  12. Safety: 🟢 Safe

  13. mcp_peer_connect

  14. Connect to specific peer
  15. Support enode URLs
  16. Validate before connecting
  17. Input: { enode: string }
  18. Safety: 🟡 Caution (network change)

  19. mcp_peer_disconnect

  20. Disconnect from peer
  21. Optionally blacklist
  22. Provide reason
  23. Input: { peerId: string, blacklist?: boolean, reason?: string }
  24. Safety: 🟡 Caution (network change)

  25. mcp_peer_quality_analyze

  26. Analyze peer quality
  27. Score peers by reliability
  28. Identify bad actors
  29. Input: { peerId?: string }
  30. Safety: 🟢 Safe

  31. mcp_blacklist_list

  32. List all blacklisted peers
  33. Show reasons and timestamps
  34. Support filtering
  35. Input: None
  36. Safety: 🟢 Safe

  37. mcp_blacklist_add

  38. Add peer to blacklist
  39. Specify duration and reason
  40. Auto-disconnect if connected
  41. Input: { address: string, duration?: number, reason: string }
  42. Safety: 🟡 Caution (network policy change)

  43. mcp_blacklist_remove

  44. Remove peer from blacklist
  45. Allow reconnection
  46. Log the action
  47. Input: { address: string }
  48. Safety: 🟡 Caution (network policy change)

  49. mcp_network_topology

  50. Visualize network connections
  51. Show peer relationships
  52. Identify network partitions
  53. Input: None
  54. Safety: 🟢 Safe

  55. mcp_discovery_status

    • Get peer discovery status
    • Show discovery mechanisms
    • Active discovery nodes
    • Input: None
    • Safety: 🟢 Safe

Enhanced Resources (6)

  1. fukuii://peers/all
  2. Complete peer list
  3. Connection details
  4. Quality metrics

  5. fukuii://peers/{id}/details

  6. Specific peer information
  7. Connection history
  8. Performance stats

  9. fukuii://network/topology

  10. Network graph data
  11. Peer relationships
  12. Connection map

  13. fukuii://blacklist/entries

  14. All blacklisted peers
  15. Reasons and timestamps
  16. Expiration info

  17. fukuii://discovery/state

  18. Discovery mechanism status
  19. Boot nodes
  20. DHT state

  21. fukuii://network/statistics

  22. Network-wide statistics
  23. Bandwidth usage
  24. Message counts

New Prompts (3)

  1. mcp_peer_connectivity_issues
  2. Diagnose connectivity problems
  3. Too few peers
  4. Connection failures
  5. Firewall/NAT issues

  6. mcp_peer_diversity_optimization

  7. Improve peer diversity
  8. Geographic distribution
  9. Client diversity
  10. Reduce centralization

  11. mcp_network_attack_detection

  12. Detect network attacks
  13. Eclipse attack prevention
  14. Sybil attack detection
  15. DDoS mitigation

Phase 5: Advanced Monitoring & Diagnostics

Timeline: Weeks 10-11
Goal: Proactive issue detection and resolution

New Tools (7)

  1. mcp_health_check_comprehensive
  2. Run all health checks
  3. Produce detailed report
  4. Prioritize issues
  5. Input: None
  6. Safety: 🟢 Safe

  7. mcp_performance_profile

  8. Profile node performance
  9. Identify bottlenecks
  10. Resource utilization analysis
  11. Input: { duration?: number }
  12. Safety: 🟢 Safe

  13. mcp_issue_detect_sync

  14. Detect sync issues automatically
  15. Compare with peers
  16. Identify stuck sync
  17. Input: None
  18. Safety: 🟢 Safe

  19. mcp_issue_detect_peers

  20. Detect peer issues
  21. Too few/many peers
  22. Bad peer detection
  23. Input: None
  24. Safety: 🟢 Safe

  25. mcp_logs_analyze

  26. Analyze logs for patterns
  27. Detect error trends
  28. Find warning clusters
  29. Input: { hours?: number }
  30. Safety: 🟢 Safe

  31. mcp_metrics_trend

  32. Analyze metric trends
  33. Detect anomalies
  34. Predict issues
  35. Input: { metric: string, period?: string }
  36. Safety: 🟢 Safe

  37. mcp_diagnostic_report

  38. Generate comprehensive diagnostic report
  39. Include all subsystems
  40. Export for support
  41. Input: None
  42. Safety: 🟢 Safe

Enhanced Resources (5)

  1. fukuii://diagnostics/health
  2. Overall health status
  3. All subsystem checks
  4. Issue summary

  5. fukuii://diagnostics/performance

  6. Performance metrics
  7. Bottleneck analysis
  8. Optimization suggestions

  9. fukuii://diagnostics/issues

  10. Detected issues list
  11. Severity ranking
  12. Remediation steps

  13. fukuii://logs/analysis

  14. Log pattern analysis
  15. Error clustering
  16. Trend detection

  17. fukuii://metrics/trends

  18. Metric trend data
  19. Anomaly detection
  20. Predictions

New Prompts (3)

  1. mcp_performance_degradation
  2. Diagnose performance issues
  3. Slow block processing
  4. High resource usage
  5. Optimization steps

  6. mcp_error_investigation

  7. Investigate error patterns
  8. Root cause analysis
  9. Historical comparison
  10. Resolution steps

  11. mcp_predictive_maintenance

  12. Predict future issues
  13. Preventive actions
  14. Capacity planning
  15. Upgrade recommendations

Phase 6: Configuration & Optimization

Timeline: Weeks 12-13
Goal: Dynamic configuration and intelligent optimization

New Tools (5)

  1. mcp_config_get_full
  2. Get complete configuration
  3. Include all defaults
  4. Show overrides
  5. Input: None
  6. Safety: 🟢 Safe

  7. mcp_config_validate_changes

  8. Validate configuration changes
  9. Check dependencies
  10. Warn about issues
  11. Input: { changes: object }
  12. Safety: 🟢 Safe (validation only)

  13. mcp_config_recommend

  14. Recommend configuration changes
  15. Based on usage patterns
  16. Hardware capabilities
  17. Network conditions
  18. Input: { goal?: string }
  19. Safety: 🟢 Safe

  20. mcp_optimization_suggest

  21. Suggest optimizations
  22. Performance improvements
  23. Resource efficiency
  24. Cost reduction
  25. Input: { focus?: string }
  26. Safety: 🟢 Safe

  27. mcp_capacity_planning

  28. Analyze capacity requirements
  29. Storage growth projections
  30. Resource scaling needs
  31. Input: { horizon?: string }
  32. Safety: 🟢 Safe

Enhanced Resources (3)

  1. fukuii://config/full
  2. Complete configuration
  3. All parameters
  4. Documentation

  5. fukuii://optimization/recommendations

  6. Optimization suggestions
  7. Expected improvements
  8. Implementation steps

  9. fukuii://capacity/projections

  10. Capacity forecasts
  11. Resource trends
  12. Scaling recommendations

New Prompts (2)

  1. mcp_configuration_optimization
  2. Optimize node configuration
  3. Balance tradeoffs
  4. Best practices
  5. Environment-specific tuning

  6. mcp_upgrade_planning

  7. Plan node upgrades
  8. Compatibility checks
  9. Migration strategy
  10. Rollback plans

Security Considerations

Authentication & Authorization

Multi-Level Access Control

Level 1: Read-Only (Monitoring) - Query node status - View blockchain data - Access logs and metrics - No state modifications

Level 2: Operational (Management) - Level 1 permissions - Start/stop mining - Manage peer connections - Modify blacklist - No sensitive data access

Level 3: Administrative (Full Control) - Level 1 & 2 permissions - Configuration changes - Account management - Full node control

Implementation Approach

// Permission-based access control
sealed trait McpPermission
object McpPermission {
  case object ReadOnly extends McpPermission
  case object Operational extends McpPermission
  case object Administrative extends McpPermission
}

// Tool permission requirements
case class McpToolDefinition(
  name: String,
  description: Option[String],
  requiredPermission: McpPermission,
  category: String
)

// Authorization check
def checkPermission(
  userPermission: McpPermission,
  requiredPermission: McpPermission
): Boolean = {
  (userPermission, requiredPermission) match {
    case (McpPermission.Administrative, _) => true
    case (McpPermission.Operational, McpPermission.ReadOnly) => true
    case (McpPermission.Operational, McpPermission.Operational) => true
    case (McpPermission.ReadOnly, McpPermission.ReadOnly) => true
    case _ => false
  }
}

API Key Management

# fukuii.conf
fukuii.network.rpc.mcp {
  enabled = true

  # Authentication
  authentication {
    required = true
    method = "api-key"  # or "jwt", "oauth"

    keys = [
      {
        name = "monitoring-agent"
        key = "${MCP_MONITORING_KEY}"
        permission = "read-only"
        rate-limit = 60  # requests per minute
      },
      {
        name = "ops-agent"
        key = "${MCP_OPS_KEY}"
        permission = "operational"
        rate-limit = 30
      },
      {
        name = "admin-agent"
        key = "${MCP_ADMIN_KEY}"
        permission = "administrative"
        rate-limit = 20
      }
    ]
  }

  # Authorization
  authorization {
    enabled = true

    # Tool-specific overrides
    tool-permissions = {
      "mcp_mining_start" = ["operational", "administrative"]
      "mcp_mining_stop" = ["operational", "administrative"]
      "mcp_config_validate_changes" = ["administrative"]
      "mcp_peer_connect" = ["operational", "administrative"]
    }
  }
}

Audit Logging

case class McpAuditLog(
  timestamp: Long,
  apiKey: String,
  toolName: String,
  parameters: JValue,
  result: Either[String, String],
  duration: Long,
  permission: McpPermission
)

trait McpAuditLogger {
  def logToolExecution(log: McpAuditLog): Unit
}

Rate Limiting

case class RateLimitConfig(
  requestsPerMinute: Int,
  burstSize: Int,
  penaltyDuration: FiniteDuration
)

trait RateLimiter {
  def checkLimit(apiKey: String): Future[Boolean]
  def recordRequest(apiKey: String): Unit
}

Input Validation

trait InputValidator {
  def validateToolInput(
    toolName: String,
    input: JValue
  ): Either[ValidationError, ValidatedInput]
}

// Example: Validate enode URL for peer connection
def validateEnodeUrl(enode: String): Either[String, EnodeUrl] = {
  val pattern = "^enode://[a-f0-9]{128}@[0-9.]+:[0-9]+$"
  if (enode.matches(pattern)) {
    Right(EnodeUrl(enode))
  } else {
    Left(s"Invalid enode URL format: $enode")
  }
}

Security Best Practices

  1. Principle of Least Privilege
  2. Grant minimum necessary permissions
  3. Use read-only access when possible
  4. Escalate only when required

  5. Defense in Depth

  6. Multiple layers of security
  7. Authentication + Authorization + Rate Limiting
  8. Input validation on all parameters

  9. Audit Everything

  10. Log all MCP operations
  11. Track permission escalations
  12. Monitor for suspicious patterns

  13. Secure by Default

  14. MCP disabled by default
  15. Require explicit configuration
  16. Enforce authentication

  17. Fail Closed

  18. Deny access on auth failures
  19. Reject invalid inputs
  20. Default to most restrictive

Implementation Roadmap

Overall Timeline: 12-16 weeks

Week 1-3   : Phase 1 - Core Node Control
Week 4-5   : Phase 2 - Mining & Block Production
Week 6-7   : Phase 3 - Transaction & Account Management
Week 8-9   : Phase 4 - Network & Peer Management
Week 10-11 : Phase 5 - Advanced Monitoring & Diagnostics
Week 12-13 : Phase 6 - Configuration & Optimization
Week 14-16 : Integration Testing, Documentation, Release

Phase-by-Phase Breakdown

Phase 1: Core Node Control (Weeks 1-3)

Deliverables: - ✅ Complete actor integration for existing tools - ✅ 8 new tools implemented - ✅ 7 enhanced resources with real data - ✅ Update existing 5 tools with actual queries - ✅ Unit tests for all tools - ✅ Integration tests with actors - ✅ Documentation updates

Key Tasks: 1. Implement actor query patterns 2. Add caching layer for expensive queries 3. Create error handling framework 4. Implement timeout management 5. Add metrics collection 6. Update documentation

Dependencies: None

Phase 2: Mining & Block Production (Weeks 4-5)

Deliverables: - ✅ 7 new mining tools - ✅ 4 mining resources - ✅ 2 mining prompts - ✅ Integration with MiningCoordinator - ✅ Mining statistics collection - ✅ Tests and documentation

Key Tasks: 1. Query MiningCoordinator for status 2. Implement mining control operations 3. Add mining statistics tracking 4. Create profitability calculator 5. Add safety checks for mining operations

Dependencies: Phase 1 complete

Phase 3: Transaction & Account Management (Weeks 6-7)

Deliverables: - ✅ 8 transaction tools - ✅ 5 transaction resources - ✅ 2 transaction prompts - ✅ Integration with TxPool and Blockchain - ✅ Gas price oracle - ✅ Tests and documentation

Key Tasks: 1. Query TxPool for pending transactions 2. Implement transaction tracing 3. Create gas price estimator 4. Add account history queries 5. Implement contract analysis

Dependencies: Phase 1 complete

Phase 4: Network & Peer Management (Weeks 8-9)

Deliverables: - ✅ 10 peer management tools - ✅ 6 network resources - ✅ 3 network prompts - ✅ Integration with PeerManagerActor - ✅ Peer quality scoring - ✅ Tests and documentation

Key Tasks: 1. Query PeerManagerActor for peer data 2. Implement peer connection control 3. Add blacklist management 4. Create peer quality analyzer 5. Implement network topology visualization

Dependencies: Phase 1 complete

Phase 5: Advanced Monitoring & Diagnostics (Weeks 10-11)

Deliverables: - ✅ 7 diagnostic tools - ✅ 5 diagnostic resources - ✅ 3 diagnostic prompts - ✅ Automated health checks - ✅ Performance profiling - ✅ Tests and documentation

Key Tasks: 1. Implement comprehensive health checks 2. Add performance profiling 3. Create log analysis tools 4. Implement anomaly detection 5. Add trend analysis

Dependencies: Phases 1-4 complete

Phase 6: Configuration & Optimization (Weeks 12-13)

Deliverables: - ✅ 5 configuration tools - ✅ 3 configuration resources - ✅ 2 configuration prompts - ✅ Configuration validation - ✅ Optimization engine - ✅ Tests and documentation

Key Tasks: 1. Implement configuration reader 2. Add validation framework 3. Create optimization recommender 4. Implement capacity planner 5. Add configuration documentation

Dependencies: Phases 1-5 complete

Integration & Release (Weeks 14-16)

Deliverables: - ✅ End-to-end testing - ✅ Performance benchmarking - ✅ Security audit - ✅ Complete documentation - ✅ Example agents - ✅ Release notes

Key Tasks: 1. Run comprehensive integration tests 2. Perform security audit 3. Benchmark performance 4. Write user documentation 5. Create example agents 6. Prepare release

Dependencies: All phases complete


Acceptance Criteria

Functional Requirements

1. Node State Monitoring

  • ✅ Agent can query real-time node status
  • ✅ Agent can access blockchain data
  • ✅ Agent can monitor sync progress
  • ✅ Agent can view peer connections
  • ✅ Agent can access performance metrics

2. Mining Control

  • ✅ Agent can start mining
  • ✅ Agent can stop mining
  • ✅ Agent can configure mining parameters
  • ✅ Agent can query mining statistics
  • ✅ Agent can assess mining profitability

3. Transaction Management

  • ✅ Agent can query transaction status
  • ✅ Agent can monitor pending transactions
  • ✅ Agent can estimate gas costs
  • ✅ Agent can query account balances
  • ✅ Agent can trace transaction execution

4. Peer Management

  • ✅ Agent can list peers
  • ✅ Agent can connect to peers
  • ✅ Agent can disconnect from peers
  • ✅ Agent can manage blacklist
  • ✅ Agent can assess peer quality

5. Diagnostics

  • ✅ Agent can run health checks
  • ✅ Agent can profile performance
  • ✅ Agent can detect issues automatically
  • ✅ Agent can analyze logs
  • ✅ Agent can generate diagnostic reports

6. Configuration

  • ✅ Agent can read configuration
  • ✅ Agent can validate changes
  • ✅ Agent can receive recommendations
  • ✅ Agent can plan capacity
  • ✅ Agent can optimize settings

Non-Functional Requirements

1. Performance

  • ✅ Tool execution time < 5 seconds (95th percentile)
  • ✅ Resource read time < 1 second (95th percentile)
  • ✅ No significant impact on node performance
  • ✅ Efficient caching reduces redundant queries

2. Security

  • ✅ All operations require authentication
  • ✅ Authorization enforced based on permissions
  • ✅ All operations are audited
  • ✅ Rate limiting prevents abuse
  • ✅ Input validation prevents injection attacks

3. Reliability

  • ✅ 99.9% uptime for MCP endpoints
  • ✅ Graceful degradation on component failures
  • ✅ Proper error handling and reporting
  • ✅ Automatic retry on transient failures

4. Usability

  • ✅ Clear, comprehensive documentation
  • ✅ Self-describing APIs (OpenAPI/JSON Schema)
  • ✅ Helpful error messages
  • ✅ Example agents provided
  • ✅ Integration guides available

5. Maintainability

  • ✅ Modular architecture
  • ✅ Comprehensive test coverage (>80%)
  • ✅ Clear code organization
  • ✅ Well-documented patterns
  • ✅ Easy to add new tools/resources

Integration Requirements

1. Backward Compatibility

  • ✅ Existing RPC endpoints unchanged
  • ✅ MCP is opt-in, not required
  • ✅ No breaking changes to APIs
  • ✅ Smooth upgrade path

2. Infrastructure

  • ✅ Works with existing HTTP/WebSocket servers
  • ✅ Integrates with existing authentication
  • ✅ Uses existing logging system
  • ✅ Compatible with monitoring systems

3. Documentation

  • ✅ API reference complete
  • ✅ Integration guides written
  • ✅ Example code provided
  • ✅ Troubleshooting guide available
  • ✅ Security best practices documented

Testing Strategy

Unit Testing

Coverage Target: 85%

Focus Areas: - Tool execution logic - Resource data fetching - Input validation - Error handling - Permission checks

Example:

class NodeStatusToolSpec extends AnyFlatSpec with Matchers {
  "NodeStatusTool" should "query actual node state" in {
    val peerManager = mock[ActorRef]
    val syncController = mock[ActorRef]

    when(peerManager ? GetPeerCount).thenReturn(Future.successful(25))
    when(syncController ? GetSyncStatus).thenReturn(
      Future.successful(SyncStatus(syncing = true, currentBlock = 100, targetBlock = 200))
    )

    val result = NodeStatusTool.execute(peerManager, syncController).unsafeRunSync()

    result should include("peerCount: 25")
    result should include("currentBlock: 100")
  }
}

Integration Testing

Test Scenarios: 1. Tool execution with real actor integration 2. Resource reading with actual blockchain queries 3. End-to-end MCP protocol flows 4. Error propagation and handling 5. Timeout and retry behavior

Example:

class McpIntegrationSpec extends AnyFlatSpec with Matchers {
  "MCP Tools" should "integrate with actual node components" in {
    val node = TestNode.start()
    val mcpService = node.mcpService

    // Test node status query
    val statusReq = McpToolsCallRequest("mcp_node_status", None)
    val statusResult = mcpService.toolsCall(statusReq).unsafeRunSync()

    statusResult.isRight shouldBe true
    val content = statusResult.right.get.content.head.text
    content should include("\"syncing\":")
    content should include("\"peerCount\":")

    node.stop()
  }
}

Performance Testing

Benchmarks: - Tool execution latency - Resource read latency - Concurrent request handling - Memory usage under load - Cache effectiveness

Tools: JMH for microbenchmarks, Gatling for load testing

Targets: - p50 latency < 100ms - p95 latency < 1s - p99 latency < 5s - Throughput > 100 req/s per endpoint - Memory overhead < 50MB

Security Testing

Test Cases: 1. Authentication bypass attempts 2. Authorization escalation attempts 3. Rate limit enforcement 4. Input injection attempts 5. Parameter tampering 6. Session hijacking 7. Replay attacks

Tools: OWASP ZAP, custom security scanners

End-to-End Testing

Test Scenarios: 1. Agent performs health check 2. Agent starts mining 3. Agent manages peers 4. Agent troubleshoots sync issue 5. Agent optimizes configuration

Approach: Scripted agent interactions using MCP SDK

Example:

# E2E test with Python MCP client
from mcp import Client

async def test_health_check_workflow():
    client = Client("http://localhost:8545")

    # Initialize MCP session
    init = await client.initialize()
    assert init["protocolVersion"] == "2024-11-05"

    # List available tools
    tools = await client.list_tools()
    assert "mcp_health_check" in [t["name"] for t in tools]

    # Run health check
    result = await client.call_tool("mcp_health_check", {})
    assert result["isError"] is None
    health_report = result["content"][0]["text"]

    # Parse and validate health report
    report = json.loads(health_report)
    assert "overall_health" in report
    assert "issues" in report


Documentation Requirements

1. API Reference Documentation

Location: docs/api/MCP_API_REFERENCE.md

Contents: - Complete tool catalog with descriptions - Input/output schemas for each tool - Example requests and responses - Error codes and handling - Resource URI patterns - Prompt templates

Format: Markdown with OpenAPI/JSON Schema snippets

2. Integration Guide

Location: docs/api/MCP_INTEGRATION_GUIDE.md

Contents: - Getting started with MCP - Authentication setup - Client SDK examples (Python, TypeScript, Go) - Common use cases - Best practices - Troubleshooting

3. Security Guide

Location: docs/api/MCP_SECURITY_GUIDE.md

Contents: - Authentication mechanisms - Authorization model - API key management - Rate limiting configuration - Audit logging setup - Security best practices - Threat model

4. Operational Guide

Location: docs/runbooks/MCP_OPERATIONS.md

Contents: - Enabling MCP on node - Configuring permissions - Monitoring MCP usage - Performance tuning - Common issues and solutions - Upgrade procedures

5. Agent Development Guide

Location: docs/for-developers/MCP_AGENT_DEVELOPMENT.md

Contents: - Building custom agents - MCP client libraries - Agent design patterns - Example agents (monitoring, auto-miner, health-checker) - Testing agents - Deployment strategies

6. Changelog & Migration Guides

Location: CHANGELOG.md and docs/api/MCP_MIGRATION_*.md

Contents: - Version history - Breaking changes - New features - Deprecation notices - Migration guides for major versions


Summary

This plan provides a comprehensive roadmap to transform Fukuii's MCP implementation from basic read-only capabilities to full agent-controlled node management. The phased approach ensures:

  1. Incremental Value Delivery: Each phase delivers usable functionality
  2. Risk Management: Early phases establish patterns for later phases
  3. Security First: Authentication and authorization from the start
  4. Quality Assurance: Comprehensive testing at every phase
  5. Documentation: Detailed docs enable agent developers

Expected Outcomes: - 45+ new MCP tools covering all critical node operations - 20+ enhanced resources providing real-time data - 15+ prompts guiding agents through complex workflows - Complete agent control over node lifecycle - Secure, auditable, production-ready implementation

Success Metrics: - 85% coverage of production RPC endpoints via MCP - <5s tool execution time (p95) - 100% authentication/authorization enforcement - >80% test coverage - Zero security vulnerabilities - Comprehensive documentation


Document Maintainer: Chippr Robotics LLC
Last Updated: 2025-12-12
Status: Planning Phase - Awaiting Approval for Implementation