NeoGraph 0.16.0
A C++20 Graph Agent Engine Library — LangGraph for C++
Loading...
Searching...
No Matches
neograph::mcp::MCPClient Class Reference

Client for connecting to MCP (Model Context Protocol) servers. More...

#include <client.h>

Public Member Functions

json call_tool (const std::string &name, const json &arguments)
 Call a tool directly by name.
 
asio::awaitable< json > call_tool_async (const std::string &name, const json &arguments)
 Async variant of call_tool() — awaits the tools/call RPC without blocking and returns the raw result.
 
asio::awaitable< CallToolResult > call_tool_result_async (const std::string &name, const json &arguments, std::chrono::steady_clock::time_point deadline, std::shared_ptr< graph::CancelToken > cancel_token)
 Bounded variant: the deadline (absolute, steady clock) and cancel token stop waiting for this call only, as for rpc_call_async().
 
std::vector< ToolDefinition > get_tool_definitions ()
 Fetch all pages while preserving the complete MCP definitions.
 
std::vector< std::unique_ptr< Tool > > get_tools ()
 Discover tools from the MCP server.
 
bool initialize (const std::string &client_name, std::chrono::steady_clock::time_point deadline, std::shared_ptr< graph::CancelToken > cancel_token)
 Bounded handshake: the deadline (absolute, steady clock) and cancel token stop waiting for it (MCPTransportError timeout or cancelled), and the client stays uninitialized.
 
bool initialize (const std::string &client_name="neograph")
 Initialize the connection and perform the MCP handshake.
 
asio::awaitable< bool > initialize_async (const std::string &client_name="neograph")
 Async handshake + initialized notification for either transport.
 
ListToolsPage list_tools (const std::optional< std::string > &cursor=std::nullopt)
 Fetch one tools/list page. The cursor is opaque and is echoed verbatim.
 
 MCPClient (const std::string &server_url)
 Construct an HTTP-mode (Streamable HTTP) MCP client.
 
 MCPClient (std::vector< std::string > argv)
 Construct a stdio-mode MCP client by spawning a subprocess.
 
 MCPClient (StdioClientConfig config)
 Hardened local launch with validated replacement environment, cwd, bounded stderr capture, startup/request deadlines, and process-tree ownership.
 
asio::awaitable< json > rpc_call_async (const std::string &method, const json &params=json::object(), std::chrono::steady_clock::time_point deadline=std::chrono::steady_clock::time_point::max(), std::shared_ptr< graph::CancelToken > cancel_token={})
 Send a transport-independent JSON-RPC request asynchronously.
 
void set_tool_list_changed_handler (std::function< void()> handler)
 Called when the server sends notifications/tools/list_changed: read get_tool_definitions() or get_tools() again for the new catalogue.
 
void shutdown () noexcept
 Permanently revoke this client and all tools retaining its session.
 

Detailed Description

Client for connecting to MCP (Model Context Protocol) servers.

Handles the initialization handshake, tool discovery, and tool invocation. Both HTTP and stdio transports are available; pick via the appropriate constructor.

// HTTP: the server's MCP endpoint URL, as given
MCPClient http_client("http://localhost:8000/mcp");
http_client.initialize("my-agent");
auto tools = http_client.get_tools();
// stdio — spawn a subprocess
MCPClient stdio_client({"python", "server.py"});
stdio_client.initialize("my-agent");
auto tools2 = stdio_client.get_tools();
Client for connecting to MCP (Model Context Protocol) servers.
Definition client.h:121
bool initialize(const std::string &client_name="neograph")
Initialize the connection and perform the MCP handshake.

Definition at line 121 of file client.h.

Constructor & Destructor Documentation

◆ MCPClient() [1/2]

neograph::mcp::MCPClient::MCPClient ( const std::string &  server_url)
explicit

Construct an HTTP-mode (Streamable HTTP) MCP client.

Parameters
server_urlThe server's MCP endpoint URL, used as given, path and query included (e.g., "http://localhost:8000/mcp"). Nothing is appended to it.

