Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/mcp.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
name: MCP Checks

on: [ push, pull_request ]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
mcp-unit:
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v6

- name: Install Rust stable toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable
rustup override set stable
rustup component add clippy

- name: Check MCP crate builds
run: cargo check -p ldk-server-mcp

- name: Run MCP crate tests
run: cargo test -p ldk-server-mcp

- name: Run MCP crate clippy
run: cargo clippy -p ldk-server-mcp --all-targets -- -D warnings
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server"]
members = ["ldk-server-cli", "ldk-server-client", "ldk-server-grpc", "ldk-server", "ldk-server-mcp"]
exclude = ["e2e-tests"]

[profile.release]
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,14 @@ The primary goal of LDK Server is to provide an efficient, stable, and API-first
a Lightning Network node. With its streamlined setup, LDK Server enables users to easily set up, configure, and run
a Lightning node while exposing a robust, language-agnostic API via [Protocol Buffers (Protobuf)](https://protobuf.dev/).

## Workspace Crates

- `ldk-server`: daemon that runs the Lightning node and exposes the API
- `ldk-server-cli`: CLI client for the server API
- `ldk-server-client`: Rust client library for authenticated TLS gRPC calls
- `ldk-server-grpc`: generated protobuf and shared gRPC types
- `ldk-server-mcp`: stdio MCP bridge exposing unary `ldk-server` RPCs as MCP tools

### Features

- **Out-of-the-Box Lightning Node**:
Expand DownExpand Up@@ -58,6 +66,18 @@ See [Getting Started](docs/getting-started.md) for a full walkthrough.
The canonical API definitions are in [`ldk-server-grpc/src/proto/`](ldk-server-grpc/src/proto/). A ready-made
Rust client library is provided in [`ldk-server-client/`](ldk-server-client/).

### MCP Bridge

The workspace also includes `ldk-server-mcp`, a stdio [Model Context Protocol](https://spec.modelcontextprotocol.io/) server
that lets MCP-compatible clients call the unary `ldk-server` RPC surface as tools.

Run it directly from the workspace:
```bash
cargo run -p ldk-server-mcp -- --config /path/to/config.toml
```

It is covered by both crate-local tests and an `e2e-tests` sanity suite against a live `ldk-server` instance.

### Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on building, testing, code style, and development workflow.
1 change: 1 addition & 0 deletions e2e-tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions e2e-tests/build.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,14 @@ fn main() {
.expect("e2e-tests must be inside workspace")
.to_path_buf();

let outer_target_dir = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.map(|path| if path.is_absolute() { path } else { workspace_root.join(path) })
.unwrap_or_else(|| workspace_root.join("target"));

// Use a separate target directory so the inner cargo build doesn't deadlock
// waiting for the build directory lock held by the outer cargo.
let target_dir = workspace_root.join("target").join("e2e-deps");
let target_dir = outer_target_dir.join("e2e-deps");

let status = Command::new(&cargo)
.args([
Expand All@@ -24,21 +29,25 @@ fn main() {
"experimental-lsps2-support",
"-p",
"ldk-server-cli",
"-p",
"ldk-server-mcp",
])
.current_dir(&workspace_root)
.env("CARGO_TARGET_DIR", &target_dir)
.env_remove("CARGO_ENCODED_RUSTFLAGS")
.status()
.expect("failed to run cargo build");

assert!(status.success(), "cargo build of ldk-server / ldk-server-cli failed");
assert!(status.success(), "cargo build of ldk-server / ldk-server-cli / ldk-server-mcp failed");

let bin_dir = target_dir.join(&profile);
let server_bin = bin_dir.join("ldk-server");
let cli_bin = bin_dir.join("ldk-server-cli");
let mcp_bin = bin_dir.join("ldk-server-mcp");

println!("cargo:rustc-env=LDK_SERVER_BIN={}", server_bin.display());
println!("cargo:rustc-env=LDK_SERVER_CLI_BIN={}", cli_bin.display());
println!("cargo:rustc-env=LDK_SERVER_MCP_BIN={}", mcp_bin.display());

// Rebuild when server or CLI source changes
println!("cargo:rerun-if-changed=../ldk-server/src");
Expand All@@ -47,4 +56,6 @@ fn main() {
println!("cargo:rerun-if-changed=../ldk-server-cli/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-grpc/src");
println!("cargo:rerun-if-changed=../ldk-server-grpc/Cargo.toml");
println!("cargo:rerun-if-changed=../ldk-server-mcp/src");
println!("cargo:rerun-if-changed=../ldk-server-mcp/Cargo.toml");
}
66 changes: 65 additions & 1 deletion e2e-tests/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.

use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
Expand All@@ -16,6 +16,7 @@ use std::time::Duration;
use corepc_node::Node;
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use serde_json::Value;
use ldk_server_client::ldk_server_grpc::api::{GetNodeInfoRequest, GetNodeInfoResponse};
use ldk_server_grpc::api::{
GetBalancesRequest, ListChannelsRequest, OnchainReceiveRequest, OpenChannelRequest,
Expand DownExpand Up@@ -291,6 +292,69 @@ pub fn cli_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_CLI_BIN"))
}

/// Returns the path to the ldk-server-mcp binary (built automatically by build.rs).
pub fn mcp_binary_path() -> PathBuf {
PathBuf::from(env!("LDK_SERVER_MCP_BIN"))
}

/// Handle to a running ldk-server-mcp child process.
pub struct McpHandle {
child: Option<Child>,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}

impl McpHandle {
pub fn start(server: &LdkServerHandle) -> Self {
let mcp_path = mcp_binary_path();
let mut child = Command::new(&mcp_path)
.env("LDK_BASE_URL", server.base_url())
.env("LDK_API_KEY", &server.api_key)
.env("LDK_TLS_CERT_PATH", server.tls_cert_path.to_str().unwrap())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Failed to run MCP server at {:?}: {}", mcp_path, e));

let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());

Self { child: Some(child), stdin, stdout }
}

pub fn send(&mut self, request: &Value) {
let line = serde_json::to_string(request).unwrap();
writeln!(self.stdin, "{}", line).unwrap();
self.stdin.flush().unwrap();
}

pub fn recv(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).expect("Failed to read MCP stdout");
serde_json::from_str(line.trim()).expect("Failed to parse MCP response")
}

pub fn call(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(&serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}));
self.recv()
}
}

