tool_executor.cpp

src/mcp/tool_executor.cpp

@file tool_executor.cpp @brief ToolExecutor implementation.

Owners: @tvanfossen

apply_pre_tool_modification

bool entropic::ToolExecutor::apply_pre_tool_modification(ToolCall &call, const char *modified)

Apply a PRE_TOOL_CALL hook's *modified_json to a call.

src/mcp/tool_executor.cpp:1204

Show on the map →

Called by fire_pre_tool_hook

Calls overwrite_call_arguments, pre_mod_refusal, sanitize_utf8

Source · 23 lines
bool ToolExecutor::apply_pre_tool_modification(ToolCall& call,
                                               const char* modified) {
    // A registered hook is a plugin .so — an external boundary in BOTH
    // directions (gh#3 / gh#111 / gh#132). Sanitize BEFORE the parse:
    // nlohmann rejects an ill-formed UTF-8 byte inside a string, so
    // sanitizing afterwards would refuse a payload that is merely dirty.
    const std::string sanitized = mcp::sanitize_utf8(modified);
    auto parsed = nlohmann::json::parse(sanitized, nullptr, false);
    std::string refusal = parsed.is_discarded()
        ? std::string{"payload is not valid JSON"}
        : pre_mod_refusal(parsed, call.name);
    if (!refusal.empty()) {
        logger->error(
            "[hook] PRE_TOOL_CALL modification REFUSED for '{}': {}. "
            "Dispatching the call with the model's own arguments. "
            "Payload: {}", call.name, refusal, sanitized);
        return false;
    }
    overwrite_call_arguments(call, parsed.at("args"));
    logger->info("[hook] PRE_TOOL_CALL rewrote args for '{}': {}",
                 call.name, call.arguments_json);
    return true;
}
Activity · 9 steps
lines 1210–1210const std::string sanitized = mcp::sanitize_utf8(modified);lines 1211–1211auto parsed = nlohmann::json::parse(sanitized, nullptr, false);lines 1212–1214std::string refusal = parsed.is_discarded() ? std::string{"payload is not valid JSON"} : pre_mod_refusal(parsed, call.name);lines 1215–1215◇ if (!refusal.empty())lines 1216–1219logger->error( "[hook] PRE_TOOL_CALL modification REFUSED for '{}': {}. " "Dispatching the call with the model's own arguments. " "Payload: {}", call.name, refusal, sanitized);lines 1220–1220return false;lines 1222–1222overwrite_call_arguments(call, parsed.at("args"));lines 1223–1224logger->info("[hook] PRE_TOOL_CALL rewrote args for '{}': {}", call.name, call.arguments_json);lines 1225–1225return true;

Requirements

REQ-MCP-017

apply_result_size_cap

void entropic::ToolExecutor::apply_result_size_cap(std::string &content) const

Truncate content in-place if it exceeds the byte cap.

src/mcp/tool_executor.cpp:1274

Source · 3 lines
void ToolExecutor::apply_result_size_cap(std::string& content) const {
    mcp::truncate_to_cap(content, loop_config_.max_tool_result_bytes);
}
Activity · 1 steps
lines 1275–1275mcp::truncate_to_cap(content, loop_config_.max_tool_result_bytes);

Requirements

REQ-MCP-019

build_complete_directive

static std::unique_ptr< Directive > entropic::build_complete_directive(const nlohmann::json &result_json)

Build a typed Directive from a directive-descriptor JSON.

src/mcp/tool_executor.cpp:1777

Show on the map →

Called by build_directive

Calls CompleteDirective

Source · 13 lines
static std::unique_ptr<Directive> build_complete_directive(
    const nlohmann::json& result_json) {
    auto cd = std::make_unique<CompleteDirective>(
        result_json.value("summary", ""));
    cd->coverage_gap = result_json.value("coverage_gap", false);
    cd->gap_description = result_json.value("gap_description", "");
    if (result_json.contains("suggested_files")
        && result_json["suggested_files"].is_array()) {
        cd->suggested_files =
            result_json["suggested_files"].get<std::vector<std::string>>();
    }
    return cd;
}
Activity · 6 steps
lines 1779–1780auto cd = std::make_unique<CompleteDirective>( result_json.value("summary", ""));lines 1781–1781cd->coverage_gap = result_json.value("coverage_gap", false);lines 1782–1782cd->gap_description = result_json.value("gap_description", "");lines 1783–1784◇ if (result_json.contains("suggested_files") && result_json["suggested_files"].is_array())lines 1785–1786cd->suggested_files = result_json["suggested_files"].get<std::vector<std::string>>();lines 1788–1788return cd;

Requirements

REQ-MCP-024

build_directive

static std::unique_ptr< Directive > entropic::build_directive(const nlohmann::json &d, const nlohmann::json &result_json)

Build a Directive from a parsed directive + result JSON.

src/mcp/tool_executor.cpp:1836

Show on the map →

Called by extract_and_process_directives

Calls DelegateDirective, PipelineDirective, StopProcessingDirective, build_complete_directive, extract_context_refs, extract_pipeline_stages

Source · 32 lines
static std::unique_ptr<Directive> build_directive(
    const nlohmann::json& d, const nlohmann::json& result_json) {
    auto type_str = d.value("type", "");
    std::unique_ptr<Directive> result;
    if (type_str == "stop_processing") {
        result = std::make_unique<StopProcessingDirective>();
    } else if (type_str == "delegate") {
        // gh#32 (v2.1.6): resume_delegation emits action=resume_delegation
        // with delegation_id but no target. The directive's target is
        // resolved later by the engine after loading the original
        // delegation's tier from storage.
        auto dl = std::make_unique<DelegateDirective>(
            result_json.value("target", ""),
            result_json.value("task", ""),
            result_json.value("max_turns", -1),
            result_json.value("delegation_id", ""));
        // gh#162 (v2.13.0): carry the lead's file references and the
        // resume-by-tier flag through to the engine.
        dl->context = extract_context_refs(result_json);
        dl->resume_by_target = result_json.value("resume_by_target", false);
        result = std::move(dl);
    } else if (type_str == "complete") {
        result = build_complete_directive(result_json);
    } else if (type_str == "pipeline") {
        auto pl = std::make_unique<PipelineDirective>(
            extract_pipeline_stages(result_json),
            result_json.value("task", ""));
        pl->context = extract_context_refs(result_json);  // gh#162
        result = std::move(pl);
    }
    return result;
}
Activity · 19 steps
lines 1838–1838auto type_str = d.value("type", "");lines 1839–1839std::unique_ptr<Directive> result;lines 1840–1840◇ if (type_str == "stop_processing")lines 1841–1841result = std::make_unique<StopProcessingDirective>();lines 1842–1842elselines 1842–1842◇ if (type_str == "delegate")lines 1847–1851auto dl = std::make_unique<DelegateDirective>( result_json.value("target", ""), result_json.value("task", ""), result_json.value("max_turns", -1), result_json.value("delegation_id", ""));lines 1854–1854dl->context = extract_context_refs(result_json);lines 1855–1855dl->resume_by_target = result_json.value("resume_by_target", false);lines 1856–1856result = std::move(dl);lines 1857–1857elselines 1857–1857◇ if (type_str == "complete")lines 1858–1858result = build_complete_directive(result_json);lines 1859–1859elselines 1859–1859◇ if (type_str == "pipeline")lines 1860–1862auto pl = std::make_unique<PipelineDirective>( extract_pipeline_stages(result_json), result_json.value("task", ""));lines 1863–1863pl->context = extract_context_refs(result_json);lines 1864–1864result = std::move(pl);lines 1866–1866return result;

Requirements

REQ-MCP-002 REQ-MCP-024

build_post_tool_json

std::string entropic::ToolExecutor::build_post_tool_json(const ToolCall &call, const std::string &raw_result, double elapsed_ms, const std::string &tier, int iteration, ToolResultKind kind)

Build enriched POST_TOOL_CALL hook context JSON.

src/mcp/tool_executor.cpp:1676

Source · 25 lines
std::string ToolExecutor::build_post_tool_json(
    const ToolCall& call,
    const std::string& raw_result,
    double elapsed_ms,
    const std::string& tier,
    int iteration,
    ToolResultKind kind) {
    nlohmann::json ctx;
    ctx["tool_name"] = call.name;
    ctx["args"] = nlohmann::json::parse(serialize_args(call));
    ctx["elapsed_ms"] = elapsed_ms;
    ctx["tier"] = tier.empty() ? std::string{"lead"} : tier;
    ctx["iteration"] = iteration;
    ctx["result_kind"] = result_kind_to_string(kind);
    try {
        auto sr = nlohmann::json::parse(raw_result);
        ctx["result"] = sr.value("result", raw_result);
        ctx["directives"] = sr.value(
            "directives", nlohmann::json::array());
    } catch (...) {
        ctx["result"] = raw_result;
        ctx["directives"] = nlohmann::json::array();
    }
    return ctx.dump();
}
Activity · 9 steps
lines 1683–1683nlohmann::json ctx;lines 1684–1684ctx["tool_name"] = call.name;lines 1685–1685ctx["args"] = nlohmann::json::parse(serialize_args(call));lines 1686–1686ctx["elapsed_ms"] = elapsed_ms;lines 1687–1687ctx["tier"] = tier.empty() ? std::string{"lead"} : tier;lines 1688–1688ctx["iteration"] = iteration;lines 1689–1689ctx["result_kind"] = result_kind_to_string(kind);lines 1690–1698try { auto sr = nlohmann::json::parse(raw_result); ctx["result"] = sr.value("result", raw_result); ctx["directives"] = sr.value( "directives", nlohmann::json::array()); } catch (...) { ctx["result"] = raw_result; ctx["directives"] = nlohmann::json::array(); }lines 1699–1699return ctx.dump();

Requirements

