external_client.cpp¶
src/mcp/external_client.cpp
@file external_client.cpp @brief ExternalMCPClient implementation.
Owners: @tvanfossen
build_request
std::string entropic::ExternalMCPClient::build_request(const std::string &method, const std::string ¶ms="{}")Build a JSON-RPC 2.0 request envelope.
src/mcp/external_client.cpp:310
Source · 6 lines
std::string ExternalMCPClient::build_request(
const std::string& method,
const std::string& params) {
int ignored = 0;
return build_request_id(method, params, ignored);
}Activity · 2 steps
Requirements
build_request_id
std::string entropic::ExternalMCPClient::build_request_id(const std::string &method, const std::string ¶ms, int &id)
Build a request and report the id it carries (gh#158).
src/mcp/external_client.cpp:328
Source · 17 lines
std::string ExternalMCPClient::build_request_id(
const std::string& method,
const std::string& params,
int& id) {
id = next_id_.fetch_add(1, std::memory_order_relaxed);
nlohmann::json req;
req["jsonrpc"] = "2.0";
req["id"] = id;
req["method"] = method;
try {
req["params"] = nlohmann::json::parse(params);
} catch (...) {
req["params"] = nlohmann::json::object();
}
return req.dump();
}Activity · 7 steps
Requirements
build_response
std::string entropic::ExternalMCPClient::build_response(const std::string &result_text, bool is_error=false)
Build ServerResponse JSON with empty directives (security).
src/mcp/external_client.cpp:525
Source · 14 lines
std::string ExternalMCPClient::build_response(
const std::string& result_text,
bool is_error) {
nlohmann::json resp;
resp["result"] = result_text;
// SECURITY: External servers CANNOT inject directives.
// Directives array is always empty for external tool results.
resp["directives"] = nlohmann::json::array();
if (is_error) {
resp["is_error"] = true;
}
return resp.dump();
}Activity · 6 steps
Requirements
connect
bool entropic::ExternalMCPClient::connect()
Connect: open transport + MCP initialize + tools/list.
src/mcp/external_client.cpp:45
Called by SCENARIO, TEST_CASE, TEST_CASE, attempt_reconnect, connect_and_register_external
Calls close, open, query_tools, send_initialize
Source · 21 lines
bool ExternalMCPClient::connect() {
if (!transport_->open()) {
logger->error("Transport open failed for '{}'", name_);
return false;
}
if (!send_initialize()) {
logger->error("MCP initialize failed for '{}'", name_);
transport_->close();
return false;
}
if (!query_tools()) {
logger->warn("tools/list failed for '{}' — "
"connected with 0 tools", name_);
}
logger->info("Connected to '{}': {} tools",
name_, cached_tool_names_.size());
return true;
}Activity · 11 steps
Requirements
empty_response_envelope
std::string entropic::ExternalMCPClient::empty_response_envelope(const std::string &tool_name) const
Build ServerResponse JSON with empty directives.
src/mcp/external_client.cpp:112
Source · 13 lines
std::string ExternalMCPClient::empty_response_envelope(
const std::string& tool_name) const {
if (transport_->is_interrupted()) {
return build_response(
"Error: tool '" + name_ + "." + tool_name +
"' was not attempted — the transport is interrupted. "
"The interrupt is released at the start of the next run.",
true);
}
return build_response(
"Error: tool '" + name_ + "." + tool_name +
"' timed out or the transport failed.", true);
}Activity · 3 steps
Requirements
execute
std::string entropic::ExternalMCPClient::execute(const std::string &tool_name, const std::string &args_json)
Execute a tool call via the external server.
src/mcp/external_client.cpp:140
Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, route_external_call
Calls build_request_id, build_response, extract_tool_result, is_connected, response_problem, send_request
Source · 40 lines
std::string ExternalMCPClient::execute(
const std::string& tool_name,
const std::string& args_json) {
if (!transport_->is_connected()) {
// gh#150: the leading "Error:" is load-bearing, not decoration.
// classify_tool_result routes on the TEXT via looks_like_tool_error,
// which matches a leading "error"/"[error]"/JSON-error shape. This
// message used to start with "Server '...'", so a failed call was
// logged status=ok and counted as a success — the reporting
// consumer watched every external call fail while the logs said
// everything was fine.
return build_response(
"Error: server '" + name_ + "' is disconnected. "
"Tool '" + name_ + "." + tool_name + "' unavailable.",
true);
}
nlohmann::json params;
params["name"] = tool_name;
try {
params["arguments"] = nlohmann::json::parse(args_json);
} catch (...) {
params["arguments"] = nlohmann::json::object();
}
int request_id = 0;
auto request = build_request_id(
"tools/call", params.dump(), request_id);
auto response = transport_->send_request(
request, DEFAULT_TIMEOUT_MS);
auto problem = response_problem(tool_name, response, request_id);
if (!problem.empty()) {
return problem;
}
auto result_text = extract_tool_result(response);
return build_response(result_text);
}Activity · 13 steps
Requirements
is_connected
bool entropic::ExternalMCPClient::is_connected() const
Check connection state.
src/mcp/external_client.cpp:296
Called by TEST_CASE, TEST_CASE, append_external_tools, check_server, external_tools_without_readonly_hint, route_external_call, watch
Calls is_connected
Source · 3 lines
bool ExternalMCPClient::is_connected() const {
return transport_->is_connected();
}Activity · 1 steps
Flows
list_tools
std::string entropic::ExternalMCPClient::list_tools() const
List tools as JSON array string (cached).
src/mcp/external_client.cpp:89
Called by TEST_CASE, TEST_CASE, append_external_tools, external_tools_without_readonly_hint
Calls none
Source · 4 lines
std::string ExternalMCPClient::list_tools() const {
std::lock_guard<std::mutex> lock(tools_mutex_);
return cached_tools_json_;
}Activity · 2 steps
Requirements
mismatched_response_envelope
std::string entropic::ExternalMCPClient::mismatched_response_envelope(const std::string &tool_name, int expected_id) const
Failure envelope for a response that answered another request (gh#158).
src/mcp/external_client.cpp:230
Source · 12 lines
std::string ExternalMCPClient::mismatched_response_envelope(
const std::string& tool_name, int expected_id) const {
logger->error("Server '{}' answered request {} with a response carrying "
"a different id; discarding it rather than returning "
"another request's result for tool '{}'",
name_, expected_id, tool_name);
return build_response(
"Error: tool '" + name_ + "." + tool_name +
"' got a response that did not answer it (JSON-RPC id mismatch). "
"The transport had a stale reply queued from an abandoned request; "
"it has been discarded. Retry the call.", true);
}Activity · 2 steps
Requirements
query_tools
bool entropic::ExternalMCPClient::query_tools()
Query tools/list and update cache.
src/mcp/external_client.cpp:440
Called by connect, refresh_tools
Calls build_request_id, response_matches, send_request
Source · 32 lines
bool ExternalMCPClient::query_tools() {
int request_id = 0;
auto request = build_request_id("tools/list", "{}", request_id);
auto response = transport_->send_request(
request, init_timeout_ms_);
if (response.empty() || !response_matches(response, request_id)) {
return false;
}
try {
auto j = nlohmann::json::parse(response);
auto tools = j.at("result").at("tools");
// Prefix tool names with server name
std::vector<std::string> names;
for (auto& tool : tools) {
std::string orig = tool["name"].get<std::string>();
tool["name"] = name_ + "." + orig;
names.push_back(tool["name"].get<std::string>());
}
std::lock_guard<std::mutex> lock(tools_mutex_);
cached_tools_json_ = tools.dump();
cached_tool_names_ = std::move(names);
return true;
} catch (const nlohmann::json::exception& e) {
logger->error("Failed to parse tools/list from '{}': {}",
name_, e.what());
return false;
}
}Activity · 6 steps
Requirements
refresh_tools
std::pair< std::vector< std::string >, std::vector< std::string > > entropic::ExternalMCPClient::refresh_tools()
Re-query tools/list and diff against cache.
src/mcp/external_client.cpp:271
Source · 18 lines
ExternalMCPClient::refresh_tools() {
auto snapshot = [this] {
std::lock_guard<std::mutex> lock(tools_mutex_);
return std::set<std::string>(cached_tool_names_.begin(),
cached_tool_names_.end());
};
std::set<std::string> old_names = snapshot();
query_tools();
std::set<std::string> new_names = snapshot();
auto added = names_diff(new_names, old_names);
auto removed = names_diff(old_names, new_names);
logger->info("Server '{}' tools refreshed: +{} -{}",
name_, added.size(), removed.size());
return {added, removed};
}Activity · 8 steps
Requirements
response_matches
bool entropic::ExternalMCPClient::response_matches(const std::string &response_json, int expected_id)
Whether a response belongs to the request that asked (gh#158).
src/mcp/external_client.cpp:356
Source · 19 lines
bool ExternalMCPClient::response_matches(
const std::string& response_json, int expected_id) {
try {
auto j = nlohmann::json::parse(response_json);
// A string id is accepted when it spells the same number. We always
// SEND an integer and JSON-RPC 2.0 requires the response to echo the
// same value, but stringifying it is the one deviation common enough
// in the wild to be worth tolerating — it is unambiguous, so
// rejecting it would break working servers for no safety gain.
if (j.value("id", nlohmann::json()).is_string()) {
return j["id"].get<std::string>()
== std::to_string(expected_id);
}
return j.contains("id") && j["id"].is_number_integer()
&& j["id"].get<int>() == expected_id;
} catch (const nlohmann::json::exception&) {
return false;
}
}Activity · 1 steps
Requirements
response_problem
std::string entropic::ExternalMCPClient::response_problem(const std::string &tool_name, const std::string &response, int expected_id) const
The failure envelope a response warrants, or empty (gh#158).
src/mcp/external_client.cpp:199
Called by execute
Calls empty_response_envelope, mismatched_response_envelope, response_matches
Source · 12 lines
std::string ExternalMCPClient::response_problem(
const std::string& tool_name,
const std::string& response,
int expected_id) const {
if (response.empty()) {
return empty_response_envelope(tool_name);
}
if (!response_matches(response, expected_id)) {
return mismatched_response_envelope(tool_name, expected_id);
}
return {};
}Activity · 5 steps
Requirements
send_initialize
bool entropic::ExternalMCPClient::send_initialize()
Send MCP initialize handshake.
src/mcp/external_client.cpp:408
Called by connect
Calls build_request_id, response_matches, send_request, validate_init_response
Source · 18 lines
bool ExternalMCPClient::send_initialize() {
nlohmann::json params;
params["protocolVersion"] = "2024-11-05";
params["capabilities"] = nlohmann::json::object();
params["clientInfo"]["name"] = "entropic";
params["clientInfo"]["version"] = "1.8.7";
int request_id = 0;
auto request = build_request_id(
"initialize", params.dump(), request_id);
auto response = transport_->send_request(
request, init_timeout_ms_);
if (response.empty() || !response_matches(response, request_id)) {
return false;
}
return validate_init_response(response);
}Activity · 11 steps
Requirements
set_init_timeout_ms
void entropic::ExternalMCPClient::set_init_timeout_ms(uint32_t ms)
Bound for bringing the server up: initialize + tools/list (gh#175, v2.14.0).
src/mcp/external_client.cpp:546
Source · 3 lines
void ExternalMCPClient::set_init_timeout_ms(uint32_t ms) {
if (ms > 0) { init_timeout_ms_ = ms; }
}