Skip to main content
Glama
StevenGeller

LDK MCP Server

by StevenGeller

ldk_create_channel

Open a Lightning Network payment channel with a peer node to enable instant Bitcoin transactions. Specify the peer's public key, channel capacity, and optional settings for push amounts and public announcement.

Instructions

Open a Lightning channel with a peer node

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
remotePubkeyYesRemote node public key (hex encoded)
capacitySatsYesChannel capacity in satoshis
pushSatsNoAmount to push to remote side (optional)
isPublicNoWhether to announce channel publicly

Implementation Reference

  • The execute function implementing the ldk_create_channel tool logic. Converts satoshis to millisatoshis, calls LightningService.createChannel, returns formatted JSON response with channel details and comprehensive Swift iOS LDK example code.
      execute: async (args: any): Promise<ToolResult> => {
        try {
          const channel = await lightningService.createChannel(
            args.remotePubkey,
            args.capacitySats * 1000, // Convert to millisats
            args.pushSats * 1000
          );
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                success: true,
                channel: {
                  channelId: channel.channelId,
                  shortChannelId: channel.shortChannelId,
                  fundingTxid: channel.fundingTxid,
                  capacitySats: Math.floor(channel.capacityMsat / 1000),
                  localBalanceSats: Math.floor(channel.localBalanceMsat / 1000),
                  remoteBalanceSats: Math.floor(channel.remoteBalanceMsat / 1000),
                  state: channel.state
                },
                swiftExample: `
    // Swift code to open a channel in your iOS app using LDK
    import LightningDevKit
    import BitcoinDevKit
    
    class ChannelOpener {
        let channelManager: Bindings.ChannelManager
        let wallet: BitcoinDevKit.Wallet
        let logger: Bindings.Logger
        
        func openChannel(
            remotePubkey: String,
            capacitySats: UInt64,
            pushSats: UInt64 = 0,
            isPublic: Bool = false
        ) async throws -> Bindings.ChannelId {
            // Parse remote pubkey
            guard let pubkeyData = Data(hexString: remotePubkey),
                  pubkeyData.count == 33 else {
                throw ChannelError.invalidPubkey
            }
            
            // Configure channel
            let userConfig = Bindings.UserConfig.initWithDefault()
            let channelHandshakeConfig = Bindings.ChannelHandshakeConfig.initWithDefault()
            channelHandshakeConfig.setAnnouncedChannel(val: isPublic)
            channelHandshakeConfig.setMinimumDepth(val: 3) // 3 confirmations
            userConfig.setChannelHandshakeConfig(val: channelHandshakeConfig)
            
            // Generate user channel ID (16 bytes)
            let userChannelId = Array<UInt8>(repeating: 0, count: 16)
            arc4random_buf(&userChannelId, 16)
            
            // Create channel with proper error handling
            let result = channelManager.createChannel(
                theirNetworkKey: pubkeyData.bytes,
                channelValueSatoshis: capacitySats,
                pushMsat: pushSats * 1000,
                userChannelId: userChannelId,
                temporaryChannelId: nil,
                overrideConfig: userConfig
            )
            
            guard result.isOk() else {
                let error = result.getError()!
                throw ChannelError.creationFailed(error.getValueAsApiMisuseError()?.getErrMessage() ?? "Unknown error")
            }
            
            return result.getValue()!
        }
        
        // Handle funding generation event
        func handleFundingGeneration(event: Bindings.Event.FundingGenerationReady) async throws {
            let outputScript = Script(rawOutputScript: event.getOutputScript())
            let amount = event.getChannelValueSatoshis()
            
            // Build funding transaction with BDK
            let txBuilder = try TxBuilder()
                .addRecipient(script: outputScript, amount: amount)
                .feeRate(satPerVbyte: 5.0)
                .enableRbf()
            
            let psbt = try txBuilder.finish(wallet: wallet)
            let signed = try wallet.sign(psbt: psbt, signOptions: nil)
            let fundingTx = signed.extractTx()
            
            // Provide funding transaction to LDK
            channelManager.fundingTransactionGenerated(
                temporaryChannelId: event.getTemporaryChannelId(),
                counterpartyNodeId: event.getCounterpartyNodeId(),
                fundingTransaction: fundingTx.serialize()
            )
            
            // Broadcast transaction
            try await broadcastTransaction(fundingTx)
        }
    }
    
    // SwiftUI view for channel opening
    struct OpenChannelView: View {
        @State private var remotePubkey = ""
        @State private var capacitySats = "100000"
        @State private var pushSats = "0"
        @State private var isPublic = false
        @State private var isOpening = false
        @State private var error: String?
        
        var body: some View {
            Form {
                Section("Channel Details") {
                    TextField("Remote Node Pubkey", text: $remotePubkey)
                        .font(.system(.body, design: .monospaced))
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    
                    HStack {
                        TextField("Capacity (sats)", text: $capacitySats)
                            .keyboardType(.numberPad)
                        
                        Text("sats")
                            .foregroundColor(.secondary)
                    }
                    
                    HStack {
                        TextField("Push Amount (sats)", text: $pushSats)
                            .keyboardType(.numberPad)
                        
                        Text("sats")
                            .foregroundColor(.secondary)
                    }
                    
                    Toggle("Public Channel", isOn: $isPublic)
                }
                
                Section("Fee Estimate") {
                    HStack {
                        Label("On-chain Fee", systemImage: "bitcoinsign.circle")
                        Spacer()
                        Text("~500 sats")
                            .foregroundColor(.secondary)
                    }
                }
                
                Section {
                    Button(action: openChannel) {
                        if isOpening {
                            HStack {
                                ProgressView()
                                    .scaleEffect(0.8)
                                Text("Opening Channel...")
                            }
                        } else {
                            Text("Open Channel")
                        }
                    }
                    .frame(maxWidth: .infinity)
                    .disabled(isOpening || !isValid)
                }
            }
            .navigationTitle("Open Channel")
            .alert("Error", isPresented: .constant(error != nil)) {
                Button("OK") { error = nil }
            } message: {
                Text(error ?? "")
            }
        }
        
        var isValid: Bool {
            !remotePubkey.isEmpty &&
            Int(capacitySats) ?? 0 >= 20000 &&
            Int(pushSats) ?? 0 >= 0
        }
        
        func openChannel() {
            Task {
                isOpening = true
                defer { isOpening = false }
                
                do {
                    let capacity = UInt64(capacitySats) ?? 0
                    let push = UInt64(pushSats) ?? 0
                    
                    try await LDKManager.shared.openChannel(
                        remotePubkey: remotePubkey,
                        capacitySats: capacity,
                        pushSats: push,
                        isPublic: isPublic
                    )
                    
                    // Navigate back or show success
                } catch {
                    self.error = error.localizedDescription
                }
            }
        }
    }`.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 defining parameters for creating a Lightning channel: remotePubkey (required), capacitySats (required, min 20k), pushSats and isPublic (optional).
    inputSchema: {
      type: 'object',
      properties: {
        remotePubkey: {
          type: 'string',
          description: 'Remote node public key (hex encoded)'
        },
        capacitySats: {
          type: 'number',
          description: 'Channel capacity in satoshis',
          minimum: 20000
        },
        pushSats: {
          type: 'number',
          description: 'Amount to push to remote side (optional)',
          default: 0
        },
        isPublic: {
          type: 'boolean',
          description: 'Whether to announce channel publicly',
          default: false
        }
      },
      required: ['remotePubkey', 'capacitySats']
    },
  • src/index.ts:38-62 (registration)
    Registration of the createChannelTool (line 48) in the central tools array used by the 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,
    ];
Behavior2/5

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

No annotations are provided, so the description carries full burden. While 'Open a Lightning channel' implies a write/mutation operation, it doesn't disclose critical behavioral aspects: whether this requires specific permissions, if it's irreversible, what happens on failure, network implications, or confirmation requirements. For a financial operation with no 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 gets straight to the point with zero wasted words. It's appropriately sized for a tool with good schema documentation and follows the principle of front-loading the core purpose.

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?

For a financial channel creation tool with no annotations and no output schema, the description is insufficient. It doesn't explain what happens after channel creation, what the tool returns, error conditions, or integration with the broader Lightning Network context. Given the complexity and lack of structured metadata, more guidance is needed.

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%, providing complete parameter documentation. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain relationships between parameters (e.g., how pushSats relates to capacitySats) or provide usage examples. With high schema coverage, baseline 3 is appropriate.

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 ('Open') and resource ('Lightning channel with a peer node'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'ldk_close_channel' or explain what distinguishes channel creation from other operations in the LDK context.

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 (like needing a peer connection), when channel creation is appropriate versus other payment methods, or what happens if the peer is unavailable. With sibling tools like 'ldk_pay_invoice' and 'ldk_close_channel', this lack of differentiation is problematic.

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