REQ-MCP-017

build_pre_tool_json

std::string entropic::ToolExecutor::build_pre_tool_json(const ToolCall &call, const std::string &tier, int iteration)

Build PRE_TOOL_CALL hook context JSON.

src/mcp/tool_executor.cpp:1713

Source · 11 lines
std::string ToolExecutor::build_pre_tool_json(
    const ToolCall& call,
    const std::string& tier,
    int iteration) {
    nlohmann::json j;
    j["tool_name"] = call.name;
    j["args"] = nlohmann::json::parse(serialize_args(call));
    j["tier"] = tier.empty() ? std::string{"lead"} : tier;
    j["iteration"] = iteration;
    return j.dump();
}
Activity · 6 steps
lines 1717–1717nlohmann::json j;lines 1718–1718j["tool_name"] = call.name;lines 1719–1719j["args"] = nlohmann::json::parse(serialize_args(call));lines 1720–1720j["tier"] = tier.empty() ? std::string{"lead"} : tier;lines 1721–1721j["iteration"] = iteration;lines 1722–1722return j.dump();

Requirements

REQ-MCP-017

check_anti_spiral_hard_block

PreconditionCheck entropic::ToolExecutor::check_anti_spiral_hard_block(const LoopContext &ctx, const ToolCall &call) const

Check whether tool_name should be hard-blocked by the anti-spiral primitive given the current consecutive-call counter on ctx .

src/mcp/tool_executor.cpp:1356

Source · 19 lines
PreconditionCheck ToolExecutor::check_anti_spiral_hard_block(
    const LoopContext& ctx, const ToolCall& call) const {
    PreconditionCheck pc;
    int projected = (call.name == ctx.last_tool_name)
        ? (ctx.consecutive_same_tool_calls + 1)
        : 1;
    int threshold = effective_hard_block_threshold();
    if (projected >= threshold) {
        std::string text =
            "[anti-spiral] tool '" + call.name + "' blocked after "
            + std::to_string(projected)
            + " consecutive calls (threshold "
            + std::to_string(threshold)
            + "); pivot to a different tool or complete the task.";
        pc.rejection = create_denied_message(call, text);
        pc.kind = ToolResultKind::rejected_anti_spiral;
    }
    return pc;
}
Activity · 8 steps
lines 1358–1358PreconditionCheck pc;lines 1359–1361int projected = (call.name == ctx.last_tool_name) ? (ctx.consecutive_same_tool_calls + 1) : 1;lines 1362–1362int threshold = effective_hard_block_threshold();lines 1363–1363◇ if (projected >= threshold)lines 1364–1369std::string text = "[anti-spiral] tool '" + call.name + "' blocked after " + std::to_string(projected) + " consecutive calls (threshold " + std::to_string(threshold) + "); pivot to a different tool or complete the task.";lines 1370–1370pc.rejection = create_denied_message(call, text);lines 1371–1371pc.kind = ToolResultKind::rejected_anti_spiral;lines 1373–1373return pc;

Requirements

REQ-MCP-012 REQ-MCP-016

check_approval

bool entropic::ToolExecutor::check_approval(const ToolCall &call)

Check tool approval (auto/allow-list/callback/deny).

src/mcp/tool_executor.cpp:228

Source · 29 lines
bool ToolExecutor::check_approval(const ToolCall& call) {
    auto args_json = serialize_args(call);
    bool auto_ok = loop_config_.auto_approve_tools
                || !server_manager_.requires_approval(call.name)
                || server_manager_.is_explicitly_allowed(
                       call.name, args_json);

    bool approved = auto_ok;
    if (!approved && callbacks_.on_tool_call != nullptr) {
        auto call_json = serialize_tool_call(call);
        callbacks_.on_tool_call(call_json.c_str(),
                                callbacks_.user_data);
        approved = true;
    }

    // Hook: ON_PERMISSION_CHECK — informational (v1.9.1)
    if (hook_iface_.fire_info != nullptr) {
        std::string perm = approved ? "allowed" : "denied";
        std::string json = "{\"tool_name\":\""
            + call.name + "\",\"permission\":\"" + perm + "\"}";
        hook_iface_.fire_info(hook_iface_.registry,
            ENTROPIC_HOOK_ON_PERMISSION_CHECK, json.c_str());
    }

    if (!approved) {
        logger->warn("No approval callback — denying: {}", call.name);
    }
    return approved;
}
Activity · 14 steps
lines 229–229auto args_json = serialize_args(call);lines 230–233bool auto_ok = loop_config_.auto_approve_tools || !server_manager_.requires_approval(call.name) || server_manager_.is_explicitly_allowed( call.name, args_json);lines 235–235bool approved = auto_ok;lines 236–236◇ if (!approved && callbacks_.on_tool_call != nullptr)lines 237–237auto call_json = serialize_tool_call(call);lines 238–239callbacks_.on_tool_call(call_json.c_str(), callbacks_.user_data);lines 240–240approved = true;lines 244–244◇ if (hook_iface_.fire_info != nullptr)lines 245–245std::string perm = approved ? "allowed" : "denied";lines 246–247std::string json = "{\"tool_name\":\"" + call.name + "\",\"permission\":\"" + perm + "\"}";lines 248–249hook_iface_.fire_info(hook_iface_.registry, ENTROPIC_HOOK_ON_PERMISSION_CHECK, json.c_str());lines 252–252◇ if (!approved)lines 253–253logger->warn("No approval callback — denying: {}", call.name);lines 255–255return approved;

Requirements

REQ-MCP-009 REQ-MCP-012

check_approval_pc

PreconditionCheck entropic::ToolExecutor::check_approval_pc(LoopContext &ctx, const ToolCall &call)

Terminal approval + duplicate-counter reset step.

src/mcp/tool_executor.cpp:947

Source · 11 lines
PreconditionCheck ToolExecutor::check_approval_pc(
    LoopContext& ctx, const ToolCall& call) {
    PreconditionCheck pc;
    ctx.consecutive_duplicate_attempts = 0;
    if (!check_approval(call)) {
        pc.rejection = create_denied_message(
            call, "Permission denied");
        pc.kind = ToolResultKind::rejected_precondition;
    }
    return pc;
}
Activity · 6 steps
lines 949–949PreconditionCheck pc;lines 950–950ctx.consecutive_duplicate_attempts = 0;lines 951–951◇ if (!check_approval(call))lines 952–953pc.rejection = create_denied_message( call, "Permission denied");lines 954–954pc.kind = ToolResultKind::rejected_precondition;lines 956–956return pc;

Requirements

REQ-MCP-009 REQ-MCP-012

check_call_preconditions

PreconditionCheck entropic::ToolExecutor::check_call_preconditions(LoopContext &ctx, const ToolCall &call)

Check preconditions (MCP keys, tier, duplicate, approval).

src/mcp/tool_executor.cpp:910

Source · 24 lines
PreconditionCheck ToolExecutor::check_call_preconditions(
    LoopContext& ctx, const ToolCall& call) {
    PreconditionCheck pc = check_spiral_blocks(ctx, call);
    if (pc.rejection.has_value()) {
        return pc;
    }
    if (auto r = check_schema(call); r.has_value()) {
        pc.rejection = std::move(r);
        pc.kind = ToolResultKind::rejected_schema;
    } else if (auto a = check_mcp_authorization(ctx, call);
               a.has_value()) {
        pc.rejection = std::move(a);
        pc.kind = ToolResultKind::rejected_precondition;
    } else if (auto t = check_tier_allowed(ctx, call); t.has_value()) {
        pc.rejection = std::move(t);
        pc.kind = ToolResultKind::rejected_unauthorized;  // gh#83
    } else if (auto dup = check_duplicate(ctx, call); !dup.empty()) {
        pc.rejection = handle_duplicate(ctx, call, dup);
        pc.kind = ToolResultKind::rejected_duplicate;
    } else {
        pc = check_approval_pc(ctx, call);
    }
    return pc;
}
Activity · 21 steps
lines 912–912PreconditionCheck pc = check_spiral_blocks(ctx, call);lines 913–913◇ if (pc.rejection.has_value())lines 914–914return pc;lines 916–916◇ if (auto r = check_schema(call); r.has_value())lines 917–917pc.rejection = std::move(r);lines 918–918pc.kind = ToolResultKind::rejected_schema;lines 919–919elselines 919–920◇ if (auto a = check_mcp_authorization(ctx, call); a.has_value())lines 921–921pc.rejection = std::move(a);lines 922–922pc.kind = ToolResultKind::rejected_precondition;lines 923–923elselines 923–923◇ if (auto t = check_tier_allowed(ctx, call); t.has_value())lines 924–924pc.rejection = std::move(t);lines 925–925pc.kind = ToolResultKind::rejected_unauthorized;lines 926–926elselines 926–926◇ if (auto dup = check_duplicate(ctx, call); !dup.empty())lines 927–927pc.rejection = handle_duplicate(ctx, call, dup);lines 928–928pc.kind = ToolResultKind::rejected_duplicate;lines 929–929elselines 930–930pc = check_approval_pc(ctx, call);lines 932–932return pc;

Requirements

REQ-MCP-012

check_dup_or_approval

std::optional< Message > entropic::ToolExecutor::check_dup_or_approval(LoopContext &ctx, const ToolCall &call)

Check duplicate detection and global approval.

src/mcp/tool_executor.cpp:836

Source · 12 lines
std::optional<Message> ToolExecutor::check_dup_or_approval(
    LoopContext& ctx, const ToolCall& call) {
    auto dup_result = check_duplicate(ctx, call);
    if (!dup_result.empty()) {
        return handle_duplicate(ctx, call, dup_result);
    }
    ctx.consecutive_duplicate_attempts = 0;
    return check_approval(call)
        ? std::nullopt
        : std::optional{create_denied_message(
              call, "Permission denied")};
}
Activity · 5 steps
lines 838–838auto dup_result = check_duplicate(ctx, call);lines 839–839◇ if (!dup_result.empty())lines 840–840return handle_duplicate(ctx, call, dup_result);lines 842–842ctx.consecutive_duplicate_attempts = 0;lines 843–846return check_approval(call) ? std::nullopt : std::optional{create_denied_message( call, "Permission denied")};

