[Lldb-commits] [lldb] [lldb-mcp] Auto connect to the first running lldb mcp instance. (PR #157503)

via lldb-commits lldb-commits at lists.llvm.org
Mon Sep 8 09:15:58 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lldb

Author: John Harrison (ashgti)

<details>
<summary>Changes</summary>

This improves the flow by automatically connecting to an exisitng lldb instance, if one is found.

Future improvements include:

* Launching a binary if an instance isn't detected.
* Multiplexing if multiple instances are detected.

---
Full diff: https://github.com/llvm/llvm-project/pull/157503.diff


4 Files Affected:

- (modified) lldb/include/lldb/Protocol/MCP/Server.h (+3) 
- (modified) lldb/source/Protocol/MCP/Server.cpp (+60-42) 
- (modified) lldb/tools/lldb-mcp/CMakeLists.txt (+1) 
- (modified) lldb/tools/lldb-mcp/lldb-mcp.cpp (+107-18) 


``````````diff
diff --git a/lldb/include/lldb/Protocol/MCP/Server.h b/lldb/include/lldb/Protocol/MCP/Server.h
index 254b7d9680cd8..567af96530e89 100644
--- a/lldb/include/lldb/Protocol/MCP/Server.h
+++ b/lldb/include/lldb/Protocol/MCP/Server.h
@@ -30,6 +30,9 @@ namespace lldb_protocol::mcp {
 struct ServerInfo {
   std::string connection_uri;
   lldb::pid_t pid;
+
+  static llvm::Error Write(const ServerInfo &);
+  static llvm::Expected<std::vector<ServerInfo>> Load();
 };
 llvm::json::Value toJSON(const ServerInfo &);
 bool fromJSON(const llvm::json::Value &, ServerInfo &, llvm::json::Path);
diff --git a/lldb/source/Protocol/MCP/Server.cpp b/lldb/source/Protocol/MCP/Server.cpp
index 0381b7f745e98..cb0e1034fe51f 100644
--- a/lldb/source/Protocol/MCP/Server.cpp
+++ b/lldb/source/Protocol/MCP/Server.cpp
@@ -11,62 +11,80 @@
 #include "lldb/Protocol/MCP/Protocol.h"
 #include "llvm/Support/JSON.h"
 
-using namespace lldb_protocol::mcp;
 using namespace llvm;
+using namespace lldb_private;
+using namespace lldb_protocol::mcp;
 
-llvm::json::Value lldb_protocol::mcp::toJSON(const ServerInfo &SM) {
-  return llvm::json::Object{{"connection_uri", SM.connection_uri},
-                            {"pid", SM.pid}};
+json::Value lldb_protocol::mcp::toJSON(const ServerInfo &SM) {
+  return json::Object{{"connection_uri", SM.connection_uri}, {"pid", SM.pid}};
 }
 
-bool lldb_protocol::mcp::fromJSON(const llvm::json::Value &V, ServerInfo &SM,
-                                  llvm::json::Path P) {
-  llvm::json::ObjectMapper O(V, P);
+bool lldb_protocol::mcp::fromJSON(const json::Value &V, ServerInfo &SM,
+                                  json::Path P) {
+  json::ObjectMapper O(V, P);
   return O && O.map("connection_uri", SM.connection_uri) &&
          O.map("pid", SM.pid);
 }
 
-Server::Server(std::string name, std::string version,
-               std::unique_ptr<MCPTransport> transport_up,
-               lldb_private::MainLoop &loop)
-    : m_name(std::move(name)), m_version(std::move(version)),
-      m_transport_up(std::move(transport_up)), m_loop(loop) {
-  AddRequestHandlers();
-}
+llvm::Error ServerInfo::Write(const ServerInfo &info) {
+  std::string buf = formatv("{0}", toJSON(info)).str();
+  size_t num_bytes = buf.size();
 
-void Server::AddRequestHandlers() {
-  AddRequestHandler("initialize", std::bind(&Server::InitializeHandler, this,
-                                            std::placeholders::_1));
-  AddRequestHandler("tools/list", std::bind(&Server::ToolsListHandler, this,
-                                            std::placeholders::_1));
-  AddRequestHandler("tools/call", std::bind(&Server::ToolsCallHandler, this,
-                                            std::placeholders::_1));
-  AddRequestHandler("resources/list", std::bind(&Server::ResourcesListHandler,
-                                                this, std::placeholders::_1));
-  AddRequestHandler("resources/read", std::bind(&Server::ResourcesReadHandler,
-                                                this, std::placeholders::_1));
-}
+  FileSpec user_lldb_dir = HostInfo::GetUserLLDBDir();
 
-llvm::Expected<Response> Server::Handle(const Request &request) {
-  auto it = m_request_handlers.find(request.method);
-  if (it != m_request_handlers.end()) {
-    llvm::Expected<Response> response = it->second(request);
-    if (!response)
-      return response;
-    response->id = request.id;
-    return *response;
-  }
+  Status error(llvm::sys::fs::create_directory(user_lldb_dir.GetPath()));
+  if (error.Fail())
+    return error.takeError();
+
+  FileSpec mcp_registry_entry_path = user_lldb_dir.CopyByAppendingPathComponent(
+      formatv("lldb-mcp-{0}.json", getpid()).str());
 
-  return llvm::make_error<MCPError>(
-      llvm::formatv("no handler for request: {0}", request.method).str());
+  const File::OpenOptions flags = File::eOpenOptionWriteOnly |
+                                  File::eOpenOptionCanCreate |
+                                  File::eOpenOptionTruncate;
+  llvm::Expected<lldb::FileUP> file = FileSystem::Instance().Open(
+      mcp_registry_entry_path, flags, lldb::eFilePermissionsFileDefault, false);
+  if (!file)
+    return file.takeError();
+  if (llvm::Error error = (*file)->Write(buf.data(), num_bytes).takeError())
+    return error;
+  return llvm::Error::success();
 }
 
-void Server::Handle(const Notification &notification) {
-  auto it = m_notification_handlers.find(notification.method);
-  if (it != m_notification_handlers.end()) {
-    it->second(notification);
-    return;
+llvm::Expected<std::vector<ServerInfo>> ServerInfo::Load() {
+  FileSpec user_lldb_dir = HostInfo::GetUserLLDBDir();
+  namespace path = llvm::sys::path;
+  FileSystem &fs = FileSystem::Instance();
+  std::error_code EC;
+  llvm::vfs::directory_iterator it = fs.DirBegin(user_lldb_dir, EC);
+  llvm::vfs::directory_iterator end;
+  std::vector<ServerInfo> infos;
+  for (; it != end && !EC; it.increment(EC)) {
+    auto &entry = *it;
+    auto name = path::filename(entry.path());
+    if (!name.starts_with("lldb-mcp-") || !name.ends_with(".json")) {
+      continue;
+    }
+
+    llvm::Expected<std::unique_ptr<File>> file =
+        fs.Open(FileSpec(entry.path()), File::eOpenOptionReadOnly);
+    if (!file)
+      return file.takeError();
+
+    char buf[1024] = {0};
+    size_t bytes_read = sizeof(buf);
+    if (llvm::Error error = (*file)->Read(buf, bytes_read).takeError())
+      return std::move(error);
+
+    auto info = json::parse<ServerInfo>(StringRef(buf, bytes_read));
+    if (!info)
+      return info.takeError();
+
+    infos.emplace_back(std::move(*info));
   }
+
+  return infos;
+}
 }
 
 void Server::AddTool(std::unique_ptr<Tool> tool) {
diff --git a/lldb/tools/lldb-mcp/CMakeLists.txt b/lldb/tools/lldb-mcp/CMakeLists.txt
index 7fe3301ab3081..5f61a1993cea3 100644
--- a/lldb/tools/lldb-mcp/CMakeLists.txt
+++ b/lldb/tools/lldb-mcp/CMakeLists.txt
@@ -6,6 +6,7 @@ add_lldb_tool(lldb-mcp
     Support
   LINK_LIBS
     liblldb
+    lldbInitialization
     lldbHost
     lldbProtocolMCP
   )
diff --git a/lldb/tools/lldb-mcp/lldb-mcp.cpp b/lldb/tools/lldb-mcp/lldb-mcp.cpp
index 6c4ebbaa5f230..498eaaaa8f383 100644
--- a/lldb/tools/lldb-mcp/lldb-mcp.cpp
+++ b/lldb/tools/lldb-mcp/lldb-mcp.cpp
@@ -10,17 +10,28 @@
 #include "lldb/Host/File.h"
 #include "lldb/Host/MainLoop.h"
 #include "lldb/Host/MainLoopBase.h"
-#include "lldb/Protocol/MCP/Protocol.h"
+#include "lldb/Host/Socket.h"
+#include "lldb/Initialization/SystemInitializerCommon.h"
+#include "lldb/Initialization/SystemLifetimeManager.h"
 #include "lldb/Protocol/MCP/Server.h"
+#include "lldb/Utility/Status.h"
+#include "lldb/Utility/UriParser.h"
+#include "lldb/lldb-forward.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/WithColor.h"
+#include <cstdlib>
+#include <memory>
 
 #if defined(_WIN32)
 #include <fcntl.h>
 #endif
 
+using namespace llvm;
+using namespace lldb;
 using namespace lldb_protocol::mcp;
 
 using lldb_private::File;
@@ -28,8 +39,78 @@ using lldb_private::MainLoop;
 using lldb_private::MainLoopBase;
 using lldb_private::NativeFile;
 
-static constexpr llvm::StringLiteral kName = "lldb-mcp";
-static constexpr llvm::StringLiteral kVersion = "0.1.0";
+namespace {
+
+inline void error(llvm::Error Err, StringRef Prefix = "") {
+  handleAllErrors(std::move(Err), [&](ErrorInfoBase &Info) {
+    WithColor::error(errs(), Prefix) << Info.message() << '\n';
+  });
+  std::exit(EXIT_FAILURE);
+}
+
+constexpr size_t kForwardIOBufferSize = 1024;
+
+void forwardIO(lldb_private::MainLoopBase &loop, lldb::IOObjectSP &from,
+               lldb::IOObjectSP &to) {
+  char buf[kForwardIOBufferSize];
+  size_t num_bytes = sizeof(buf);
+
+  if (llvm::Error err = from->Read(buf, num_bytes).takeError())
+    error(std::move(err));
+
+  // EOF reached.
+  if (num_bytes == 0)
+    return loop.RequestTermination();
+
+  if (llvm::Error err = to->Write(buf, num_bytes).takeError())
+    error(std::move(err));
+}
+
+void connectAndForwardIO(lldb_private::MainLoop &loop, ServerInfo &info,
+                         IOObjectSP &input_sp, IOObjectSP &output_sp) {
+  auto uri = lldb_private::URI::Parse(info.connection_uri);
+  if (!uri)
+    error(createStringError("invalid connection_uri"));
+
+  std::optional<lldb_private::Socket::ProtocolModePair> protocol_and_mode =
+      lldb_private::Socket::GetProtocolAndMode(uri->scheme);
+
+  lldb_private::Status status;
+  std::unique_ptr<lldb_private::Socket> sock =
+      lldb_private::Socket::Create(protocol_and_mode->first, status);
+
+  if (status.Fail())
+    error(status.takeError());
+
+  if (uri->port && !uri->hostname.empty())
+    status = sock->Connect(
+        llvm::formatv("[{0}]:{1}", uri->hostname, *uri->port).str());
+  else
+    status = sock->Connect(uri->path);
+  if (status.Fail())
+    error(status.takeError());
+
+  IOObjectSP sock_sp = std::move(sock);
+  auto input_handle = loop.RegisterReadObject(
+      input_sp, std::bind(forwardIO, std::placeholders::_1, input_sp, sock_sp),
+      status);
+  if (status.Fail())
+    error(status.takeError());
+
+  auto socket_handle = loop.RegisterReadObject(
+      sock_sp, std::bind(forwardIO, std::placeholders::_1, sock_sp, output_sp),
+      status);
+  if (status.Fail())
+    error(status.takeError());
+
+  status = loop.Run();
+  if (status.Fail())
+    error(status.takeError());
+}
+
+llvm::ManagedStatic<lldb_private::SystemLifetimeManager> g_debugger_lifetime;
+
+} // namespace
 
 int main(int argc, char *argv[]) {
   llvm::InitLLVM IL(argc, argv, /*InstallPipeSignalExitHandler=*/false);
@@ -53,33 +134,41 @@ int main(int argc, char *argv[]) {
   assert(result);
 #endif
 
-  lldb::IOObjectSP input = std::make_shared<NativeFile>(
+  if (auto e = g_debugger_lifetime->Initialize(
+          std::make_unique<lldb_private::SystemInitializerCommon>(nullptr)))
+    error(std::move(e));
+
+  IOObjectSP input_sp = std::make_shared<NativeFile>(
       fileno(stdin), File::eOpenOptionReadOnly, NativeFile::Unowned);
 
-  lldb::IOObjectSP output = std::make_shared<NativeFile>(
+  IOObjectSP output_sp = std::make_shared<NativeFile>(
       fileno(stdout), File::eOpenOptionWriteOnly, NativeFile::Unowned);
 
-  constexpr llvm::StringLiteral client_name = "stdio";
   static MainLoop loop;
 
-  llvm::sys::SetInterruptFunction([]() {
+  sys::SetInterruptFunction([]() {
     loop.AddPendingCallback(
         [](MainLoopBase &loop) { loop.RequestTermination(); });
   });
 
-  auto transport_up = std::make_unique<lldb_protocol::mcp::Transport>(
-      input, output, [&](llvm::StringRef message) {
-        llvm::errs() << formatv("{0}: {1}", client_name, message) << '\n';
-      });
+  auto existing_servers = ServerInfo::Load();
+
+  if (!existing_servers)
+    error(existing_servers.takeError());
+
+  // FIXME: Launch `lldb -o 'protocol start MCP'`.
+  if (existing_servers->empty())
+    error(createStringError("No MCP servers running"));
+
+  // FIXME: Support selecting a specific server.
+  if (existing_servers->size() != 1)
+    error(createStringError("To many MCP servers running, picking a specific "
+                            "one is not yet implemented."));
 
-  auto instance_up = std::make_unique<lldb_protocol::mcp::Server>(
-      std::string(kName), std::string(kVersion), std::move(transport_up), loop);
+  ServerInfo &info = existing_servers->front();
+  connectAndForwardIO(loop, info, input_sp, output_sp);
 
-  if (llvm::Error error = instance_up->Run()) {
-    llvm::logAllUnhandledErrors(std::move(error), llvm::WithColor::error(),
-                                "MCP error: ");
-    return EXIT_FAILURE;
-  }
+  g_debugger_lifetime->Terminate();
 
   return EXIT_SUCCESS;
 }

``````````

</details>


https://github.com/llvm/llvm-project/pull/157503


More information about the lldb-commits mailing list