Skip to content

[lldb] Expose debuggers and target as resources through MCP #148075

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 11, 2025
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
2 changes: 1 addition & 1 deletion lldb/include/lldb/Core/Debugger.h
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ class Debugger : public std::enable_shared_from_this<Debugger>,

bool GetNotifyVoid() const;

const std::string &GetInstanceName() { return m_instance_name; }
const std::string &GetInstanceName() const { return m_instance_name; }

bool GetShowInlineDiagnostics() const;

Expand Down
2 changes: 1 addition & 1 deletion lldb/include/lldb/Target/Target.h
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,7 @@ class Target : public std::enable_shared_from_this<Target>,

Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }

Debugger &GetDebugger() { return m_debugger; }
Debugger &GetDebugger() const { return m_debugger; }

size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
Status &error);
Expand Down
1 change: 1 addition & 0 deletions lldb/source/Plugins/Protocol/MCP/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ add_lldb_library(lldbPluginProtocolServerMCP PLUGIN
MCPError.cpp
Protocol.cpp
ProtocolServerMCP.cpp
Resource.cpp
Tool.cpp

LINK_COMPONENTS
Expand Down
11 changes: 11 additions & 0 deletions lldb/source/Plugins/Protocol/MCP/MCPError.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace lldb_private::mcp {

char MCPError::ID;
char UnsupportedURI::ID;

MCPError::MCPError(std::string message, int64_t error_code)
: m_message(message), m_error_code(error_code) {}
Expand All @@ -31,4 +32,14 @@ protocol::Error MCPError::toProtcolError() const {
return error;
}

UnsupportedURI::UnsupportedURI(std::string uri) : m_uri(uri) {}

void UnsupportedURI::log(llvm::raw_ostream &OS) const {
OS << "unsupported uri: " << m_uri;
}

std::error_code UnsupportedURI::convertToErrorCode() const {
return llvm::inconvertibleErrorCode();
}

} // namespace lldb_private::mcp
19 changes: 18 additions & 1 deletion lldb/source/Plugins/Protocol/MCP/MCPError.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "Protocol.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatVariadic.h"
#include <string>

namespace lldb_private::mcp {
Expand All @@ -16,7 +17,7 @@ class MCPError : public llvm::ErrorInfo<MCPError> {
public:
static char ID;

MCPError(std::string message, int64_t error_code);
MCPError(std::string message, int64_t error_code = kInternalError);

void log(llvm::raw_ostream &OS) const override;
std::error_code convertToErrorCode() const override;
Expand All @@ -25,9 +26,25 @@ class MCPError : public llvm::ErrorInfo<MCPError> {

protocol::Error toProtcolError() const;

static constexpr int64_t kResourceNotFound = -32002;
static constexpr int64_t kInternalError = -32603;

private:
std::string m_message;
int64_t m_error_code;
};

class UnsupportedURI : public llvm::ErrorInfo<UnsupportedURI> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the MCP spec, there are 2 error codes for resources:

  • Resource not found: -32002
  • Internal errors: -32603

See https://modelcontextprotocol.io/specification/2025-06-18/server/resources#error-handling

Should we use those here?

public:
static char ID;

UnsupportedURI(std::string uri);

void log(llvm::raw_ostream &OS) const override;
std::error_code convertToErrorCode() const override;

private:
std::string m_uri;
};

} // namespace lldb_private::mcp
54 changes: 53 additions & 1 deletion lldb/source/Plugins/Protocol/MCP/Protocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,67 @@ bool fromJSON(const llvm::json::Value &V, ToolCapability &TC,
return O && O.map("listChanged", TC.listChanged);
}

llvm::json::Value toJSON(const ResourceCapability &RC) {
return llvm::json::Object{{"listChanged", RC.listChanged},
{"subscribe", RC.subscribe}};
}

bool fromJSON(const llvm::json::Value &V, ResourceCapability &RC,
llvm::json::Path P) {
llvm::json::ObjectMapper O(V, P);
return O && O.map("listChanged", RC.listChanged) &&
O.map("subscribe", RC.subscribe);
}

llvm::json::Value toJSON(const Capabilities &C) {
return llvm::json::Object{{"tools", C.tools}};
return llvm::json::Object{{"tools", C.tools}, {"resources", C.resources}};
}

bool fromJSON(const llvm::json::Value &V, Resource &R, llvm::json::Path P) {
llvm::json::ObjectMapper O(V, P);
return O && O.map("uri", R.uri) && O.map("name", R.name) &&
O.mapOptional("description", R.description) &&
O.mapOptional("mimeType", R.mimeType);
}

llvm::json::Value toJSON(const Resource &R) {
llvm::json::Object Result{{"uri", R.uri}, {"name", R.name}};
if (R.description)
Result.insert({"description", R.description});
if (R.mimeType)
Result.insert({"mimeType", R.mimeType});
return Result;
}

bool fromJSON(const llvm::json::Value &V, Capabilities &C, llvm::json::Path P) {
llvm::json::ObjectMapper O(V, P);
return O && O.map("tools", C.tools);
}

llvm::json::Value toJSON(const ResourceContents &RC) {
llvm::json::Object Result{{"uri", RC.uri}, {"text", RC.text}};
if (RC.mimeType)
Result.insert({"mimeType", RC.mimeType});
return Result;
}

bool fromJSON(const llvm::json::Value &V, ResourceContents &RC,
llvm::json::Path P) {
llvm::json::ObjectMapper O(V, P);
return O && O.map("uri", RC.uri) && O.map("text", RC.text) &&
O.mapOptional("mimeType", RC.mimeType);
}

llvm::json::Value toJSON(const ResourceResult &RR) {
return llvm::json::Object{{"contents", RR.contents}};
}

bool fromJSON(const llvm::json::Value &V, ResourceResult &RR,
llvm::json::Path P) {
llvm::json::ObjectMapper O(V, P);
return O && O.map("contents", RR.contents);
}

llvm::json::Value toJSON(const TextContent &TC) {
return llvm::json::Object{{"type", "text"}, {"text", TC.text}};
}
Expand Down
60 changes: 59 additions & 1 deletion lldb/source/Plugins/Protocol/MCP/Protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,75 @@ struct ToolCapability {
llvm::json::Value toJSON(const ToolCapability &);
bool fromJSON(const llvm::json::Value &, ToolCapability &, llvm::json::Path);

struct ResourceCapability {
/// Whether this server supports notifications for changes to the resources
/// list.
bool listChanged = false;

/// Whether subscriptions are supported.
bool subscribe = false;
};

llvm::json::Value toJSON(const ResourceCapability &);
bool fromJSON(const llvm::json::Value &, ResourceCapability &,
llvm::json::Path);

/// Capabilities that a server may support. Known capabilities are defined here,
/// in this schema, but this is not a closed set: any server can define its own,
/// additional capabilities.
struct Capabilities {
/// Present if the server offers any tools to call.
/// Tool capabilities of the server.
ToolCapability tools;

/// Resource capabilities of the server.
ResourceCapability resources;
};

llvm::json::Value toJSON(const Capabilities &);
bool fromJSON(const llvm::json::Value &, Capabilities &, llvm::json::Path);

/// A known resource that the server is capable of reading.
struct Resource {
/// The URI of this resource.
std::string uri;

/// A human-readable name for this resource.
std::string name;

/// A description of what this resource represents.
std::optional<std::string> description;

/// The MIME type of this resource, if known.
std::optional<std::string> mimeType;
Comment on lines +115 to +118
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been using std::optional less in lldb-dap's protocols because here isn't much of a meaningful difference between an empty string and std::nullopt. Not a required change, but I find it makes it easier to think about since I don't have to double check if field != std::nullopt && !field->empty(), I can just do !field.empty().

When encoding toJSON we can check if the string is empty and not include it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me do this as a followup for all of MCP 👍

};

llvm::json::Value toJSON(const Resource &);
bool fromJSON(const llvm::json::Value &, Resource &, llvm::json::Path);

/// The contents of a specific resource or sub-resource.
struct ResourceContents {
/// The URI of this resource.
std::string uri;

/// The text of the item. This must only be set if the item can actually be
/// represented as text (not binary data).
std::string text;

/// The MIME type of this resource, if known.
std::optional<std::string> mimeType;
};

llvm::json::Value toJSON(const ResourceContents &);
bool fromJSON(const llvm::json::Value &, ResourceContents &, llvm::json::Path);

/// The server's response to a resources/read request from the client.
struct ResourceResult {
std::vector<ResourceContents> contents;
};

llvm::json::Value toJSON(const ResourceResult &);
bool fromJSON(const llvm::json::Value &, ResourceResult &, llvm::json::Path);

/// Text provided to or from an LLM.
struct TextContent {
/// The text content of the message.
Expand Down
89 changes: 85 additions & 4 deletions lldb/source/Plugins/Protocol/MCP/ProtocolServerMCP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,29 @@ ProtocolServerMCP::ProtocolServerMCP() : ProtocolServer() {
AddRequestHandler("initialize",
std::bind(&ProtocolServerMCP::InitializeHandler, this,
std::placeholders::_1));

AddRequestHandler("tools/list",
std::bind(&ProtocolServerMCP::ToolsListHandler, this,
std::placeholders::_1));
AddRequestHandler("tools/call",
std::bind(&ProtocolServerMCP::ToolsCallHandler, this,
std::placeholders::_1));

AddRequestHandler("resources/list",
std::bind(&ProtocolServerMCP::ResourcesListHandler, this,
std::placeholders::_1));
AddRequestHandler("resources/read",
std::bind(&ProtocolServerMCP::ResourcesReadHandler, this,
std::placeholders::_1));
AddNotificationHandler(
"notifications/initialized", [](const protocol::Notification &) {
LLDB_LOG(GetLog(LLDBLog::Host), "MCP initialization complete");
});

AddTool(
std::make_unique<CommandTool>("lldb_command", "Run an lldb command."));
AddTool(std::make_unique<DebuggerListTool>(
"lldb_debugger_list", "List debugger instances with their debugger_id."));

AddResourceProvider(std::make_unique<DebuggerResourceProvider>());
}

ProtocolServerMCP::~ProtocolServerMCP() { llvm::consumeError(Stop()); }
Expand Down Expand Up @@ -75,7 +84,7 @@ ProtocolServerMCP::Handle(protocol::Request request) {
}

return make_error<MCPError>(
llvm::formatv("no handler for request: {0}", request.method).str(), 1);
llvm::formatv("no handler for request: {0}", request.method).str());
}

void ProtocolServerMCP::Handle(protocol::Notification notification) {
Expand Down Expand Up @@ -216,7 +225,7 @@ ProtocolServerMCP::HandleData(llvm::StringRef data) {
response.takeError(),
[&](const MCPError &err) { protocol_error = err.toProtcolError(); },
[&](const llvm::ErrorInfoBase &err) {
protocol_error.error.code = -1;
protocol_error.error.code = MCPError::kInternalError;
protocol_error.error.message = err.message();
});
protocol_error.id = request->id;
Expand Down Expand Up @@ -244,6 +253,9 @@ ProtocolServerMCP::HandleData(llvm::StringRef data) {
protocol::Capabilities ProtocolServerMCP::GetCapabilities() {
protocol::Capabilities capabilities;
capabilities.tools.listChanged = true;
// FIXME: Support sending notifications when a debugger/target are
// added/removed.
capabilities.resources.listChanged = false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we support sending notifications when a debugger/target are added/removed? Otherwise the client could get out of sync with the state of lldb.

Maybe as a FIXME/TODO if we can't easily do that now.

return capabilities;
}

Expand All @@ -255,6 +267,15 @@ void ProtocolServerMCP::AddTool(std::unique_ptr<Tool> tool) {
m_tools[tool->GetName()] = std::move(tool);
}

void ProtocolServerMCP::AddResourceProvider(
std::unique_ptr<ResourceProvider> resource_provider) {
std::lock_guard<std::mutex> guard(m_server_mutex);

if (!resource_provider)
return;
m_resource_providers.push_back(std::move(resource_provider));
}

void ProtocolServerMCP::AddRequestHandler(llvm::StringRef method,
RequestHandler handler) {
std::lock_guard<std::mutex> guard(m_server_mutex);
Expand Down Expand Up @@ -327,3 +348,63 @@ ProtocolServerMCP::ToolsCallHandler(const protocol::Request &request) {

return response;
}

llvm::Expected<protocol::Response>
ProtocolServerMCP::ResourcesListHandler(const protocol::Request &request) {
protocol::Response response;

llvm::json::Array resources;

std::lock_guard<std::mutex> guard(m_server_mutex);
for (std::unique_ptr<ResourceProvider> &resource_provider_up :
m_resource_providers) {
for (const protocol::Resource &resource :
resource_provider_up->GetResources())
resources.push_back(resource);
}
response.result.emplace(
llvm::json::Object{{"resources", std::move(resources)}});

return response;
}

llvm::Expected<protocol::Response>
ProtocolServerMCP::ResourcesReadHandler(const protocol::Request &request) {
protocol::Response response;

if (!request.params)
return llvm::createStringError("no resource parameters");

const json::Object *param_obj = request.params->getAsObject();
if (!param_obj)
return llvm::createStringError("no resource parameters");

const json::Value *uri = param_obj->get("uri");
if (!uri)
return llvm::createStringError("no resource uri");

llvm::StringRef uri_str = uri->getAsString().value_or("");
if (uri_str.empty())
return llvm::createStringError("no resource uri");

std::lock_guard<std::mutex> guard(m_server_mutex);
for (std::unique_ptr<ResourceProvider> &resource_provider_up :
m_resource_providers) {
llvm::Expected<protocol::ResourceResult> result =
resource_provider_up->ReadResource(uri_str);
if (result.errorIsA<UnsupportedURI>()) {
llvm::consumeError(result.takeError());
continue;
}
if (!result)
return result.takeError();

protocol::Response response;
response.result.emplace(std::move(*result));
return response;
}

return make_error<MCPError>(
llvm::formatv("no resource handler for uri: {0}", uri_str).str(),
MCPError::kResourceNotFound);
}
Loading
Loading