Requirements

REQ-MCP-012 REQ-MCP-015

check_duplicate

std::string entropic::ToolExecutor::check_duplicate(const LoopContext &ctx, const ToolCall &call) const

Check duplicate tool call.

src/mcp/tool_executor.cpp:167

Source · 13 lines
std::string ToolExecutor::check_duplicate(
    const LoopContext& ctx,
    const ToolCall& call) const {
    if (server_manager_.skip_duplicate_check(call.name)) {
        return "";
    }
    auto key = tool_call_key(call);
    auto it = ctx.recent_tool_calls.find(key);
    if (it != ctx.recent_tool_calls.end()) {
        return it->second;
    }
    return "";
}
Activity · 7 steps
lines 170–170◇ if (server_manager_.skip_duplicate_check(call.name))lines 171–171return "";lines 173–173auto key = tool_call_key(call);lines 174–174auto it = ctx.recent_tool_calls.find(key);lines 175–175◇ if (it != ctx.recent_tool_calls.end())lines 176–176return it->second;lines 178–178return "";

Requirements

REQ-MCP-015

check_enum

static std::string entropic::check_enum(const std::string &key, const nlohmann::json &allowed, const nlohmann::json &val)

Check one property's enum and type constraints.

src/mcp/tool_executor.cpp:343

Source · 11 lines
static std::string check_enum(
    const std::string& key,
    const nlohmann::json& allowed,
    const nlohmann::json& val)
{
    for (const auto& e : allowed) {
        if (e == val) { return ""; }
    }
    return "Invalid value for '" + key + "': "
         + val.dump() + ". Must be one of: " + allowed.dump();
}
Activity · 4 steps
lines 348–348◇ for (const auto& e : allowed)lines 349–349◇ if (e == val)lines 349–349return "";lines 351–352return "Invalid value for '" + key + "': " + val.dump() + ". Must be one of: " + allowed.dump();

Requirements

REQ-MCP-013

check_mcp_authorization

std::optional< Message > entropic::ToolExecutor::check_mcp_authorization(const LoopContext &ctx, const ToolCall &call) const

Check MCP authorization for a tool call.

src/mcp/tool_executor.cpp:790

Source · 29 lines
std::optional<Message> ToolExecutor::check_mcp_authorization(
    const LoopContext& ctx,
    const ToolCall& call) const {
    if (auth_mgr_ == nullptr) {
        return std::nullopt;
    }
    auto identity = ctx.locked_tier.empty()
                        ? "lead" : ctx.locked_tier;
    auto required = server_manager_.get_required_access_level(
        call.name);
    if (!auth_mgr_->is_enforced(identity) ||
        auth_mgr_->check_access(identity, call.name, required)) {
        return std::nullopt;
    }
    auto level_str = mcp_access_level_name(required);
    logger->warn("MCP key denied: {} requires {} for {}",
                 call.name, level_str, identity);
    Message msg;
    msg.role = "user";
    tag_tool_result(msg, call);  // v2.14.6
    msg.content =
        "Tool `" + call.name + "` was denied: identity `"
        + identity + "` lacks " + level_str
        + " access.\n\n"
        "Your MCP key set does not authorize this tool. "
        "Use `entropic.delegate` to hand off to an identity "
        "that has the required access.";
    return msg;
}
Activity · 13 steps
lines 793–793◇ if (auth_mgr_ == nullptr)lines 794–794return std::nullopt;lines 796–797auto identity = ctx.locked_tier.empty() ? "lead" : ctx.locked_tier;lines 798–799auto required = server_manager_.get_required_access_level( call.name);lines 800–801◇ if (!auth_mgr_->is_enforced(identity) || auth_mgr_->check_access(identity, call.name, required))lines 802–802return std::nullopt;lines 804–804auto level_str = mcp_access_level_name(required);lines 805–806logger->warn("MCP key denied: {} requires {} for {}", call.name, level_str, identity);lines 807–807Message msg;lines 808–808msg.role = "user";lines 809–809tag_tool_result(msg, call);lines 810–816msg.content = "Tool `" + call.name + "` was denied: identity `" + identity + "` lacks " + level_str + " access.\n\n" "Your MCP key set does not authorize this tool. " "Use `entropic.delegate` to hand off to an identity " "that has the required access.";lines 817–817return msg;

Requirements

REQ-MCP-010 REQ-MCP-011 REQ-MCP-012

check_property_constraints

static std::string entropic::check_property_constraints(const std::string &key, const nlohmann::json &prop, const nlohmann::json &val)

Check one property's enum, type and range constraints.

src/mcp/tool_executor.cpp:426

Source · 14 lines
static std::string check_property_constraints(
    const std::string& key,
    const nlohmann::json& prop,
    const nlohmann::json& val)
{
    std::string err;
    if (prop.contains("enum")) {
        err = check_enum(key, prop["enum"], val);
    }
    if (err.empty() && prop.contains("type")) {
        err = check_type(key, prop["type"].get<std::string>(), val);
    }
    return err.empty() ? check_range(key, prop, val) : err;
}
Activity · 6 steps
lines 431–431std::string err;lines 432–432◇ if (prop.contains("enum"))lines 433–433err = check_enum(key, prop["enum"], val);lines 435–435◇ if (err.empty() && prop.contains("type"))lines 436–436err = check_type(key, prop["type"].get<std::string>(), val);lines 438–438return err.empty() ? check_range(key, prop, val) : err;

Requirements

REQ-MCP-013

check_range

static std::string entropic::check_range(const std::string &key, const nlohmann::json &prop, const nlohmann::json &val)

Check a numeric value against minimum / maximum (v2.14.0).

src/mcp/tool_executor.cpp:396

Source · 17 lines
static std::string check_range(
    const std::string& key,
    const nlohmann::json& prop,
    const nlohmann::json& val)
{
    std::string err;
    if (val.is_number() && prop.contains("minimum")
        && val.get<double>() < prop["minimum"].get<double>()) {
        err = "Value for '" + key + "' is " + val.dump()
            + ", below the minimum " + prop["minimum"].dump();
    } else if (val.is_number() && prop.contains("maximum")
               && val.get<double>() > prop["maximum"].get<double>()) {
        err = "Value for '" + key + "' is " + val.dump()
            + ", above the maximum " + prop["maximum"].dump();
    }
    return err;
}
Activity · 7 steps
lines 401–401std::string err;lines 402–403◇ if (val.is_number() && prop.contains("minimum") && val.get<double>() < prop["minimum"].get<double>())lines 404–405err = "Value for '" + key + "' is " + val.dump() + ", below the minimum " + prop["minimum"].dump();lines 406–406elselines 406–407◇ if (val.is_number() && prop.contains("maximum") && val.get<double>() > prop["maximum"].get<double>())lines 408–409err = "Value for '" + key + "' is " + val.dump() + ", above the maximum " + prop["maximum"].dump();lines 411–411return err;

Requirements

REQ-MCP-013

check_repeated_failure

PreconditionCheck entropic::ToolExecutor::check_repeated_failure(const LoopContext &ctx, const ToolCall &call) const

Refuse a call whose exact arguments have already failed max_identical_failures times.

src/mcp/tool_executor.cpp:1394

Source · 24 lines
PreconditionCheck ToolExecutor::check_repeated_failure(
    const LoopContext& ctx, const ToolCall& call) const {
    PreconditionCheck pc;
    auto it = ctx.failed_tool_calls.find(tool_call_key(call));
    if (it == ctx.failed_tool_calls.end()) {
        return pc;
    }
    int failures = it->second;
    if (failures + 1 >= loop_config_.max_identical_failures) {
        std::string text =
            "[repeated-failure] tool '" + call.name + "' has already failed "
            + std::to_string(failures)
            + " times with identical arguments; the failure is not "
              "transient. Change the arguments, try a different approach, "
              "or report that the task cannot be completed this way.";
        pc.rejection = create_denied_message(call, text);
        // Deliberately the EXISTING kind, not a new one: repeating a call
        // that keeps failing IS a spiral, and the nine result_kind strings
        // are a consumer contract (sassafras-class reads them). A tenth
        // kind would be a breaking change for a case this one describes.
        pc.kind = ToolResultKind::rejected_anti_spiral;
    }
    return pc;
}
Activity · 10 steps
lines 1396–1396PreconditionCheck pc;lines 1397–1397auto it = ctx.failed_tool_calls.find(tool_call_key(call));lines 1398–1398◇ if (it == ctx.failed_tool_calls.end())lines 1399–1399return pc;lines 1401–1401int failures = it->second;lines 1402–1402◇ if (failures + 1 >= loop_config_.max_identical_failures)lines 1403–1408std::string text = "[repeated-failure] tool '" + call.name + "' has already failed " + std::to_string(failures) + " times with identical arguments; the failure is not " "transient. Change the arguments, try a different approach, " "or report that the task cannot be completed this way.";lines 1409–1409pc.rejection = create_denied_message(call, text);lines 1414–1414pc.kind = ToolResultKind::rejected_anti_spiral;lines 1416–1416return pc;

Requirements

REQ-MCP-015 REQ-MCP-016

check_required_fields

static std::string entropic::check_required_fields(const nlohmann::json &schema, const nlohmann::json &args)

Check required fields are present.

src/mcp/tool_executor.cpp:309

