Skip to main content
Glama
StevenGeller

LDK MCP Server

by StevenGeller

ldk_backup_state

Backup or restore Lightning Development Kit channel states to manage iOS wallet data, enabling recovery and continuity for Lightning Network transactions.

Instructions

Test channel backup and restore flows

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesAction to perform
backupDataNoBase64 encoded backup data (required for restore)

Implementation Reference

  • The main tool handler function (execute) that processes input arguments for 'backup' and 'restore' actions. For backup, it calls lightningService.backupState() and returns base64 data with size, timestamp, and extensive Swift iOS backup implementation example. For restore, it calls lightningService.restoreState() with provided backup data.
      execute: async (args: any): Promise<ToolResult> => {
        try {
          if (args.action === 'backup') {
            const backup = await lightningService.backupState();
            
            return {
              content: [{
                type: 'text',
                text: JSON.stringify({
                  success: true,
                  action: 'backup',
                  backupData: backup,
                  backupSize: Buffer.from(backup, 'base64').length,
                  timestamp: new Date().toISOString(),
                  swiftExample: `
    // Swift code for channel backup in your iOS app
    import LightningDevKit
    import Foundation
    
    class LDKBackupManager {
        private let fileManager = FileManager.default
        private let backupDirectory: URL
        
        init() throws {
            // Create backup directory in app's documents
            let documentsPath = fileManager.urls(for: .documentDirectory, 
                                               in: .userDomainMask).first!
            backupDirectory = documentsPath.appendingPathComponent("ldk_backups")
            
            try fileManager.createDirectory(at: backupDirectory, 
                                          withIntermediateDirectories: true)
        }
        
        // Backup channel state
        func backupChannels() throws {
            let channelManager = LDKManager.shared.channelManager
            let channels = channelManager.listChannels()
            
            // Serialize channel monitors
            var backupData: [String: Data] = [:]
            
            for channel in channels {
                let channelId = channel.getChannelId()
                let monitor = LDKManager.shared.getChannelMonitor(channelId: channelId)
                
                if let serialized = monitor?.write() {
                    backupData[channelId.toHex()] = Data(serialized)
                }
            }
            
            // Add channel manager state
            if let managerBytes = channelManager.write() {
                backupData["channel_manager"] = Data(managerBytes)
            }
            
            // Add network graph
            if let graphBytes = LDKManager.shared.networkGraph.write() {
                backupData["network_graph"] = Data(graphBytes)
            }
            
            // Create timestamped backup
            let timestamp = ISO8601DateFormatter().string(from: Date())
            let backupFile = backupDirectory
                .appendingPathComponent("backup_\\(timestamp).json")
            
            let jsonData = try JSONEncoder().encode(backupData)
            try jsonData.write(to: backupFile)
            
            // Also save to iCloud if available
            saveToICloud(data: jsonData, timestamp: timestamp)
            
            print("Backup saved: \\(backupFile.lastPathComponent)")
        }
        
        // Restore from backup
        func restoreFromBackup(backupFile: URL) throws {
            let jsonData = try Data(contentsOf: backupFile)
            let backupData = try JSONDecoder().decode([String: Data].self, from: jsonData)
            
            // Restore channel monitors first
            for (channelIdHex, monitorData) in backupData {
                if channelIdHex == "channel_manager" || channelIdHex == "network_graph" {
                    continue
                }
                
                let monitor = try ChannelMonitor.read(
                    ser: [UInt8](monitorData),
                    arg: LDKManager.shared.keysManager
                )
                
                // Persist restored monitor
                LDKManager.shared.persistChannelMonitor(monitor: monitor)
            }
            
            // Then restore channel manager
            if let managerData = backupData["channel_manager"] {
                // This requires rebuilding the channel manager with monitors
                try LDKManager.shared.restoreChannelManager(
                    serialized: [UInt8](managerData),
                    monitors: getRestoredMonitors()
                )
            }
            
            print("Restore completed successfully")
        }
        
        // Automatic backup on important events
        func setupAutomaticBackup() {
            // Backup after channel updates
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(handleChannelUpdate),
                name: .ldkChannelUpdated,
                object: nil
            )
            
            // Backup periodically
            Timer.scheduledTimer(withTimeInterval: 3600, repeats: true) { _ in
                try? self.backupChannels()
            }
        }
        
        @objc private func handleChannelUpdate() {
            // Debounce backups to avoid too frequent saves
            NSObject.cancelPreviousPerformRequests(
                withTarget: self,
                selector: #selector(performBackup),
                object: nil
            )
            
            perform(#selector(performBackup), with: nil, afterDelay: 5.0)
        }
        
        @objc private func performBackup() {
            try? backupChannels()
        }
        
        // iCloud backup
        private func saveToICloud(data: Data, timestamp: String) {
            guard let containerURL = FileManager.default.url(
                forUbiquityContainerIdentifier: nil
            ) else { return }
            
            let iCloudBackup = containerURL
                .appendingPathComponent("Documents")
                .appendingPathComponent("ldk_backup_\\(timestamp).json")
            
            do {
                try data.write(to: iCloudBackup)
                print("Backup saved to iCloud")
            } catch {
                print("iCloud backup failed: \\(error)")
            }
        }
    }
    
    // Extension for Notification.Name
    extension Notification.Name {
        static let ldkChannelUpdated = Notification.Name("ldkChannelUpdated")
    }`.trim()
                }, null, 2)
              }]
            };
          } else if (args.action === 'restore') {
            if (!args.backupData) {
              throw new Error('Backup data required for restore');
            }
            
            const success = await lightningService.restoreState(args.backupData);
            
            return {
              content: [{
                type: 'text',
                text: JSON.stringify({
                  success,
                  action: 'restore',
                  message: success ? 'State restored successfully' : 'Restore failed'
                }, null, 2)
              }]
            };
          } else {
            throw new Error('Invalid action. Use "backup" or "restore"');
          }
        } catch (error) {
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error'
              }, null, 2)
            }],
            isError: true
          };
        }
      }
  • Tool input schema: object with 'action' (enum: 'backup', 'restore', required) and optional 'backupData' (string, base64 for restore).
    inputSchema: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: ['backup', 'restore'],
          description: 'Action to perform'
        },
        backupData: {
          type: 'string',
          description: 'Base64 encoded backup data (required for restore)'
        }
      },
      required: ['action']
    },
  • src/index.ts:38-62 (registration)
    Registration in the central tools array used by MCP server for listing and executing tools. backupStateTool is included at line 43. The array is used in setRequestHandler for ListToolsRequestSchema and CallToolRequestSchema.
    const tools = [
      generateInvoiceTool,
      payInvoiceTool,
      getChannelStatusTool,
      getNodeInfoTool,
      backupStateTool,
      keychainTestTool,
      backgroundTestTool,
      pushNotificationTool,
      biometricAuthTool,
      createChannelTool,
      closeChannelTool,
      getBalanceTool,
      decodeInvoiceTool,
      listPaymentsTool,
      estimateFeeTool,
      generateMnemonicTool,
      deriveAddressTool,
      getSwiftCodeTool,
      getArchitectureTool,
      testScenarioTool,
      networkGraphTool,
      eventHandlingTool,
      chainSyncTool,
    ];
  • Supporting methods in LightningService: backupState() serializes nodeInfo, channels, payments to JSON base64; restoreState() deserializes and restores the mock LDK state.
    async backupState(): Promise<string> {
      const state = {
        nodeInfo: this.nodeInfo,
        channels: Array.from(this.channels.entries()),
        payments: Array.from(this.payments.entries()),
        timestamp: Date.now()
      };
      
      return Buffer.from(JSON.stringify(state)).toString('base64');
    }
    
    async restoreState(backup: string): Promise<boolean> {
      try {
        const state = JSON.parse(Buffer.from(backup, 'base64').toString());
        this.nodeInfo = state.nodeInfo;
        this.channels = new Map(state.channels);
        this.payments = new Map(state.payments);
        return true;
      } catch (error) {
        throw new Error(`Failed to restore state: ${error}`);
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden but provides minimal behavioral insight. It mentions 'test' and 'flows', hinting at non-production or diagnostic use, but doesn't disclose critical traits like whether it's read-only, destructive, requires specific permissions, or has side effects (e.g., affecting channel state). This is inadequate for a tool with potential mutation implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with no wasted words. It's front-loaded with the core purpose, though it could be more structured (e.g., specifying it's for testing Lightning channels). It earns a 4 for being concise but loses a point for lacking clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (testing backup/restore flows for channels), no annotations, and no output schema, the description is incomplete. It doesn't explain what 'backup data' entails, the format of results, or error conditions. For a tool with potential state changes, this leaves significant gaps for an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so parameters are fully documented in the schema. The description adds no additional meaning beyond implying 'backup' and 'restore' actions, which are already clear from the enum. Baseline score of 3 is appropriate as the schema handles parameter semantics adequately.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Test channel backup and restore flows' states a general purpose (testing backup/restore) but lacks specificity about what 'channel' refers to (e.g., Lightning Network channels) and doesn't distinguish it from siblings like 'ldk_channel_status' or 'ldk_close_channel'. It's vague about the exact resource being tested.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives. It doesn't mention prerequisites, context (e.g., during development or debugging), or when to choose it over other LDK tools like 'ldk_channel_status' for monitoring. Usage is implied only by the name and description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/StevenGeller/ldk-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server