16#include "llvm/ADT/SmallString.h"
17#include "llvm/Support/ErrorExtras.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/JSON.h"
20#include "llvm/Support/Signals.h"
27 if (!m_filename.empty())
28 sys::RemoveFileOnSignal(m_filename);
34 *
this = std::move(other);
58 json::ObjectMapper O(V, P);
63 std::string buf = formatv(
"{0}",
toJSON(info)).str();
64 size_t num_bytes = buf.size();
66 FileSpec user_lldb_dir = HostInfo::GetUserLLDBDir();
70 return error.takeError();
73 formatv(
"lldb-mcp-{0}.json", getpid()).str());
78 Expected<lldb::FileUP> file =
81 return file.takeError();
82 if (llvm::Error
error = (*file)->Write(buf.data(), num_bytes).takeError())
88 namespace path = llvm::sys::path;
89 FileSpec user_lldb_dir = HostInfo::GetUserLLDBDir();
92 vfs::directory_iterator it = fs.
DirBegin(user_lldb_dir, EC);
93 vfs::directory_iterator end;
94 std::vector<ServerInfo> infos;
95 for (; it != end && !EC; it.increment(EC)) {
97 auto path = entry.path();
98 auto name = path::filename(path);
99 if (!name.starts_with(
"lldb-mcp-") || !name.ends_with(
".json"))
103 auto info = json::parse<ServerInfo>(toStringRef(buffer->GetData()));
105 return info.takeError();
107 infos.emplace_back(std::move(*info));
120 m_tools[tool->GetName()] = std::move(tool);
124 std::unique_ptr<ResourceProvider> resource_provider) {
125 if (!resource_provider)
142 binder_up->Bind<
void>(
"notifications/initialized",
143 [
this]() {
Log(
"MCP initialization complete"); });
150 binder->OnDisconnect([
this, transport_ptr]() {
152 "Client not found in m_instances");
155 binder->OnError([
this](llvm::Error err) {
156 Logv(
"Transport error: {0}", llvm::toString(std::move(err)));
159 auto handle =
transport->RegisterMessageHandler(loop, *binder);
161 return handle.takeError();
165 return llvm::Error::success();
168Expected<InitializeResult>
180 for (
const auto &tool :
m_tools)
181 result.
tools.emplace_back(tool.second->GetDefinition());
186llvm::Expected<CallToolResult>
188 llvm::StringRef tool_name = params.
name;
189 if (tool_name.empty())
190 return llvm::createStringError(
"no tool name");
192 auto it =
m_tools.find(tool_name);
194 return llvm::createStringErrorV(
"no tool \"{0}\"", tool_name);
200 llvm::Expected<CallToolResult> text_result = it->second->Call(tool_args);
202 return text_result.takeError();
209 for (std::unique_ptr<ResourceProvider> &resource_provider_up :
211 for (
const Resource &resource : resource_provider_up->GetResources())
217Expected<ReadResourceResult>
219 StringRef uri_str = params.
uri;
223 for (std::unique_ptr<ResourceProvider> &resource_provider_up :
225 Expected<ReadResourceResult> result =
226 resource_provider_up->ReadResource(uri_str);
228 consumeError(result.takeError());
232 return result.takeError();
237 return make_error<MCPError>(
238 formatv(
"no resource handler for uri: {0}", uri_str).str(),
static llvm::raw_ostream & error(Stream &strm)
static llvm::Error createStringError(const char *format, Args &&...args)
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
llvm::vfs::directory_iterator DirBegin(const FileSpec &file_spec, std::error_code &ec)
Get a directory iterator.
static FileSystem & Instance()
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
static constexpr int64_t kResourceNotFound
A handle that tracks the server info on disk and cleans up the disk record once it is no longer refer...
llvm::SmallString< 128 > m_filename
void Remove()
Remove the file on disk, if one is tracked.
ServerInfoHandle & operator=(ServerInfoHandle &&other) noexcept
ServerInfoHandle(llvm::StringRef filename="")
const std::string m_version
void AddTool(std::unique_ptr< Tool > tool)
void AddResourceProvider(std::unique_ptr< ResourceProvider > resource_provider)
llvm::StringMap< std::unique_ptr< Tool > > m_tools
MCPBinderUP Bind(MCPTransport &)
std::vector< std::unique_ptr< ResourceProvider > > m_resource_providers
llvm::Expected< ReadResourceResult > ResourcesReadHandler(const ReadResourceParams &)
LogCallback m_log_callback
Server(std::string name, std::string version, LogCallback log_callback={})
llvm::Expected< ListToolsResult > ToolsListHandler()
void Log(llvm::StringRef message)
llvm::Expected< InitializeResult > InitializeHandler(const InitializeParams &)
llvm::Expected< CallToolResult > ToolsCallHandler(const CallToolParams &)
llvm::Error Accept(lldb_private::MainLoop &, MCPTransportUP)
std::unique_ptr< lldb_protocol::mcp::MCPTransport > MCPTransportUP
llvm::Expected< ListResourcesResult > ResourcesListHandler()
auto Logv(const char *Fmt, Ts &&...Vals)
std::map< MCPTransport *, Client > m_instances
ServerCapabilities GetCapabilities()
A class that represents a running process on the host machine.
std::unique_ptr< MCPBinder > MCPBinderUP
std::variant< std::monostate, llvm::json::Value > ToolArguments
lldb_private::transport::JSONTransport< ProtocolDescriptor > MCPTransport
Generic transport that uses the MCP protocol.
llvm::json::Value toJSON(const Request &)
llvm::unique_function< void(llvm::StringRef message)> LogCallback
Generic logging callback, to allow the MCP server / client / transport layer to be independent of the...
static llvm::StringLiteral kProtocolVersion
bool fromJSON(const llvm::json::Value &, Request &, llvm::json::Path)
std::string name
Intended for programmatic or logical use, but used as a display name in past specs or fallback (if ti...
After receiving an initialize request from the client, the server sends this response.
std::string protocolVersion
The version of the Model Context Protocol that the server wants to use.
ServerCapabilities capabilities
Implementation serverInfo
The server’s response to a resources/list request from the client.
std::vector< Resource > resources
Sent from the client to the server, to read a specific resource URI.
std::string uri
The URI of the resource to read.
The server's response to a resources/read request from the client.
A known resource that the server is capable of reading.
Capabilities that a server may support.
bool supportsResourcesList
bool supportsResourcesSubscribe
Information about this instance of lldb's MCP server for lldb-mcp to use to coordinate connecting an ...
static llvm::Expected< std::vector< ServerInfo > > Load()
Loads any server info saved in ~/.lldb.
std::string connection_uri
static llvm::Expected< ServerInfoHandle > Write(const ServerInfo &)
Writes the server info into a unique file in ~/.lldb.