Source · 13 lines
static std::string check_required_fields(
    const nlohmann::json& schema,
    const nlohmann::json& args)
{
    for (const auto& req : schema.value("required",
                                         nlohmann::json::array())) {
        if (!args.contains(req.get<std::string>())) {
            return "Missing required argument: "
                 + req.get<std::string>();
        }
    }
    return "";
}
Activity · 4 steps
lines 313–313◇ for (const auto& req : schema.value("required", nlohmann::json::array()))lines 315–315◇ if (!args.contains(req.get<std::string>()))lines 316–317return "Missing required argument: " + req.get<std::string>();lines 320–320return "";

Requirements

REQ-MCP-013

check_schema

std::optional< Message > entropic::ToolExecutor::check_schema(const ToolCall &call)

Validate tool arguments against schema constraints.

src/mcp/tool_executor.cpp:873

Source · 13 lines
std::optional<Message> ToolExecutor::check_schema(
    const ToolCall& call) {
    auto schema = server_manager_.get_tool_schema(call.name);
    if (schema.empty()) { return std::nullopt; }
    auto args = nlohmann::json::parse(
        serialize_args(call), nullptr, false);
    auto err = args.is_discarded()
        ? std::string{} : validate_tool_args(schema, args);
    if (err.empty()) { return std::nullopt; }
    logger->warn("Tool '{}' argument validation failed: {}",
                 call.name, err);
    return create_denied_message(call, err);
}
Activity · 9 steps
lines 875–875auto schema = server_manager_.get_tool_schema(call.name);lines 876–876◇ if (schema.empty())lines 876–876return std::nullopt;lines 877–878auto args = nlohmann::json::parse( serialize_args(call), nullptr, false);lines 879–880auto err = args.is_discarded() ? std::string{} : validate_tool_args(schema, args);lines 881–881◇ if (err.empty())lines 881–881return std::nullopt;lines 882–883logger->warn("Tool '{}' argument validation failed: {}", call.name, err);lines 884–884return create_denied_message(call, err);

Requirements

REQ-MCP-008 REQ-MCP-013

check_spiral_blocks

PreconditionCheck entropic::ToolExecutor::check_spiral_blocks(const LoopContext &ctx, const ToolCall &call) const

Run both pre-dispatch spiral blocks in order.

src/mcp/tool_executor.cpp:1432

Source · 13 lines
PreconditionCheck ToolExecutor::check_spiral_blocks(
    const LoopContext& ctx, const ToolCall& call) const {
    // Both fire BEFORE schema/auth/dispatch (Issue #14, v2.1.4): they are
    // cheaper than those checks and short-circuit a tool the engine has
    // already decided to refuse. They are siblings, not duplicates — one
    // counts a tool NAME repeating, the other one exact call repeating
    // against an identical error, and neither sees the other's case.
    PreconditionCheck pc = check_anti_spiral_hard_block(ctx, call);
    if (pc.rejection.has_value()) {
        return pc;
    }
    return check_repeated_failure(ctx, call);
}
Activity · 4 steps
lines 1439–1439PreconditionCheck pc = check_anti_spiral_hard_block(ctx, call);lines 1440–1440◇ if (pc.rejection.has_value())lines 1441–1441return pc;lines 1443–1443return check_repeated_failure(ctx, call);

Requirements

REQ-MCP-016

check_tier_allowed

std::optional< Message > entropic::ToolExecutor::check_tier_allowed(const LoopContext &ctx, const ToolCall &call) const

Check tier allowed_tools + bash_commands restrictions.

src/mcp/tool_executor.cpp:270

Source · 28 lines
std::optional<Message> ToolExecutor::check_tier_allowed(
    const LoopContext& ctx, const ToolCall& call) const {
    // gh#83 (v2.5.2): enforce the locked tier's allowed_tools at
    // dispatch — not just at prompt-injection time. Without this a
    // model that emits an off-allowlist call (hallucinated, learned,
    // or cross-tier) has it dispatched normally; tier isolation was
    // advisory only. Pass through when: no tier locked, no map wired,
    // or the tier declares no allowlist (unrestricted).
    if (ctx.locked_tier.empty() || tier_allowed_tools_ == nullptr) {
        return std::nullopt;
    }
    auto it = tier_allowed_tools_->find(ctx.locked_tier);
    // Authorized when the tier has no allowlist entry (its identity declares
    // no `allowed_tools` key: unrestricted) or the call is in the list.
    // gh#211 (v2.14.4): a DECLARED empty list means no tools — it used to
    // read as unrestricted, so `allowed_tools: []` granted everything.
    bool authorized = it == tier_allowed_tools_->end()
                   || std::find(it->second.begin(), it->second.end(),
                                call.name) != it->second.end();
    if (authorized) {
        return std::nullopt;
    }
    logger->warn("Tool '{}' not in tier '{}' allowed_tools — rejecting",
                 call.name, ctx.locked_tier);
    return create_denied_message(
        call, "tier '" + ctx.locked_tier + "' is not authorized to call '"
                  + call.name + "'");
}
Activity · 8 steps
lines 278–278◇ if (ctx.locked_tier.empty() || tier_allowed_tools_ == nullptr)lines 279–279return std::nullopt;lines 281–281auto it = tier_allowed_tools_->find(ctx.locked_tier);lines 286–288bool authorized = it == tier_allowed_tools_->end() || std::find(it->second.begin(), it->second.end(), call.name) != it->second.end();lines 289–289◇ if (authorized)lines 290–290return std::nullopt;lines 292–293logger->warn("Tool '{}' not in tier '{}' allowed_tools — rejecting", call.name, ctx.locked_tier);lines 294–296return create_denied_message( call, "tier '" + ctx.locked_tier + "' is not authorized to call '" + call.name + "'");

Requirements

REQ-MCP-012 REQ-MCP-014

check_type

static std::string entropic::check_type(const std::string &key, const std::string &type, const nlohmann::json &val)

Check a single value against a type constraint.

src/mcp/tool_executor.cpp:366

Source · 14 lines
static std::string check_type(
    const std::string& key,
    const std::string& type,
    const nlohmann::json& val)
{
    bool ok = (type == "string" && val.is_string())
           || (type == "integer" && val.is_number_integer())
           || (type == "number" && val.is_number())
           || (type == "boolean" && val.is_boolean())
           || (type == "array" && val.is_array())
           || (type == "object" && val.is_object());
    return ok ? "" : "Type mismatch for '" + key
                   + "': expected " + type;
}
Activity · 2 steps
lines 371–376bool ok = (type == "string" && val.is_string()) || (type == "integer" && val.is_number_integer()) || (type == "number" && val.is_number()) || (type == "boolean" && val.is_boolean()) || (type == "array" && val.is_array()) || (type == "object" && val.is_object());lines 377–378return ok ? "" : "Type mismatch for '" + key + "': expected " + type;

Requirements

REQ-MCP-013

classify_tool_result

static ToolResultKind entropic::classify_tool_result(const std::string &content)

Classify a tool result by its content (error/empty/ok).

src/mcp/tool_executor.cpp:1030

Source · 9 lines
static ToolResultKind classify_tool_result(const std::string& content) {
    if (mcp::looks_like_tool_error(content)) {
        return ToolResultKind::error;
    }
    if (mcp::is_effectively_empty(content)) {
        return ToolResultKind::ok_empty;
    }
    return ToolResultKind::ok;
}
Activity · 5 steps
lines 1031–1031◇ if (mcp::looks_like_tool_error(content))lines 1032–1032return ToolResultKind::error;lines 1034–1034◇ if (mcp::is_effectively_empty(content))lines 1035–1035return ToolResultKind::ok_empty;lines 1037–1037return ToolResultKind::ok;

Requirements

REQ-MCP-019

create_circuit_breaker_message

Message entropic::ToolExecutor::create_circuit_breaker_message()

Create circuit breaker message.

src/mcp/tool_executor.cpp:1529

Source · 11 lines
Message ToolExecutor::create_circuit_breaker_message() {
    Message msg;
    msg.role = "user";
    msg.content =
        "STOP: You have called the same tool 3 times with "
        "identical arguments. This indicates you are stuck. "
        "Please try a completely different approach or respond "
        "to the user explaining what's blocking you.";
    logger->error("Circuit breaker triggered");
    return msg;
}
Activity · 5 steps
lines 1530–1530Message msg;lines 1531–1531msg.role = "user";lines 1532–1536msg.content = "STOP: You have called the same tool 3 times with " "identical arguments. This indicates you are stuck. " "Please try a completely different approach or respond " "to the user explaining what's blocking you.";lines 1537–1537logger->error("Circuit breaker triggered");lines 1538–1538return msg;

Requirements

REQ-MCP-015

create_denied_message

Message entropic::ToolExecutor::create_denied_message(const ToolCall &call, const std::string &reason)

Create a permission denied message.

src/mcp/tool_executor.cpp:701

Source · 12 lines
Message ToolExecutor::create_denied_message(
    const ToolCall& call,
    const std::string& reason) {
    Message msg;
    msg.role = "user";
    tag_tool_result(msg, call);  // v2.14.6
    msg.content =
        "Tool `" + call.name + "` was denied: " + reason + "\n\n"
        "This tool is not available to you. Do NOT retry it. "
        "Use a different approach to accomplish your task.";
    return msg;
}
Activity · 5 steps
lines 704–704Message msg;lines 705–705msg.role = "user";lines 706–706tag_tool_result(msg, call);lines 707–710msg.content = "Tool `" + call.name + "` was denied: " + reason + "\n\n" "This tool is not available to you. Do NOT retry it. " "Use a different approach to accomplish your task.";lines 711–711return msg;

Requirements

REQ-MCP-015

create_duplicate_message

Message entropic::ToolExecutor::create_duplicate_message(const ToolCall &call, const std::string &previous_result)

Create duplicate notification message.

src/mcp/tool_executor.cpp:1553

Show on the map →

Called by handle_duplicate

Calls tag_tool_result