The client answers a server's ping and refuses other server requests with -32601 (it declares no client capability), reads JSON and Server-Sent Event responses, resumes an event stream the server closed early (GET with Last-Event-ID), opens the optional GET event stream for server messages between calls once its session is initialized, starts a new session when the server answers 404 for its session and sends the request again once, and ends its session with DELETE on shutdown() or when the last reference goes. A 307 or 308 answer is followed, with the request's method, body and headers, up to five times and only on the endpoint URL's origin (scheme, host and port); any other redirect is an error with its HTTP status.

◆ MCPClient() [2/2]

neograph::mcp::MCPClient::MCPClient ( std::vector< std::string >  argv)
explicit

Construct a stdio-mode MCP client by spawning a subprocess.

Parameters
argvCommand + arguments (e.g., {"python", "server.py"}). argv[0] is resolved via PATH before fork. Pipe/fork failures throw during construction; exec failure surfaces on the first RPC.

The subprocess tree is terminated when the last reference to the underlying session is dropped, or when shutdown() is called. This legacy overload inherits environment, cwd, and stderr.

Member Function Documentation

◆ call_tool()

json neograph::mcp::MCPClient::call_tool ( const std::string &  name,
const json &  arguments 
)

Call a tool directly by name.

Parameters
nameTool name on the server.
argumentsJSON object of tool arguments.
Returns
Raw MCP tools/call result object from the server.

◆ get_tools()

std::vector< std::unique_ptr< Tool > > neograph::mcp::MCPClient::get_tools ( )

Discover tools from the MCP server.

Returns
Vector of Tool unique_ptrs (MCPTool instances).

◆ initialize() [1/2]

bool neograph::mcp::MCPClient::initialize ( const std::string &  client_name,
std::chrono::steady_clock::time_point  deadline,
std::shared_ptr< graph::CancelToken >  cancel_token 
)

Bounded handshake: the deadline (absolute, steady clock) and cancel token stop waiting for it (MCPTransportError timeout or cancelled), and the client stays uninitialized.

MCP never cancels initialize on the wire, so the server is not told: a stdio server may then refuse a second handshake, and a hardened stdio session ends.

◆ initialize() [2/2]

bool neograph::mcp::MCPClient::initialize ( const std::string &  client_name = "neograph")

Initialize the connection and perform the MCP handshake.

Parameters
client_nameClient identifier sent during handshake (default: "neograph").
Returns
True after initialization. Protocol and transport failures throw.

◆ rpc_call_async()

asio::awaitable< json > neograph::mcp::MCPClient::rpc_call_async ( const std::string &  method,
const json &  params = json::object(),
std::chrono::steady_clock::time_point  deadline = std::chrono::steady_clock::time_point::max(),
std::shared_ptr< graph::CancelToken >  cancel_token = {} 
)

Send a transport-independent JSON-RPC request asynchronously.

Both transports are coroutine-native. stdio owns its process and correlation reader; HTTP owns its headers and HTTP request lifecycle.

Parameters
methodJSON-RPC method name.
paramsMethod parameters.
deadlineAbsolute steady-clock deadline (unbounded by default).
cancel_tokenOptional cancellation token for this request.
Returns
The validated JSON-RPC result field.

◆ set_tool_list_changed_handler()

void neograph::mcp::MCPClient::set_tool_list_changed_handler ( std::function< void()>  handler)

Called when the server sends notifications/tools/list_changed: read get_tool_definitions() or get_tools() again for the new catalogue.

Until then outputSchema checks are skipped, as the cached schemas may be stale. The notification may come on a call's response stream, on stdio at any time, or over HTTP on the optional GET event stream the client opens for its session after initialize. The handler runs on the client's transport thread: return promptly and do not call this client from it. An empty handler stops the callbacks.

◆ shutdown()

void neograph::mcp::MCPClient::shutdown ( )
noexcept

Permanently revoke this client and all tools retaining its session.

Aborts and drains transport work and terminates the owned subprocess tree, independently of shared ownership. Repeated and concurrent calls are safe. A call from a transport callback cancels in place without self-joining; its current operation unwinds with MCPFailure::shutdown. Subsequent requests fail with MCPFailure::shutdown.


The documentation for this class was generated from the following file: