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 &params="{}")

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
lines 313–313int ignored = 0;lines 314–314return build_request_id(method, params, ignored);

Requirements

REQ-MCP-025

build_request_id

std::string entropic::ExternalMCPClient::build_request_id(const std::string &method, const std::string &params, 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
lines 333–333id = next_id_.fetch_add(1, std::memory_order_relaxed);lines 334–334nlohmann::json req;lines 335–335req["jsonrpc"] = "2.0";lines 336–336req["id"] = id;lines 337–337req["method"] = method;lines 338–342try { req["params"] = nlohmann::json::parse(params); } catch (...) { req["params"] = nlohmann::json::object(); }lines 343–343return req.dump();

Requirements

REQ-MCP-025 REQ-MCP-026

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
lines 529–529nlohmann::json resp;lines 530–530resp["result"] = result_text;lines 533–533resp["directives"] = nlohmann::json::array();lines 534–534◇ if (is_error)lines 535–535resp["is_error"] = true;lines 537–537return resp.dump();

Requirements

REQ-MCP-002 REQ-MCP-025

connect

bool entropic::ExternalMCPClient::connect()

Connect: open transport + MCP initialize + tools/list.

src/mcp/external_client.cpp:45

Show on the map →

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
lines 46–46◇ if (!transport_->open())lines 47–47logger->error("Transport open failed for '{}'", name_);lines 48–48return false;lines 51–51◇ if (!send_initialize())lines 52–52logger->error("MCP initialize failed for '{}'", name_);lines 53–53transport_->close();lines 54–54return false;lines 57–57◇ if (!query_tools())lines 58–59logger->warn("tools/list failed for '{}' — " "connected with 0 tools", name_);lines 62–63logger->info("Connected to '{}': {} tools", name_, cached_tool_names_.size());lines 64–64return true;

Requirements

REQ-MCP-025

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
lines 114–114◇ if (transport_->is_interrupted())lines 115–119return 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);lines 121–123return build_response( "Error: tool '" + name_ + "." + tool_name + "' timed out or the transport failed.", true);

Requirements

REQ-MCP-025

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

Show on the map →

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
lines 144–144◇ if (!transport_->is_connected())lines 152–155return build_response( "Error: server '" + name_ + "' is disconnected. " "Tool '" + name_ + "." + tool_name + "' unavailable.", true);lines 158–158nlohmann::json params;lines 159–159params["name"] = tool_name;lines 160–164try { params["arguments"] = nlohmann::json::parse(args_json); } catch (...) { params["arguments"] = nlohmann::json::object(); }lines 166–166int request_id = 0;lines 167–168auto request = build_request_id( "tools/call", params.dump(), request_id);lines 169–170auto response = transport_->send_request( request, DEFAULT_TIMEOUT_MS);lines 172–172auto problem = response_problem(tool_name, response, request_id);lines 173–173◇ if (!problem.empty())lines 174–174return problem;lines 177–177auto result_text = extract_tool_result(response);lines 178–178return build_response(result_text);

Requirements

REQ-MCP-002 REQ-MCP-025 REQ-MCP-026

is_connected

bool entropic::ExternalMCPClient::is_connected() const

Check connection state.

src/mcp/external_client.cpp:296

Source · 3 lines
bool ExternalMCPClient::is_connected() const {
    return transport_->is_connected();
}
Activity · 1 steps
lines 297–297return transport_->is_connected();

Flows

list_tools

std::string entropic::ExternalMCPClient::list_tools() const

List tools as JSON array string (cached).

src/mcp/external_client.cpp:89

Source · 4 lines
std::string ExternalMCPClient::list_tools() const {
    std::lock_guard<std::mutex> lock(tools_mutex_);
    return cached_tools_json_;
}
Activity · 2 steps
lines 90–90std::lock_guard<std::mutex> lock(tools_mutex_);lines 91–91return cached_tools_json_;

Requirements

REQ-MCP-007 REQ-MCP-025

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
lines 232–235logger->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);lines 236–240return 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);

Requirements

REQ-MCP-025 REQ-MCP-026

query_tools

bool entropic::ExternalMCPClient::query_tools()

Query tools/list and update cache.

src/mcp/external_client.cpp:440

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
lines 441–441int request_id = 0;lines 442–442auto request = build_request_id("tools/list", "{}", request_id);lines 443–444auto response = transport_->send_request( request, init_timeout_ms_);lines 446–446◇ if (response.empty() || !response_matches(response, request_id))lines 447–447return false;lines 450–470try { 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; }

Requirements

REQ-MCP-007 REQ-MCP-025 REQ-MCP-026

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

Show on the map →

Called by TEST_CASE, on_reconnect_success

Calls names_diff, query_tools

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
lines 272–276auto snapshot = [this] { std::lock_guard<std::mutex> lock(tools_mutex_); return std::set<std::string>(cached_tool_names_.begin(), cached_tool_names_.end()); };lines 278–278std::set<std::string> old_names = snapshot();lines 279–279query_tools();lines 280–280std::set<std::string> new_names = snapshot();lines 282–282auto added = names_diff(new_names, old_names);lines 283–283auto removed = names_diff(old_names, new_names);lines 285–286logger->info("Server '{}' tools refreshed: +{} -{}", name_, added.size(), removed.size());lines 287–287return {added, removed};

Requirements

REQ-MCP-025

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
lines 358–373try { 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; }

Requirements

REQ-MCP-025 REQ-MCP-026

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

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
lines 203–203◇ if (response.empty())lines 204–204return empty_response_envelope(tool_name);lines 206–206◇ if (!response_matches(response, expected_id))lines 207–207return mismatched_response_envelope(tool_name, expected_id);lines 209–209return {};

Requirements

REQ-MCP-025 REQ-MCP-026

send_initialize

bool entropic::ExternalMCPClient::send_initialize()

Send MCP initialize handshake.

src/mcp/external_client.cpp:408

Show on the map →

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
lines 409–409nlohmann::json params;lines 410–410params["protocolVersion"] = "2024-11-05";lines 411–411params["capabilities"] = nlohmann::json::object();lines 412–412params["clientInfo"]["name"] = "entropic";lines 413–413params["clientInfo"]["version"] = "1.8.7";lines 415–415int request_id = 0;lines 416–417auto request = build_request_id( "initialize", params.dump(), request_id);lines 418–419auto response = transport_->send_request( request, init_timeout_ms_);lines 421–421◇ if (response.empty() || !response_matches(response, request_id))lines 422–422return false;lines 424–424return validate_init_response(response);

Requirements

REQ-MCP-025 REQ-MCP-026

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

Show on the map →

Called by create_external_client

Calls none

Source · 3 lines
void ExternalMCPClient::set_init_timeout_ms(uint32_t ms) {
    if (ms > 0) { init_timeout_ms_ = ms; }
}
Activity · 2 steps
lines 547–547◇ if (ms > 0)lines 547–547init_timeout_ms_ = ms;

Requirements

REQ-MCP-025