Source · 26 lines
Message ToolExecutor::create_duplicate_message(
    const ToolCall& call,
    const std::string& previous_result) {
    bool was_denied =
        previous_result.find("was denied") != std::string::npos
        || previous_result.find("not available") != std::string::npos;

    Message msg;
    msg.role = "user";
    tag_tool_result(msg, call);  // v2.14.6

    if (was_denied) {
        msg.content =
            "Tool `" + call.name + "` is not available to you "
            "and retrying will not help. You MUST use a different "
            "approach. Do NOT call `" + call.name + "` again.";
    } else {
        msg.content =
            "Tool `" + call.name + "` was already called with "
            "the same arguments.\n\nPrevious result:\n" +
            previous_result +
            "\n\nDo NOT call this tool again. "
            "Use the previous result above.";
    }
    return msg;
}
Activity · 9 steps
lines 1556–1558bool was_denied = previous_result.find("was denied") != std::string::npos || previous_result.find("not available") != std::string::npos;lines 1560–1560Message msg;lines 1561–1561msg.role = "user";lines 1562–1562tag_tool_result(msg, call);lines 1564–1564◇ if (was_denied)lines 1565–1568msg.content = "Tool `" + call.name + "` is not available to you " "and retrying will not help. You MUST use a different " "approach. Do NOT call `" + call.name + "` again.";lines 1569–1569elselines 1570–1575msg.content = "Tool `" + call.name + "` was already called with " "the same arguments.\n\nPrevious result:\n" + previous_result + "\n\nDo NOT call this tool again. " "Use the previous result above.";lines 1577–1577return msg;

Requirements

REQ-MCP-015

create_error_message

Message entropic::ToolExecutor::create_error_message(const ToolCall &call, const std::string &error)

Create a tool error message.

src/mcp/tool_executor.cpp:724

Show on the map →

Called by none

Calls tag_tool_result

Source · 14 lines
Message ToolExecutor::create_error_message(
    const ToolCall& call,
    const std::string& error) {
    Message msg;
    msg.role = "user";
    tag_tool_result(msg, call);  // v2.14.6
    msg.content =
        "Tool `" + call.name + "` failed with error: " + error +
        "\n\nRECOVERY:\n"
        "- Check arguments are correct\n"
        "- Try a different approach\n"
        "- Do NOT retry with the same arguments";
    return msg;
}
Activity · 5 steps
lines 727–727Message msg;lines 728–728msg.role = "user";lines 729–729tag_tool_result(msg, call);lines 730–735msg.content = "Tool `" + call.name + "` failed with error: " + error + "\n\nRECOVERY:\n" "- Check arguments are correct\n" "- Try a different approach\n" "- Do NOT retry with the same arguments";lines 736–736return msg;

Requirements

REQ-MCP-015

effective_hard_block_threshold

int entropic::ToolExecutor::effective_hard_block_threshold() const

Compute the effective hard-block threshold.

src/mcp/tool_executor.cpp:1324

Source · 7 lines
int ToolExecutor::effective_hard_block_threshold() const {
    int configured = loop_config_.max_consecutive_same_tool_hard_block;
    if (configured < 0) {
        configured = loop_config_.max_consecutive_same_tool + 2;
    }
    return configured;
}
Activity · 4 steps
lines 1325–1325int configured = loop_config_.max_consecutive_same_tool_hard_block;lines 1326–1326◇ if (configured < 0)lines 1327–1327configured = loop_config_.max_consecutive_same_tool + 2;lines 1329–1329return configured;

Requirements

REQ-MCP-016

execute_tool

std::pair< Message, std::string > entropic::ToolExecutor::execute_tool(LoopContext &ctx, const ToolCall &call)

Execute a single tool call through ServerManager .

src/mcp/tool_executor.cpp:536

Show on the map →

Called by process_single_call

Calls fire_tool_complete_callback, parse_tool_result_text, record_tool_history, sanitize_utf8, serialize_args, serialize_tool_call, servers_for, tag_tool_result

Source · 54 lines
std::pair<Message, std::string> ToolExecutor::execute_tool(
    LoopContext& ctx, const ToolCall& call) {

    auto args_json = serialize_args(call);

    if (callbacks_.on_tool_start != nullptr) {
        auto call_json = serialize_tool_call(call);
        callbacks_.on_tool_start(call_json.c_str(),
                                 callbacks_.user_data);
    }

    auto start = std::chrono::steady_clock::now();
    // Inbound boundary from MCP server subprocess. v2.1.0 (#47) introduced
    // this; v2.1.1 (#3) generalized it as one of several boundary-policy
    // sanitize sites — see include/entropic/mcp/utf8_sanitize.h for the
    // full policy. The earlier "trust downstream" assumption was wrong:
    // bytes also enter via the model token stream and the audit-replay
    // path; both now sanitize at their own boundaries.
    // gh#166 (v2.13.0): route to the RUNNING SESSION's workspace. This is
    // the call that touches the filesystem, so it is the one that must
    // land in the right repository; the metadata lookups above answer
    // schema/permission questions that are workspace-invariant for the
    // built-in servers and fail SAFE (unknown → WRITE required, no schema
    // → no validation skip that grants anything).
    std::string result_json;
    {
        RunSessionScope session_scope(ctx.session_key);
        result_json = mcp::sanitize_utf8(
            servers_for(ctx.session_key).execute(call.name, args_json));
    }
    auto end = std::chrono::steady_clock::now();
    auto ms = std::chrono::duration_cast<
        std::chrono::milliseconds>(end - start).count();

    ctx.metrics.tool_calls++;

    std::string result_text = parse_tool_result_text(result_json);

    // P1-11 (2.0.6-rc16): stash into history ring buffer so the
    // constitutional validator revision prompt (and diagnostic tools)
    // can surface prior-iteration tool calls without re-reading
    // messages[].
    record_tool_history(call, args_json, result_text, ms,
                        ctx.metrics.iterations);

    fire_tool_complete_callback(call, result_text, ms);

    Message msg;
    msg.role = "user";
    msg.content = result_text;
    tag_tool_result(msg, call);

    return {std::move(msg), result_json};
}
Activity · 19 steps
lines 539–539auto args_json = serialize_args(call);lines 541–541◇ if (callbacks_.on_tool_start != nullptr)lines 542–542auto call_json = serialize_tool_call(call);lines 543–544callbacks_.on_tool_start(call_json.c_str(), callbacks_.user_data);lines 547–547auto start = std::chrono::steady_clock::now();lines 560–560std::string result_json;lines 562–562RunSessionScope session_scope(ctx.session_key);lines 563–564result_json = mcp::sanitize_utf8( servers_for(ctx.session_key).execute(call.name, args_json));lines 566–566auto end = std::chrono::steady_clock::now();lines 567–568auto ms = std::chrono::duration_cast< std::chrono::milliseconds>(end - start).count();lines 570–570ctx.metrics.tool_calls++;lines 572–572std::string result_text = parse_tool_result_text(result_json);lines 578–579record_tool_history(call, args_json, result_text, ms, ctx.metrics.iterations);lines 581–581fire_tool_complete_callback(call, result_text, ms);lines 583–583Message msg;lines 584–584msg.role = "user";lines 585–585msg.content = result_text;lines 586–586tag_tool_result(msg, call);lines 588–588return {std::move(msg), result_json};

Requirements

REQ-LOOP-009 REQ-MCP-002 REQ-MCP-020 REQ-MCP-027

extract_and_process_directives

void entropic::ToolExecutor::extract_and_process_directives(LoopContext &ctx, const std::string &raw_result)

Extract directives from ServerResponse and process via hooks.

src/mcp/tool_executor.cpp:1903

Source · 23 lines
void ToolExecutor::extract_and_process_directives(
    LoopContext& ctx, const std::string& raw_result) {
    if (hooks_.process_directives == nullptr) { return; }
    auto extracted = extract_directive_array(raw_result);
    if (!extracted) { return; }
    auto& [resp, dirs] = *extracted;

    auto result_json = nlohmann::json::parse(
        resp.value("result", "{}"), nullptr, false);

    std::vector<std::unique_ptr<Directive>> owned;
    for (const auto& d : dirs) {
        auto directive = build_directive(d, result_json);
        if (directive) { owned.push_back(std::move(directive)); }
    }
    if (owned.empty()) { return; }

    std::vector<const Directive*> ptrs;
    ptrs.reserve(owned.size());
    for (const auto& d : owned) { ptrs.push_back(d.get()); }
    logger->info("Processing {} directives from tool result", ptrs.size());
    hooks_.process_directives(ctx, ptrs, hooks_.user_data);
}
Activity · 20 steps
lines 1905–1905◇ if (hooks_.process_directives == nullptr)lines 1905–1905return;lines 1906–1906auto extracted = extract_directive_array(raw_result);lines 1907–1907◇ if (!extracted)lines 1907–1907return;lines 1908–1908auto& [resp, dirs] = *extracted;lines 1910–1911auto result_json = nlohmann::json::parse( resp.value("result", "{}"), nullptr, false);lines 1913–1913std::vector<std::unique_ptr<Directive>> owned;lines 1914–1914◇ for (const auto& d : dirs)lines 1915–1915auto directive = build_directive(d, result_json);lines 1916–1916◇ if (directive)lines 1916–1916owned.push_back(std::move(directive));lines 1918–1918◇ if (owned.empty())lines 1918–1918return;lines 1920–1920std::vector<const Directive*> ptrs;lines 1921–1921ptrs.reserve(owned.size());lines 1922–1922◇ for (const auto& d : owned)lines 1922–1922ptrs.push_back(d.get());lines 1923–1923logger->info("Processing {} directives from tool result", ptrs.size());lines 1924–1924hooks_.process_directives(ctx, ptrs, hooks_.user_data);

Requirements

REQ-MCP-002 REQ-MCP-024