impl Drop for McpHandle {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}

/// Run a CLI command against the given server handle and return raw stdout as a string.
pub fn run_cli_raw(handle: &LdkServerHandle, args: &[&str]) -> String {
let cli_path = cli_binary_path();
Expand Down
87 changes: 87 additions & 0 deletions e2e-tests/tests/mcp.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use e2e_tests::{LdkServerHandle, McpHandle, TestBitcoind};
use ldk_server_client::ldk_server_grpc::api::Bolt11ReceiveRequest;
use ldk_server_client::ldk_server_grpc::types::{
bolt11_invoice_description, Bolt11InvoiceDescription,
};
use serde_json::json;

#[tokio::test]
async fn test_mcp_initialize_and_list_tools() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let initialize = mcp.call(
1,
"initialize",
json!({
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "e2e-test", "version": "0.1"}
}),
);
assert_eq!(initialize["result"]["protocolVersion"], "2025-11-25");
assert!(initialize["result"]["capabilities"]["tools"].is_object());

let tools = mcp.call(2, "tools/list", json!({}));
let tool_names = tools["result"]["tools"].as_array().unwrap();
assert!(tool_names.iter().any(|tool| tool["name"] == "get_node_info"));
assert!(tool_names.iter().any(|tool| tool["name"] == "onchain_receive"));
assert!(tool_names.iter().any(|tool| tool["name"] == "decode_invoice"));
}

#[tokio::test]
async fn test_mcp_live_tool_calls() {
let bitcoind = TestBitcoind::new();
let server = LdkServerHandle::start(&bitcoind).await;
let mut mcp = McpHandle::start(&server);

let node_info = mcp.call(1, "tools/call", json!({
"name": "get_node_info",
"arguments": {}
}));
let node_info_text = node_info["result"]["content"][0]["text"].as_str().unwrap();
let node_info_json: serde_json::Value = serde_json::from_str(node_info_text).unwrap();
assert_eq!(node_info_json["node_id"], server.node_id());

let onchain_receive = mcp.call(2, "tools/call", json!({
"name": "onchain_receive",
"arguments": {}
}));
let onchain_receive_text = onchain_receive["result"]["content"][0]["text"].as_str().unwrap();
let onchain_receive_json: serde_json::Value =
serde_json::from_str(onchain_receive_text).unwrap();
assert!(onchain_receive_json["address"].as_str().unwrap().starts_with("bcrt1"));

let invoice = server
.client()
.bolt11_receive(Bolt11ReceiveRequest {
amount_msat: Some(50_000_000),
description: Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct("mcp decode".to_string())),
}),
expiry_secs: 3600,
})
.await
.unwrap();

let decode_invoice = mcp.call(3, "tools/call", json!({
"name": "decode_invoice",
"arguments": { "invoice": invoice.invoice }
}));
let decode_invoice_text = decode_invoice["result"]["content"][0]["text"].as_str().unwrap();
let decode_invoice_json: serde_json::Value =
serde_json::from_str(decode_invoice_text).unwrap();
assert_eq!(decode_invoice_json["destination"], server.node_id());
assert_eq!(decode_invoice_json["description"], "mcp decode");
assert_eq!(decode_invoice_json["amount_msat"], 50_000_000u64);
}
Loading