Skip to main content
Glama
StevenGeller

LDK MCP Server

by StevenGeller

ldk_get_balance

Retrieve Lightning wallet balance and channel liquidity data to monitor funds and manage payment capacity.

Instructions

Get Lightning wallet balance and channel liquidity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The complete tool handler implementation for 'ldk_get_balance'. Defines the tool object with schema, description, and execute function that fetches balance data from LightningService, calculates inbound liquidity from channels, formats the response as JSON including sats conversions and a comprehensive SwiftUI example for iOS balance display.
    export const getBalanceTool: Tool = {
      name: 'ldk_get_balance',
      description: 'Get Lightning wallet balance and channel liquidity',
      inputSchema: {
        type: 'object',
        properties: {}
      },
      execute: async (args: any): Promise<ToolResult> => {
        try {
          const balance = await lightningService.getBalance();
          const channels = await lightningService.getChannelStatus();
          
          // Calculate inbound liquidity
          let inboundMsat = 0;
          for (const channel of channels) {
            if (channel.isUsable) {
              inboundMsat += channel.remoteBalanceMsat;
            }
          }
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                success: true,
                balance: {
                  totalSats: Math.floor(balance.totalMsat / 1000),
                  spendableSats: Math.floor(balance.spendableMsat / 1000),
                  inboundSats: Math.floor(inboundMsat / 1000)
                },
                liquidity: {
                  canSendMaxSats: Math.floor(balance.spendableMsat / 1000),
                  canReceiveMaxSats: Math.floor(inboundMsat / 1000)
                },
                swiftExample: `
    // Swift code to display balance in your iOS app
    import SwiftUI
    import LightningDevKit
    
    struct BalanceView: View {
        @State private var balance: WalletBalance?
        @State private var isLoading = true
        
        var body: some View {
            VStack(spacing: 24) {
                // Total balance card
                VStack(spacing: 16) {
                    HStack {
                        Image(systemName: "bitcoinsign.circle.fill")
                            .font(.largeTitle)
                            .foregroundColor(.orange)
                        
                        Spacer()
                        
                        VStack(alignment: .trailing) {
                            Text(formatSats(balance?.totalSats ?? 0))
                                .font(.system(size: 32, weight: .bold, design: .rounded))
                            Text("sats")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    // Balance breakdown
                    VStack(spacing: 8) {
                        BalanceDetailRow(
                            label: "Spendable",
                            amount: balance?.spendableSats ?? 0,
                            icon: "paperplane.fill",
                            color: .green
                        )
                        
                        BalanceDetailRow(
                            label: "Receivable",
                            amount: balance?.inboundSats ?? 0,
                            icon: "arrow.down.circle.fill",
                            color: .blue
                        )
                    }
                }
                .padding()
                .background(
                    LinearGradient(
                        colors: [Color.orange.opacity(0.1), Color.orange.opacity(0.05)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .cornerRadius(16)
                
                // Quick actions
                HStack(spacing: 16) {
                    QuickActionButton(
                        title: "Send",
                        icon: "paperplane.fill",
                        color: .green,
                        isEnabled: (balance?.spendableSats ?? 0) > 0
                    ) {
                        // Navigate to send view
                    }
                    
                    QuickActionButton(
                        title: "Receive",
                        icon: "qrcode",
                        color: .blue,
                        isEnabled: (balance?.inboundSats ?? 0) > 0
                    ) {
                        // Navigate to receive view
                    }
                }
                
                Spacer()
            }
            .padding()
            .navigationTitle("Balance")
            .task {
                await loadBalance()
            }
            .refreshable {
                await loadBalance()
            }
            .overlay {
                if isLoading {
                    ProgressView()
                }
            }
        }
        
        func loadBalance() async {
            isLoading = true
            defer { isLoading = false }
            
            balance = await LDKManager.shared.getBalance()
        }
        
        func formatSats(_ sats: Int64) -> String {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.groupingSeparator = ","
            return formatter.string(from: NSNumber(value: sats)) ?? "0"
        }
    }
    
    struct BalanceDetailRow: View {
        let label: String
        let amount: Int64
        let icon: String
        let color: Color
        
        var body: some View {
            HStack {
                Label(label, systemImage: icon)
                    .foregroundColor(color)
                    .font(.callout)
                
                Spacer()
                
                Text(formatAmount(amount))
                    .font(.callout)
                    .fontWeight(.medium)
                    .foregroundColor(.secondary)
            }
        }
        
        func formatAmount(_ sats: Int64) -> String {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.groupingSeparator = ","
            return (formatter.string(from: NSNumber(value: sats)) ?? "0") + " sats"
        }
    }
    
    struct QuickActionButton: View {
        let title: String
        let icon: String
        let color: Color
        let isEnabled: Bool
        let action: () -> Void
        
        var body: some View {
            Button(action: action) {
                VStack(spacing: 8) {
                    Image(systemName: icon)
                        .font(.title2)
                    Text(title)
                        .font(.caption)
                }
                .frame(maxWidth: .infinity)
                .padding()
                .background(color.opacity(isEnabled ? 0.15 : 0.05))
                .foregroundColor(isEnabled ? color : .gray)
                .cornerRadius(12)
            }
            .disabled(!isEnabled)
        }
    }
    
    // Extension for LDK balance fetching
    extension LDKManager {
        func getBalance() async -> WalletBalance {
            let channels = channelManager.listChannels()
            
            var totalMsat: UInt64 = 0
            var spendableMsat: UInt64 = 0
            var inboundMsat: UInt64 = 0
            
            for channel in channels {
                if channel.isUsable {
                    let localBalance = channel.balanceMsat
                    let remoteBalance = (channel.channelValueSatoshis * 1000) - localBalance
                    
                    totalMsat += localBalance
                    spendableMsat += max(0, localBalance - (channel.channelValueSatoshis * 10)) // Reserve 1%
                    inboundMsat += remoteBalance
                }
            }
            
            return WalletBalance(
                totalSats: Int64(totalMsat / 1000),
                spendableSats: Int64(spendableMsat / 1000),
                inboundSats: Int64(inboundMsat / 1000)
            )
        }
    }
    
    struct WalletBalance {
        let totalSats: Int64
        let spendableSats: Int64
        let inboundSats: Int64
    }`.trim()
              }, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error'
              }, null, 2)
            }],
            isError: true
          };
        }
      }
    };
  • src/index.ts:24-62 (registration)
    Tool registration in the main MCP server index file. Imports getBalanceTool and includes it in the tools array used for listing and executing tools via MCP handlers.
    import { getBalanceTool } from './tools/getBalance.js';
    import { decodeInvoiceTool } from './tools/decodeInvoice.js';
    import { listPaymentsTool } from './tools/listPayments.js';
    import { estimateFeeTool } from './tools/estimateFee.js';
    import { generateMnemonicTool } from './tools/generateMnemonic.js';
    import { deriveAddressTool } from './tools/deriveAddress.js';
    import { getSwiftCodeTool } from './tools/getSwiftCode.js';
    import { getArchitectureTool } from './tools/getArchitecture.js';
    import { testScenarioTool } from './tools/testScenario.js';
    import { networkGraphTool } from './tools/networkGraph.js';
    import { eventHandlingTool } from './tools/eventHandling.js';
    import { chainSyncTool } from './tools/chainSync.js';
    
    // Aggregate all tools
    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,
    ];
  • Input schema definition for the ldk_get_balance tool, specifying an empty object (no required parameters).
    inputSchema: {
      type: 'object',
      properties: {}
    },
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but lacks critical details: whether it's a read-only operation, if it requires authentication, potential rate limits, or what the return format looks like (e.g., structured data vs raw numbers). For a financial tool with zero annotation coverage, this is a significant gap.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose ('Get Lightning wallet balance and channel liquidity'). There is zero waste—every word contributes directly to understanding the tool's function without redundancy or fluff.

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 (financial/blockchain tool), lack of annotations, and no output schema, the description is incomplete. It doesn't explain what 'balance' includes (e.g., on-chain vs off-chain), how liquidity is reported, or error conditions. For a tool in this domain with rich sibling tools, more context is needed to ensure safe and correct usage.

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

Parameters4/5

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

The tool has 0 parameters, and schema description coverage is 100% (empty schema is fully described). The description doesn't need to add parameter semantics, so it meets the baseline of 4 for zero-parameter tools. No additional value is required or provided beyond the schema.

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

Purpose4/5

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

The description clearly states the tool's purpose with specific verbs ('Get') and resources ('Lightning wallet balance and channel liquidity'). It distinguishes itself from siblings like ldk_list_payments (which lists payments) or ldk_channel_status (which focuses on channel status), but doesn't explicitly differentiate beyond the natural scope of 'balance' vs other operations.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing an initialized wallet), exclusions (e.g., not for historical balances), or comparisons to siblings like ldk_node_info (which might include balance info). Usage is implied by the name but not explicitly stated.

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