extract_context_refs

static std::vector< ContextRef > entropic::extract_context_refs(const nlohmann::json &result_json)

Parse the context array of a delegate/pipeline result (gh#162).

src/mcp/tool_executor.cpp:1805

Source · 18 lines
static std::vector<ContextRef> extract_context_refs(
    const nlohmann::json& result_json) {
    std::vector<ContextRef> refs;
    if (!result_json.contains("context")
        || !result_json["context"].is_array()) {
        return refs;
    }
    for (const auto& entry : result_json["context"]) {
        if (!entry.is_object()) { continue; }
        ContextRef ref;
        ref.path = entry.value("path", std::string{});
        if (ref.path.empty()) { continue; }
        ref.lines = entry.value("lines", std::string{});
        ref.note = entry.value("note", std::string{});
        refs.push_back(std::move(ref));
    }
    return refs;
}
Activity · 14 steps
lines 1807–1807std::vector<ContextRef> refs;lines 1808–1809◇ if (!result_json.contains("context") || !result_json["context"].is_array())lines 1810–1810return refs;lines 1812–1812◇ for (const auto& entry : result_json["context"])lines 1813–1813◇ if (!entry.is_object())lines 1813–1813continue;lines 1814–1814ContextRef ref;lines 1815–1815ref.path = entry.value("path", std::string{});lines 1816–1816◇ if (ref.path.empty())lines 1816–1816continue;lines 1817–1817ref.lines = entry.value("lines", std::string{});lines 1818–1818ref.note = entry.value("note", std::string{});lines 1819–1819refs.push_back(std::move(ref));lines 1821–1821return refs;

Requirements

REQ-DELEG-006

extract_directive_array

static std::optional< std::pair< nlohmann::json, nlohmann::json > > entropic::extract_directive_array(const std::string &raw_result)

Pull the "directives" array out of a tool ServerResponse JSON.

src/mcp/tool_executor.cpp:1880

Source · 9 lines
extract_directive_array(const std::string& raw_result) {
    auto resp = nlohmann::json::parse(raw_result, nullptr, false);
    if (!resp.is_object() || !resp.contains("directives")) {
        return std::nullopt;
    }
    auto dirs = resp["directives"];
    if (!dirs.is_array() || dirs.empty()) { return std::nullopt; }
    return std::make_pair(std::move(resp), std::move(dirs));
}
Activity · 7 steps
lines 1881–1881auto resp = nlohmann::json::parse(raw_result, nullptr, false);lines 1882–1882◇ if (!resp.is_object() || !resp.contains("directives"))lines 1883–1883return std::nullopt;lines 1885–1885auto dirs = resp["directives"];lines 1886–1886◇ if (!dirs.is_array() || dirs.empty())lines 1886–1886return std::nullopt;lines 1887–1887return std::make_pair(std::move(resp), std::move(dirs));

Requirements

REQ-MCP-002

finalize_tool_call

void entropic::ToolExecutor::finalize_tool_call(LoopContext &ctx, const ToolCall &call, Message &msg, const std::string &raw_result, double exec_ms)

Post-execution processing for a tool call.

src/mcp/tool_executor.cpp:1095

Source · 32 lines
void ToolExecutor::finalize_tool_call(LoopContext& ctx, const ToolCall& call,
                                      Message& msg,
                                      const std::string& raw_result,
                                      double exec_ms) {
    // #46 (v2.1.0): cap result content at LoopConfig.max_tool_result_bytes
    // so a single runaway tool can't exhaust the context budget. Applied
    // BEFORE classification so kind reflects the bounded form, and BEFORE
    // record_tool_call so the duplicate cache stores what the model saw.
    apply_result_size_cap(msg.content);
    ctx.effective_tool_calls++;
    msg.metadata["added_at_iteration"] =
        std::to_string(ctx.metrics.iterations);
    record_tool_call(ctx, call, raw_result);

    // #44 (v2.1.0): honest byte-level signal — error trumps empty.
    ToolResultKind kind = classify_tool_result(msg.content);
    // gh#84 (v2.5.1): stamp the result kind on the message so the
    // engine can tell genuine progress (ok / ok_empty) from rejections
    // and errors when deciding whether to reset the thinking budget.
    msg.metadata["result_kind"] = result_kind_to_string(kind);
    fire_post_tool_hook(ctx, call, raw_result, exec_ms, kind, msg);

    // Demo ask #5 (v2.1.0): anti-spiral primitive. Track consecutive
    // same-tool calls; at threshold, populate pending_anti_spiral_warning
    // so the next turn's reminder tells the model to pivot or complete.
    update_anti_spiral_tracking(ctx, call.name);

    log_tool_call(ctx, call, exec_ms, raw_result, kind);

    extract_and_process_directives(ctx, raw_result);
    run_post_tool_hooks(ctx);
}
Activity · 11 steps
lines 1103–1103apply_result_size_cap(msg.content);lines 1104–1104ctx.effective_tool_calls++;lines 1105–1106msg.metadata["added_at_iteration"] = std::to_string(ctx.metrics.iterations);lines 1107–1107record_tool_call(ctx, call, raw_result);lines 1110–1110ToolResultKind kind = classify_tool_result(msg.content);lines 1114–1114msg.metadata["result_kind"] = result_kind_to_string(kind);lines 1115–1115fire_post_tool_hook(ctx, call, raw_result, exec_ms, kind, msg);lines 1120–1120update_anti_spiral_tracking(ctx, call.name);lines 1122–1122log_tool_call(ctx, call, exec_ms, raw_result, kind);lines 1124–1124extract_and_process_directives(ctx, raw_result);lines 1125–1125run_post_tool_hooks(ctx);

Requirements

REQ-MCP-015 REQ-MCP-017 REQ-MCP-019

fire_post_tool_hook

void entropic::ToolExecutor::fire_post_tool_hook(const LoopContext &ctx, const ToolCall &call, const std::string &raw_result, double elapsed_ms, ToolResultKind kind, Message &msg)

Fire POST_TOOL_CALL hook (if wired) and apply any transform.

src/mcp/tool_executor.cpp:1470

Source · 20 lines
void ToolExecutor::fire_post_tool_hook(
    const LoopContext& ctx, const ToolCall& call,
    const std::string& raw_result, double elapsed_ms,
    ToolResultKind kind, Message& msg) {
    if (hook_iface_.fire_post == nullptr) { return; }
    auto json = build_post_tool_json(
        call, raw_result, elapsed_ms, ctx.locked_tier,
        ctx.metrics.iterations, kind);
    char* out = nullptr;
    hook_iface_.fire_post(hook_iface_.registry,
        ENTROPIC_HOOK_POST_TOOL_CALL, json.c_str(), &out);
    if (out != nullptr) {
        // gh#3 recurrence (gh#111, v2.9.7): a hook's transformed result is
        // an inbound boundary crossing a plugin .so, same class as
        // fire_post_generate_hook/fire_complete_hook in engine.cpp —
        // sanitize before it becomes msg.content.
        msg.content = mcp::sanitize_utf8(out);
        free(out);
    }
}
Activity · 8 steps
lines 1474–1474◇ if (hook_iface_.fire_post == nullptr)lines 1474–1474return;lines 1475–1477auto json = build_post_tool_json( call, raw_result, elapsed_ms, ctx.locked_tier, ctx.metrics.iterations, kind);lines 1478–1478char* out = nullptr;lines 1479–1480hook_iface_.fire_post(hook_iface_.registry, ENTROPIC_HOOK_POST_TOOL_CALL, json.c_str(), &out);lines 1481–1481◇ if (out != nullptr)lines 1486–1486msg.content = mcp::sanitize_utf8(out);lines 1487–1487free(out);

Requirements

REQ-MCP-017

fire_pre_tool_hook

bool entropic::ToolExecutor::fire_pre_tool_hook(const LoopContext &ctx, ToolCall &call)

Fire PRE_TOOL_CALL hook; returns true if cancelled.

src/mcp/tool_executor.cpp:1249

Source · 14 lines
bool ToolExecutor::fire_pre_tool_hook(
    const LoopContext& ctx, ToolCall& call) {
    if (hook_iface_.fire_pre == nullptr) { return false; }
    auto json = build_pre_tool_json(call, ctx.locked_tier,
                                    ctx.metrics.iterations);
    char* mod = nullptr;
    int rc = hook_iface_.fire_pre(hook_iface_.registry,
        ENTROPIC_HOOK_PRE_TOOL_CALL, json.c_str(), &mod);
    if (mod != nullptr) {
        if (rc == 0) { apply_pre_tool_modification(call, mod); }
        free(mod);
    }
    return rc != 0;
}
Activity · 10 steps
lines 1251–1251◇ if (hook_iface_.fire_pre == nullptr)lines 1251–1251return false;lines 1252–1253auto json = build_pre_tool_json(call, ctx.locked_tier, ctx.metrics.iterations);lines 1254–1254char* mod = nullptr;lines 1255–1256int rc = hook_iface_.fire_pre(hook_iface_.registry, ENTROPIC_HOOK_PRE_TOOL_CALL, json.c_str(), &mod);lines 1257–1257◇ if (mod != nullptr)lines 1258–1258◇ if (rc == 0)lines 1258–1258apply_pre_tool_modification(call, mod);lines 1259–1259free(mod);lines 1261–1261return rc != 0;

Requirements

REQ-MCP-017

handle_duplicate

Message entropic::ToolExecutor::handle_duplicate(LoopContext &ctx, const ToolCall &call, const std::string &previous_result)

Handle duplicate: increment counter, build feedback message.

src/mcp/tool_executor.cpp:197

Source · 13 lines
Message ToolExecutor::handle_duplicate(
    LoopContext& ctx,
    const ToolCall& call,
    const std::string& previous_result) {
    ctx.consecutive_duplicate_attempts++;
    logger->warn("Duplicate tool call #{}: {}",
                 ctx.consecutive_duplicate_attempts, call.name);

    if (ctx.consecutive_duplicate_attempts >= 3) {
        return create_circuit_breaker_message();
    }
    return create_duplicate_message(call, previous_result);
}
Activity · 5 steps
lines 201–201ctx.consecutive_duplicate_attempts++;lines 202–203logger->warn("Duplicate tool call #{}: {}", ctx.consecutive_duplicate_attempts, call.name);lines 205–205◇ if (ctx.consecutive_duplicate_attempts >= 3)lines 206–206return create_circuit_breaker_message();lines 208–208return create_duplicate_message(call, previous_result);

Requirements

REQ-MCP-015

parse_tool_result_text

static std::string entropic::parse_tool_result_text(const std::string &result_json)

Extract the "result" text from an MCP result JSON envelope.

src/mcp/tool_executor.cpp:484

Source · 8 lines
static std::string parse_tool_result_text(const std::string& result_json) {
    try {
        auto j = nlohmann::json::parse(result_json);
        return j.value("result", result_json);
    } catch (...) {
        return result_json;
    }
}
Activity · 1 steps
lines 485–490try { auto j = nlohmann::json::parse(result_json); return j.value("result", result_json); } catch (...) { return result_json; }

Requirements

REQ-MCP-002

process_single_call

std::vector< Message > entropic::ToolExecutor::process_single_call(LoopContext &ctx, const ToolCall &incoming)

Process a single tool call (precondition check + execute).

src/mcp/tool_executor.cpp:978

Source · 40 lines
std::vector<Message> ToolExecutor::process_single_call(
    LoopContext& ctx, const ToolCall& incoming) {
    // gh#168 (v2.13.0): the PRE_TOOL_CALL hook may rewrite the call's
    // ARGUMENTS, so the executor works on its own copy — preconditions,
    // dispatch, the dup cache and the POST hook all then see one
    // consistent call rather than the model's superseded version.
    ToolCall call = incoming;
    // Hook: PRE_TOOL_CALL first — fires for every attempt, including
    // those that a precondition will reject. (E9, 2.0.6-rc19)
    if (fire_pre_tool_hook(ctx, call)) {
        auto msg = create_denied_message(call, "Cancelled by hook");
        // gh#84 (v2.5.1): stamp kind so the engine treats this as a
        // non-progress outcome for the thinking-budget reset.
        msg.metadata["result_kind"] =
            result_kind_to_string(ToolResultKind::rejected_precondition);
        fire_post_tool_hook(ctx, call, "", 0.0,
            ToolResultKind::rejected_precondition, msg);
        return {std::move(msg)};
    }

    auto pc = check_call_preconditions(ctx, call);
    if (pc.rejection.has_value()) {
        logger->info("Tool '{}' rejected by precondition (kind={})",
                     call.name, result_kind_to_string(pc.kind));
        // gh#84 (v2.5.1): stamp kind for the engine's budget decision.
        pc.rejection->metadata["result_kind"] =
            result_kind_to_string(pc.kind);
        fire_post_tool_hook(ctx, call, "", 0.0, pc.kind, *pc.rejection);
        return {std::move(*pc.rejection)};
    }

    auto exec_start = std::chrono::steady_clock::now();
    auto [msg, raw_result] = execute_tool(ctx, call);
    auto exec_ms = std::chrono::duration<double, std::milli>(
        std::chrono::steady_clock::now() - exec_start).count();

    finalize_tool_call(ctx, call, msg, raw_result, exec_ms);

    return {std::move(msg)};
}
Activity · 17 steps
lines 984–984ToolCall call = incoming;lines 987–987◇ if (fire_pre_tool_hook(ctx, call))lines 988–988auto msg = create_denied_message(call, "Cancelled by hook");lines 991–992msg.metadata["result_kind"] = result_kind_to_string(ToolResultKind::rejected_precondition);lines 993–994fire_post_tool_hook(ctx, call, "", 0.0, ToolResultKind::rejected_precondition, msg);lines 995–995return {std::move(msg)};lines 998–998auto pc = check_call_preconditions(ctx, call);lines 999–999◇ if (pc.rejection.has_value())lines 1000–1001logger->info("Tool '{}' rejected by precondition (kind={})", call.name, result_kind_to_string(pc.kind));lines 1003–1004pc.rejection->metadata["result_kind"] = result_kind_to_string(pc.kind);lines 1005–1005fire_post_tool_hook(ctx, call, "", 0.0, pc.kind, *pc.rejection);lines 1006–1006return {std::move(*pc.rejection)};lines 1009–1009auto exec_start = std::chrono::steady_clock::now();lines 1010–1010auto [msg, raw_result] = execute_tool(ctx, call);lines 1011–1012auto exec_ms = std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now() - exec_start).count();lines 1014–1014finalize_tool_call(ctx, call, msg, raw_result, exec_ms);lines 1016–1016return {std::move(msg)};

