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
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
Requirements
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
Requirements
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
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
Requirements
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
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
Requirements
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
Requirements
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
Requirements
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
Called by check_spiral_blocks
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
Requirements
check_approval
bool entropic::ToolExecutor::check_approval(const ToolCall &call)
Check tool approval (auto/allow-list/callback/deny).
src/mcp/tool_executor.cpp:228
Called by check_approval_pc, check_dup_or_approval
Calls is_explicitly_allowed, requires_approval, serialize_args, serialize_tool_call
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
Requirements
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
Requirements
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
Called by process_single_call
Calls check_approval_pc, check_duplicate, check_mcp_authorization, check_schema, check_spiral_blocks, check_tier_allowed, handle_duplicate
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
Requirements
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
Called by none
Calls check_approval, check_duplicate, create_denied_message, handle_duplicate
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
Requirements
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
Called by check_call_preconditions, check_dup_or_approval
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
Requirements
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
Requirements
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
Called by check_call_preconditions
Calls check_access, get_required_access_level, is_enforced, mcp_access_level_name, tag_tool_result
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
check_schema
std::optional< Message > entropic::ToolExecutor::check_schema(const ToolCall &call)
Validate tool arguments against schema constraints.
src/mcp/tool_executor.cpp:873
Called by check_call_preconditions
Calls create_denied_message, get_tool_schema, serialize_args, validate_tool_args
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
Requirements
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
Called by check_call_preconditions
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Called by check_anti_spiral_hard_block, check_approval_pc, check_dup_or_approval, check_repeated_failure, check_schema, check_tier_allowed, process_single_call
Calls tag_tool_result
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
Requirements
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
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
Requirements
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
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
Requirements
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
Requirements
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
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Called by process_single_call
Calls apply_result_size_cap, classify_tool_result, extract_and_process_directives, fire_post_tool_hook, log_tool_call, record_tool_call, result_kind_to_string, run_post_tool_hooks, update_anti_spiral_tracking
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
Requirements
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
Called by finalize_tool_call, process_single_call
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
Requirements
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
Called by process_single_call
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
Requirements
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
Called by check_call_preconditions, check_dup_or_approval
Calls create_circuit_breaker_message, create_duplicate_message
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
Requirements
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
Requirements
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
Called by process_tool_calls
Calls check_call_preconditions, create_denied_message, execute_tool, finalize_tool_call, fire_post_tool_hook, fire_pre_tool_hook, result_kind_to_string
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
Requirements
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
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
Requirements
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
Requirements
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
Called by execute_tool
Calls looks_like_tool_error, record, summarize_params, truncate_result
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
Requirements
serialize_args
std::string entropic::ToolExecutor::serialize_args(const ToolCall &call)
Serialize tool call arguments to JSON.
src/mcp/tool_executor.cpp:1611
Called by build_post_tool_json, build_pre_tool_json, check_approval, check_schema, execute_tool, log_tool_call
Calls none
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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;
}