Skip to main content
Glama
StevenGeller

LDK MCP Server

by StevenGeller

ldk_estimate_fee

Calculate Lightning Network routing fees for payments by specifying the amount in satoshis and optionally the target node to estimate transaction costs.

Instructions

Estimate Lightning routing fees for a payment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountSatsYesPayment amount in satoshis
targetNodeNoTarget node public key (optional)

Implementation Reference

  • Primary handler for ldk_estimate_fee tool: converts input to msat, delegates to LightningService for estimation, formats comprehensive response including Swift iOS example code.
      execute: async (args: any): Promise<ToolResult> => {
        try {
          const amountMsat = args.amountSats * 1000;
          const estimate = await lightningService.estimateFee(amountMsat);
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                success: true,
                amountSats: args.amountSats,
                feeEstimate: {
                  baseFee: estimate.baseFee,
                  proportionalMillionths: estimate.proportionalMillionths,
                  estimatedFeeSats: Math.ceil(estimate.estimatedFeeMsat / 1000),
                  estimatedDurationSeconds: estimate.estimatedDurationSeconds,
                  feePercentage: (estimate.estimatedFeeMsat / amountMsat * 100).toFixed(2)
                },
                swiftExample: `
    // Swift code for fee estimation in your iOS app
    import SwiftUI
    import LightningDevKit
    
    struct FeeEstimator {
        static func estimateRoutingFee(
            amountMsat: UInt64,
            targetNode: [UInt8]? = nil
        ) -> FeeEstimate {
            let router = LDKManager.shared.router
            let networkGraph = LDKManager.shared.networkGraph
            
            // Get route parameters
            let paymentParams = PaymentParameters.initForKeysend(
                payeePublicKey: targetNode ?? generateRandomPubkey()
            )
            
            let routeParams = RouteParameters(
                paymentParamsArg: paymentParams,
                finalValueMsatArg: amountMsat
            )
            
            // Find route
            let routeResult = router.findRoute(
                payer: LDKManager.shared.channelManager.getOurNodeId(),
                routeParams: routeParams,
                channelDetails: LDKManager.shared.channelManager.listUsableChannels(),
                scorerParams: InFlightHtlcs()
            )
            
            if let route = routeResult.getValue() {
                let totalFees = route.getTotalFees()
                let hops = route.getHops().count
                
                return FeeEstimate(
                    totalFeeMsat: totalFees,
                    numberOfHops: hops,
                    estimatedDuration: hops * 30 // ~30 seconds per hop
                )
            } else {
                // Fallback estimate
                return FeeEstimate(
                    totalFeeMsat: UInt64(Double(amountMsat) * 0.001), // 0.1%
                    numberOfHops: 3,
                    estimatedDuration: 90
                )
            }
        }
    }
    
    struct FeeEstimate {
        let totalFeeMsat: UInt64
        let numberOfHops: Int
        let estimatedDuration: Int
        
        var totalFeeSats: Int {
            Int(totalFeeMsat / 1000)
        }
    }
    
    // SwiftUI Fee Display Component
    struct FeeEstimateView: View {
        let amountSats: Int
        @State private var feeEstimate: FeeEstimate?
        @State private var isCalculating = false
        
        var body: some View {
            VStack(alignment: .leading, spacing: 12) {
                HStack {
                    Label("Network Fee", systemImage: "network")
                        .font(.headline)
                    
                    Spacer()
                    
                    if isCalculating {
                        ProgressView()
                            .scaleEffect(0.8)
                    }
                }
                
                if let estimate = feeEstimate {
                    VStack(alignment: .leading, spacing: 8) {
                        // Fee amount
                        HStack {
                            Text("Estimated Fee")
                                .foregroundColor(.secondary)
                            Spacer()
                            Text("~\\(estimate.totalFeeSats) sats")
                                .fontWeight(.medium)
                        }
                        
                        // Fee percentage
                        HStack {
                            Text("Fee Rate")
                                .foregroundColor(.secondary)
                            Spacer()
                            Text(String(format: "%.2f%%", feePercentage))
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        // Route info
                        HStack {
                            Text("Route Hops")
                                .foregroundColor(.secondary)
                            Spacer()
                            Text("\\(estimate.numberOfHops)")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        // Duration
                        HStack {
                            Text("Est. Duration")
                                .foregroundColor(.secondary)
                            Spacer()
                            Text("~\\(estimate.estimatedDuration)s")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    // Visual fee indicator
                    FeeIndicator(feePercentage: feePercentage)
                        .padding(.top, 8)
                    
                } else {
                    Text("Calculating route fees...")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            .padding()
            .background(Color(UIColor.secondarySystemBackground))
            .cornerRadius(12)
            .task {
                await calculateFee()
            }
        }
        
        var feePercentage: Double {
            guard let estimate = feeEstimate, amountSats > 0 else { return 0 }
            return Double(estimate.totalFeeSats) / Double(amountSats) * 100
        }
        
        func calculateFee() async {
            isCalculating = true
            defer { isCalculating = false }
            
            feeEstimate = FeeEstimator.estimateRoutingFee(
                amountMsat: UInt64(amountSats * 1000)
            )
        }
    }
    
    struct FeeIndicator: View {
        let feePercentage: Double
        
        var feeLevel: FeeLevel {
            if feePercentage < 0.1 {
                return .low
            } else if feePercentage < 0.5 {
                return .medium
            } else {
                return .high
            }
        }
        
        enum FeeLevel {
            case low, medium, high
            
            var color: Color {
                switch self {
                case .low: return .green
                case .medium: return .orange
                case .high: return .red
                }
            }
            
            var text: String {
                switch self {
                case .low: return "Low fees"
                case .medium: return "Normal fees"
                case .high: return "High fees"
                }
            }
        }
        
        var body: some View {
            HStack(spacing: 8) {
                Circle()
                    .fill(feeLevel.color)
                    .frame(width: 8, height: 8)
                
                Text(feeLevel.text)
                    .font(.caption)
                    .foregroundColor(feeLevel.color)
                
                Spacer()
            }
        }
    }`.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
          };
        }
      }
  • Input schema validation for the tool parameters.
    inputSchema: {
      type: 'object',
      properties: {
        amountSats: {
          type: 'number',
          description: 'Payment amount in satoshis',
          minimum: 1
        },
        targetNode: {
          type: 'string',
          description: 'Target node public key (optional)'
        }
      },
      required: ['amountSats']
    },
  • src/index.ts:38-62 (registration)
    Registration of estimateFeeTool (imported at line 27) in the central tools array used by MCP server for tool listing and execution.
    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,
    ];
  • Core fee estimation helper in LightningService implementing base + proportional fee calculation.
    async estimateFee(amountMsat: number): Promise<FeeEstimate> {
      // Simple fee estimation
      const baseFee = 1000; // 1 sat base fee
      const proportionalMillionths = 1000; // 0.1%
      const estimatedFeeMsat = baseFee + Math.floor(amountMsat * proportionalMillionths / 1000000);
      
      return {
        baseFee,
        proportionalMillionths,
        estimatedFeeMsat,
        estimatedDurationSeconds: 60 // 1 minute estimate
      };
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool estimates fees but does not reveal critical traits such as whether it requires network connectivity, how it calculates fees (e.g., based on current network conditions), or if it has rate limits. This leaves significant gaps in understanding its operation.

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, direct sentence that efficiently conveys the core function without unnecessary words. It is front-loaded with the essential action and resource, making it easy to parse and understand quickly.

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 of Lightning network fee estimation and the lack of annotations and output schema, the description is insufficient. It does not cover behavioral aspects like error handling, return format, or dependencies on network state, leaving the agent with incomplete information for reliable tool invocation.

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?

The input schema has 100% description coverage, with clear documentation for both parameters ('amountSats' and 'targetNode'). The description adds no additional semantic context beyond what the schema provides, such as explaining fee estimation algorithms or default behaviors when 'targetNode' is omitted. Baseline 3 is appropriate as the schema handles parameter documentation adequately.

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 action ('Estimate') and the resource ('Lightning routing fees for a payment'), making the purpose immediately understandable. However, it does not differentiate from siblings like 'ldk_pay_invoice' or 'ldk_decode_invoice', which also involve payment-related operations, leaving room for potential confusion.

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. For example, it does not specify if this should be used before 'ldk_pay_invoice' to check costs or as a standalone fee estimator, nor does it mention prerequisites or exclusions, leaving usage context unclear.

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