Requirements

REQ-MCP-012 REQ-MCP-017

process_tool_calls

std::vector< Message > entropic::ToolExecutor::process_tool_calls(LoopContext &ctx, const std::vector< ToolCall > &tool_calls)

Process a batch of tool calls.

src/mcp/tool_executor.cpp:100

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, child_reads_plan, dispatch, run_with_pre_mod

Calls call, fire_state_callback, process_single_call, should_stop_batch, sort_tool_calls, truncate_to_limit

Source · 27 lines
std::vector<Message> ToolExecutor::process_tool_calls(
    LoopContext& ctx,
    const std::vector<ToolCall>& tool_calls) {
    logger->info("Processing {} tool calls", tool_calls.size());
    ctx.state = AgentState::WAITING_TOOL;
    fire_state_callback(ctx);

    auto limited = sort_tool_calls(tool_calls);
    int eff_limit = ctx.effective_max_tool_calls_per_turn >= 0
        ? ctx.effective_max_tool_calls_per_turn
        : loop_config_.max_tool_calls_per_turn;
    truncate_to_limit(limited, eff_limit);

    std::vector<Message> results;
    for (const auto& call : limited) {
        auto msgs = process_single_call(ctx, call);
        for (auto& m : msgs) {
            results.push_back(std::move(m));
        }
        if (should_stop_batch(ctx, results)) {
            break;
        }
    }

    ctx.consecutive_errors = 0;
    return results;
}
Activity · 15 steps
lines 103–103logger->info("Processing {} tool calls", tool_calls.size());lines 104–104ctx.state = AgentState::WAITING_TOOL;lines 105–105fire_state_callback(ctx);lines 107–107auto limited = sort_tool_calls(tool_calls);lines 108–110int eff_limit = ctx.effective_max_tool_calls_per_turn >= 0 ? ctx.effective_max_tool_calls_per_turn : loop_config_.max_tool_calls_per_turn;lines 111–111truncate_to_limit(limited, eff_limit);lines 113–113std::vector<Message> results;lines 114–114◇ for (const auto& call : limited)lines 115–115auto msgs = process_single_call(ctx, call);lines 116–116◇ for (auto& m : msgs)lines 117–117results.push_back(std::move(m));lines 119–119◇ if (should_stop_batch(ctx, results))lines 120–120break;lines 124–124ctx.consecutive_errors = 0;lines 125–125return results;

Requirements

REQ-MCP-012

record_tool_call

void entropic::ToolExecutor::record_tool_call(LoopContext &ctx, const ToolCall &call, const std::string &result)

Record tool call for duplicate detection (skip errors).

src/mcp/tool_executor.cpp:657

Source · 30 lines
void ToolExecutor::record_tool_call(
    LoopContext& ctx,
    const ToolCall& call,
    const std::string& result) {
    // Extract result text from JSON envelope
    std::string text = result;
    try {
        auto j = nlohmann::json::parse(result);
        text = j.value("result", result);
    } catch (...) {}

    auto key = tool_call_key(call);

    // Don't cache error results — but do COUNT them (v2.13.0). Caching the
    // text would poison a transient failure for the rest of the turn,
    // which v1.8.5 rightly avoided; counting bounds the repeat without
    // taking the retry away. check_repeated_failure reads this.
    // gh#190 (v2.14.0): ONE error classifier for every site. This used to
    // match only an "Error:" prefix, so a structured {"error": ...} result
    // read as success — it cleared the failure count and was cached.
    if (mcp::looks_like_tool_error(text)) {
        ctx.failed_tool_calls[key]++;
        return;
    }
    // A success clears the failure history for this exact call: whatever
    // was wrong is no longer wrong, and a later failure deserves its own
    // retry rather than inheriting a spent budget.
    ctx.failed_tool_calls.erase(key);
    ctx.recent_tool_calls[key] = text;
}
Activity · 8 steps
lines 662–662std::string text = result;lines 663–666try { auto j = nlohmann::json::parse(result); text = j.value("result", result); } catch (...) {}lines 668–668auto key = tool_call_key(call);lines 677–677◇ if (mcp::looks_like_tool_error(text))lines 678–678ctx.failed_tool_calls[key]++;lines 679–679return;lines 684–684ctx.failed_tool_calls.erase(key);lines 685–685ctx.recent_tool_calls[key] = text;

Requirements

REQ-MCP-015

record_tool_history

void entropic::ToolExecutor::record_tool_history(const ToolCall &call, const std::string &args_json, const std::string &result_text, long long ms, int iteration)

Stash a finished tool call in the history ring buffer.

src/mcp/tool_executor.cpp:606

Source · 15 lines
void ToolExecutor::record_tool_history(const ToolCall& call,
                                       const std::string& args_json,
                                       const std::string& result_text,
                                       long long ms, int iteration) {
    ToolCallRecord rec;
    rec.sequence = ++history_seq_;
    rec.tool_name = call.name;
    rec.params_summary = summarize_params(args_json);
    rec.status = mcp::looks_like_tool_error(result_text)  // gh#190: one classifier
        ? "error" : "success";
    rec.result_summary = truncate_result(result_text, 200);
    rec.elapsed_ms = static_cast<double>(ms);
    rec.iteration = iteration;
    history_.record(rec);
}
Activity · 9 steps
lines 610–610ToolCallRecord rec;lines 611–611rec.sequence = ++history_seq_;lines 612–612rec.tool_name = call.name;lines 613–613rec.params_summary = summarize_params(args_json);lines 614–615rec.status = mcp::looks_like_tool_error(result_text) // gh#190: one classifier ? "error" : "success";lines 616–616rec.result_summary = truncate_result(result_text, 200);lines 617–617rec.elapsed_ms = static_cast<double>(ms);lines 618–618rec.iteration = iteration;lines 619–619history_.record(rec);

Requirements

REQ-MCP-020

serialize_args

std::string entropic::ToolExecutor::serialize_args(const ToolCall &call)

Serialize tool call arguments to JSON.

src/mcp/tool_executor.cpp:1611

Source · 10 lines
std::string ToolExecutor::serialize_args(const ToolCall& call) {
    if (!call.arguments_json.empty()) {
        return call.arguments_json;
    }
    nlohmann::json args = nlohmann::json::object();
    for (const auto& [k, v] : call.arguments) {
        args[k] = v;
    }
    return args.dump();
}
Activity · 6 steps
lines 1612–1612◇ if (!call.arguments_json.empty())lines 1613–1613return call.arguments_json;lines 1615–1615nlohmann::json args = nlohmann::json::object();lines 1616–1616◇ for (const auto& [k, v] : call.arguments)lines 1617–1617args[k] = v;lines 1619–1619return args.dump();

Requirements

REQ-MCP-013

servers_for

ServerManager & entropic::ToolExecutor::servers_for(const std::string &session_key) const

The servers a session's tool call must run against (gh#166).

src/mcp/tool_executor.cpp:64

Source · 8 lines
ServerManager& ToolExecutor::servers_for(
    const std::string& session_key) const {
    if (server_resolver_ != nullptr) {
        auto* resolved = server_resolver_(session_key, server_resolver_data_);
        if (resolved != nullptr) { return *resolved; }
    }
    return server_manager_;
}
Activity · 5 steps
lines 66–66◇ if (server_resolver_ != nullptr)lines 67–67auto* resolved = server_resolver_(session_key, server_resolver_data_);lines 68–68◇ if (resolved != nullptr)lines 68–68return *resolved;lines 70–70return server_manager_;

Requirements

REQ-MCP-027

set_server_resolver

void entropic::ToolExecutor::set_server_resolver(ServerManager *(*fn)(const std::string &session_key, void *user_data), void *user_data)

Resolve a session's MCP servers (gh#166, v2.13.0).

src/mcp/tool_executor.cpp:51

Source · 5 lines
void ToolExecutor::set_server_resolver(
    ServerManager* (*fn)(const std::string&, void*), void* user_data) {
    server_resolver_ = fn;
    server_resolver_data_ = user_data;
}
Activity · 2 steps
lines 53–53server_resolver_ = fn;lines 54–54server_resolver_data_ = user_data;

Requirements

REQ-MCP-027

should_stop_batch

bool entropic::ToolExecutor::should_stop_batch(const LoopContext &ctx, const std::vector< Message > &results) const

Check if batch should stop.

src/mcp/tool_executor.cpp:1499

Source · 8 lines
bool ToolExecutor::should_stop_batch(
    const LoopContext& ctx,
    const std::vector<Message>& /*results*/) const {
    return ctx.state == AgentState::COMPLETE
        || ctx.pending_delegation.has_value()
        || ctx.pending_pipeline.has_value()
        || ctx.consecutive_duplicate_attempts >= 3;
}
Activity · 1 steps
lines 1502–1505return ctx.state == AgentState::COMPLETE || ctx.pending_delegation.has_value() || ctx.pending_pipeline.has_value() || ctx.consecutive_duplicate_attempts >= 3;

Requirements

REQ-MCP-012

sort_tool_calls

std::vector< ToolCall > entropic::ToolExecutor::sort_tool_calls(const std::vector< ToolCall > &calls)

Sort tool calls so entropic.delegate is always last.

src/mcp/tool_executor.cpp:140

Source · 11 lines
std::vector<ToolCall> ToolExecutor::sort_tool_calls(
    const std::vector<ToolCall>& calls) {
    auto sorted = calls;
    std::stable_sort(sorted.begin(), sorted.end(),
        [](const ToolCall& a, const ToolCall& b) {
            bool a_delegate = (a.name == "entropic.delegate");
            bool b_delegate = (b.name == "entropic.delegate");
            return !a_delegate && b_delegate;
        });
    return sorted;
}
Activity · 3 steps
lines 142–142auto sorted = calls;lines 143–148std::stable_sort(sorted.begin(), sorted.end(), [](const ToolCall& a, const ToolCall& b) { bool a_delegate = (a.name == "entropic.delegate"); bool b_delegate = (b.name == "entropic.delegate"); return !a_delegate && b_delegate; });lines 149–149return sorted;

Requirements

REQ-MCP-012

tool_call_key

std::string entropic::ToolExecutor::tool_call_key(const ToolCall &call)

Generate duplicate detection key: name + sorted args.

src/mcp/tool_executor.cpp:634

Source · 10 lines
std::string ToolExecutor::tool_call_key(const ToolCall& call) {
    // Sort arguments for consistent key. gh#143: seed an OBJECT, not a
    // default-constructed null — an argument-free call would otherwise
    // key as "<name>:null" instead of "<name>:{}".
    nlohmann::json args = nlohmann::json::object();
    for (const auto& [k, v] : call.arguments) {
        args[k] = v;
    }
    return call.name + ":" + args.dump();
}
Activity · 4 steps
lines 638–638nlohmann::json args = nlohmann::json::object();lines 639–639◇ for (const auto& [k, v] : call.arguments)lines 640–640args[k] = v;lines 642–642return call.name + ":" + args.dump();

Requirements

REQ-MCP-015

truncate_to_limit

void entropic::ToolExecutor::truncate_to_limit(std::vector< ToolCall > &calls, int limit) const

Truncate to effective per-turn call limit.

src/mcp/tool_executor.cpp:763

Source · 8 lines
void ToolExecutor::truncate_to_limit(
    std::vector<ToolCall>& calls,
    int limit) const {
    auto lim = static_cast<size_t>(limit);
    if (calls.size() > lim) {
        calls.resize(lim);
    }
}
Activity · 3 steps
lines 766–766auto lim = static_cast<size_t>(limit);lines 767–767◇ if (calls.size() > lim)lines 768–768calls.resize(lim);

Requirements

REQ-MCP-012

update_anti_spiral_tracking

void entropic::ToolExecutor::update_anti_spiral_tracking(LoopContext &ctx, const std::string &tool_name)

Update anti-spiral tracking for a just-dispatched tool.

src/mcp/tool_executor.cpp:1293

Source · 17 lines
void ToolExecutor::update_anti_spiral_tracking(
    LoopContext& ctx, const std::string& tool_name) {
    if (tool_name == ctx.last_tool_name) {
        ++ctx.consecutive_same_tool_calls;
    } else {
        ctx.last_tool_name = tool_name;
        ctx.consecutive_same_tool_calls = 1;
    }
    if (ctx.consecutive_same_tool_calls
            >= loop_config_.max_consecutive_same_tool) {
        ctx.pending_anti_spiral_warning =
            tool_name + " has been called "
            + std::to_string(ctx.consecutive_same_tool_calls)
            + " times consecutively; pivot to a different tool or "
              "complete the task next turn.";
    }
}
Activity · 7 steps
lines 1295–1295◇ if (tool_name == ctx.last_tool_name)lines 1296–1296++ctx.consecutive_same_tool_calls;lines 1297–1297elselines 1298–1298ctx.last_tool_name = tool_name;lines 1299–1299ctx.consecutive_same_tool_calls = 1;lines 1301–1302◇ if (ctx.consecutive_same_tool_calls >= loop_config_.max_consecutive_same_tool)lines 1303–1307ctx.pending_anti_spiral_warning = tool_name + " has been called " + std::to_string(ctx.consecutive_same_tool_calls) + " times consecutively; pivot to a different tool or " "complete the task next turn.";

Requirements

REQ-MCP-016

validate_tool_args

static std::string entropic::validate_tool_args(const std::string &schema_json, const nlohmann::json &args)

Validate tool arguments against the tool's JSON Schema.

src/mcp/tool_executor.cpp:457

Source · 17 lines
static std::string validate_tool_args(
    const std::string& schema_json,
    const nlohmann::json& args)
{
    auto schema = nlohmann::json::parse(schema_json, nullptr, false);
    if (!schema.is_object()) { return ""; }

    auto err = check_required_fields(schema, args);
    auto props = schema.value("properties", nlohmann::json::object());
    for (auto it = props.begin(); it != props.end() && err.empty(); ++it) {
        if (args.contains(it.key())) {
            err = check_property_constraints(
                it.key(), it.value(), args[it.key()]);
        }
    }
    return err;
}
Activity · 9 steps
lines 461–461auto schema = nlohmann::json::parse(schema_json, nullptr, false);lines 462–462◇ if (!schema.is_object())lines 462–462return "";lines 464–464auto err = check_required_fields(schema, args);lines 465–465auto props = schema.value("properties", nlohmann::json::object());lines 466–466◇ for (auto it = props.begin(); it != props.end() && err.empty(); ++it)lines 467–467◇ if (args.contains(it.key()))lines 468–469err = check_property_constraints( it.key(), it.value(), args[it.key()]);lines 472–472return err;

Requirements

REQ-MCP-013