Entropic 2.9.4
Local-first agentic inference engine
Loading...
Searching...
No Matches
tool_executor.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
12
13#include <nlohmann/json.hpp>
14
15#include <algorithm>
16#include <chrono>
17#include <memory>
18#include <optional>
19
20static auto logger = entropic::log::get("mcp.tool_executor");
21
22namespace entropic {
23
34 ServerManager& server_manager,
35 const LoopConfig& loop_config,
36 EngineCallbacks& callbacks,
38 : server_manager_(server_manager),
39 loop_config_(loop_config),
40 callbacks_(callbacks),
41 hooks_(hooks) {}
42
50 const PermissionPersistInterface& persist) {
51 permission_persist_ = persist;
52}
53
63 LoopContext& ctx,
64 const std::vector<ToolCall>& tool_calls) {
65 logger->info("Processing {} tool calls", tool_calls.size());
66 ctx.state = AgentState::WAITING_TOOL;
67 fire_state_callback(ctx);
68
69 auto limited = sort_tool_calls(tool_calls);
70 int eff_limit = ctx.effective_max_tool_calls_per_turn >= 0
72 : loop_config_.max_tool_calls_per_turn;
73 truncate_to_limit(limited, eff_limit);
74
75 std::vector<Message> results;
76 for (const auto& call : limited) {
77 auto msgs = process_single_call(ctx, call);
78 for (auto& m : msgs) {
79 results.push_back(std::move(m));
80 }
81 if (should_stop_batch(ctx, results)) {
82 break;
83 }
84 }
85
86 ctx.consecutive_errors = 0;
87 return results;
88}
89
97std::vector<ToolCall> ToolExecutor::sort_tool_calls(
98 const std::vector<ToolCall>& calls) {
99 auto sorted = calls;
100 std::stable_sort(sorted.begin(), sorted.end(),
101 [](const ToolCall& a, const ToolCall& b) {
102 bool a_delegate = (a.name == "entropic.delegate");
103 bool b_delegate = (b.name == "entropic.delegate");
104 return !a_delegate && b_delegate;
105 });
106 return sorted;
107}
108
117std::string ToolExecutor::check_duplicate(
118 const LoopContext& ctx,
119 const ToolCall& call) const {
120 if (server_manager_.skip_duplicate_check(call.name)) {
121 return "";
122 }
123 auto key = tool_call_key(call);
124 auto it = ctx.recent_tool_calls.find(key);
125 if (it != ctx.recent_tool_calls.end()) {
126 return it->second;
127 }
128 return "";
129}
130
140Message ToolExecutor::handle_duplicate(
141 LoopContext& ctx,
142 const ToolCall& call,
143 const std::string& previous_result) {
144 ctx.consecutive_duplicate_attempts++;
145 logger->warn("Duplicate tool call #{}: {}",
146 ctx.consecutive_duplicate_attempts, call.name);
147
148 if (ctx.consecutive_duplicate_attempts >= 3) {
149 return create_circuit_breaker_message();
150 }
151 return create_duplicate_message(call, previous_result);
152}
153
161bool ToolExecutor::check_approval(const ToolCall& call) {
162 auto args_json = serialize_args(call);
163 bool auto_ok = loop_config_.auto_approve_tools
164 || server_manager_.is_explicitly_allowed(
165 call.name, args_json);
166
167 bool approved = auto_ok;
168 if (!approved && callbacks_.on_tool_call != nullptr) {
169 auto call_json = serialize_tool_call(call);
170 callbacks_.on_tool_call(call_json.c_str(),
171 callbacks_.user_data);
172 approved = true;
173 }
174
175 // Hook: ON_PERMISSION_CHECK — informational (v1.9.1)
176 if (hook_iface_.fire_info != nullptr) {
177 std::string perm = approved ? "allowed" : "denied";
178 std::string json = "{\"tool_name\":\""
179 + call.name + "\",\"permission\":\"" + perm + "\"}";
180 hook_iface_.fire_info(hook_iface_.registry,
182 }
183
184 if (!approved) {
185 logger->warn("No approval callback — denying: {}", call.name);
186 }
187 return approved;
188}
189
198std::optional<Message> ToolExecutor::check_tier_allowed(
199 const LoopContext& ctx, const ToolCall& call) const {
200 // gh#83 (v2.5.2): enforce the locked tier's allowed_tools at
201 // dispatch — not just at prompt-injection time. Without this a
202 // model that emits an off-allowlist call (hallucinated, learned,
203 // or cross-tier) has it dispatched normally; tier isolation was
204 // advisory only. Pass through when: no tier locked, no map wired,
205 // or the tier declares no allowlist (unrestricted).
206 if (ctx.locked_tier.empty() || tier_allowed_tools_ == nullptr) {
207 return std::nullopt;
208 }
209 auto it = tier_allowed_tools_->find(ctx.locked_tier);
210 // Authorized when: tier has no allowlist entry, an empty allowlist
211 // (unrestricted), or the call is in the list. Short-circuit eval
212 // guards the `it->second` access against the end() case.
213 bool authorized = it == tier_allowed_tools_->end()
214 || it->second.empty()
215 || std::find(it->second.begin(), it->second.end(),
216 call.name) != it->second.end();
217 if (authorized) {
218 return std::nullopt;
219 }
220 logger->warn("Tool '{}' not in tier '{}' allowed_tools — rejecting",
221 call.name, ctx.locked_tier);
222 return create_denied_message(
223 call, "tier '" + ctx.locked_tier + "' is not authorized to call '"
224 + call.name + "'");
225}
226
235static std::string check_required_fields(
236 const nlohmann::json& schema,
237 const nlohmann::json& args)
238{
239 for (const auto& req : schema.value("required",
240 nlohmann::json::array())) {
241 if (!args.contains(req.get<std::string>())) {
242 return "Missing required argument: "
243 + req.get<std::string>();
244 }
245 }
246 return "";
247}
248
267static std::string check_enum(
268 const std::string& key,
269 const nlohmann::json& allowed,
270 const nlohmann::json& val)
271{
272 for (const auto& e : allowed) {
273 if (e == val) { return ""; }
274 }
275 return "Invalid value for '" + key + "': "
276 + val.dump() + ". Must be one of: " + allowed.dump();
277}
278
288static std::string check_type(
289 const std::string& key,
290 const std::string& type,
291 const nlohmann::json& val)
292{
293 bool ok = (type == "string" && val.is_string())
294 || (type == "integer" && val.is_number_integer())
295 || (type == "number" && val.is_number())
296 || (type == "boolean" && val.is_boolean())
297 || (type == "array" && val.is_array())
298 || (type == "object" && val.is_object());
299 return ok ? "" : "Type mismatch for '" + key
300 + "': expected " + type;
301}
302
312static std::string check_property_constraints(
313 const std::string& key,
314 const nlohmann::json& prop,
315 const nlohmann::json& val)
316{
317 if (prop.contains("enum")) {
318 auto err = check_enum(key, prop["enum"], val);
319 if (!err.empty()) { return err; }
320 }
321 if (!prop.contains("type")) { return ""; }
322 return check_type(key, prop["type"].get<std::string>(), val);
323}
324
337static std::string validate_tool_args(
338 const std::string& schema_json,
339 const nlohmann::json& args)
340{
341 auto schema = nlohmann::json::parse(schema_json, nullptr, false);
342 if (!schema.is_object()) { return ""; }
343
344 auto err = check_required_fields(schema, args);
345 auto props = schema.value("properties", nlohmann::json::object());
346 for (auto it = props.begin(); it != props.end() && err.empty(); ++it) {
347 if (args.contains(it.key())) {
349 it.key(), it.value(), args[it.key()]);
350 }
351 }
352 return err;
353}
354
362static std::string parse_tool_result_text(const std::string& result_json) {
363 try {
364 auto j = nlohmann::json::parse(result_json);
365 return j.value("result", result_json);
366 } catch (...) {
367 return result_json;
368 }
369}
370
379std::pair<Message, std::string> ToolExecutor::execute_tool(
380 LoopContext& ctx, const ToolCall& call) {
381
382 auto args_json = serialize_args(call);
383
384 if (callbacks_.on_tool_start != nullptr) {
385 auto call_json = serialize_tool_call(call);
386 callbacks_.on_tool_start(call_json.c_str(),
387 callbacks_.user_data);
388 }
389
390 auto start = std::chrono::steady_clock::now();
391 // Inbound boundary from MCP server subprocess. v2.1.0 (#47) introduced
392 // this; v2.1.1 (#3) generalized it as one of several boundary-policy
393 // sanitize sites — see include/entropic/mcp/utf8_sanitize.h for the
394 // full policy. The earlier "trust downstream" assumption was wrong:
395 // bytes also enter via the model token stream and the audit-replay
396 // path; both now sanitize at their own boundaries.
397 auto result_json = mcp::sanitize_utf8(
398 server_manager_.execute(call.name, args_json));
399 auto end = std::chrono::steady_clock::now();
400 auto ms = std::chrono::duration_cast<
401 std::chrono::milliseconds>(end - start).count();
402
403 ctx.metrics.tool_calls++;
404
405 std::string result_text = parse_tool_result_text(result_json);
406
407 // P1-11 (2.0.6-rc16): stash into history ring buffer so the
408 // constitutional validator revision prompt (and diagnostic tools)
409 // can surface prior-iteration tool calls without re-reading
410 // messages[].
411 record_tool_history(call, args_json, result_text, ms,
412 ctx.metrics.iterations);
413
414 fire_tool_complete_callback(call, result_text, ms);
415
416 Message msg;
417 msg.role = "user";
418 msg.content = result_text;
419 msg.metadata["tool_call_id"] = call.id;
420 msg.metadata["tool_name"] = call.name;
421
422 return {std::move(msg), result_json};
423}
424
435void ToolExecutor::record_tool_history(const ToolCall& call,
436 const std::string& args_json,
437 const std::string& result_text,
438 long long ms, int iteration) {
439 ToolCallRecord rec;
440 rec.sequence = ++history_seq_;
441 rec.tool_name = call.name;
442 rec.params_summary = summarize_params(args_json);
443 rec.status = (result_text.rfind("error", 0) == 0)
444 ? "error" : "success";
445 rec.result_summary = truncate_result(result_text, 200);
446 rec.elapsed_ms = static_cast<double>(ms);
447 rec.iteration = iteration;
448 history_.record(rec);
449}
450
458std::string ToolExecutor::tool_call_key(const ToolCall& call) {
459 // Sort arguments for consistent key
460 nlohmann::json args;
461 for (const auto& [k, v] : call.arguments) {
462 args[k] = v;
463 }
464 return call.name + ":" + args.dump();
465}
466
475void ToolExecutor::record_tool_call(
476 LoopContext& ctx,
477 const ToolCall& call,
478 const std::string& result) {
479 // Extract result text from JSON envelope
480 std::string text = result;
481 try {
482 auto j = nlohmann::json::parse(result);
483 text = j.value("result", result);
484 } catch (...) {}
485
486 // Don't cache error results
487 if (text.find("Error:") == 0 || text.find("error:") == 0) {
488 return;
489 }
490 auto key = tool_call_key(call);
491 ctx.recent_tool_calls[key] = text;
492}
493
502Message ToolExecutor::create_denied_message(
503 const ToolCall& call,
504 const std::string& reason) {
505 Message msg;
506 msg.role = "user";
507 msg.content =
508 "Tool `" + call.name + "` was denied: " + reason + "\n\n"
509 "This tool is not available to you. Do NOT retry it. "
510 "Use a different approach to accomplish your task.";
511 return msg;
512}
513
522Message ToolExecutor::create_error_message(
523 const ToolCall& call,
524 const std::string& error) {
525 Message msg;
526 msg.role = "user";
527 msg.content =
528 "Tool `" + call.name + "` failed with error: " + error +
529 "\n\nRECOVERY:\n"
530 "- Check arguments are correct\n"
531 "- Try a different approach\n"
532 "- Do NOT retry with the same arguments";
533 return msg;
534}
535
536// ── Private helpers ──────────────────────────────────────
537
544void ToolExecutor::fire_state_callback(const LoopContext& ctx) {
545 if (callbacks_.on_state_change != nullptr) {
546 callbacks_.on_state_change(
547 static_cast<int>(ctx.state), callbacks_.user_data);
548 }
549}
550
558void ToolExecutor::truncate_to_limit(
559 std::vector<ToolCall>& calls,
560 int limit) const {
561 auto lim = static_cast<size_t>(limit);
562 if (calls.size() > lim) {
563 calls.resize(lim);
564 }
565}
566
575std::optional<Message> ToolExecutor::check_mcp_authorization(
576 const LoopContext& ctx,
577 const ToolCall& call) const {
578 if (auth_mgr_ == nullptr) {
579 return std::nullopt;
580 }
581 auto identity = ctx.locked_tier.empty()
582 ? "lead" : ctx.locked_tier;
583 auto required = server_manager_.get_required_access_level(
584 call.name);
585 if (!auth_mgr_->is_enforced(identity) ||
586 auth_mgr_->check_access(identity, call.name, required)) {
587 return std::nullopt;
588 }
589 auto level_str = mcp_access_level_name(required);
590 logger->warn("MCP key denied: {} requires {} for {}",
591 call.name, level_str, identity);
592 Message msg;
593 msg.role = "user";
594 msg.content =
595 "Tool `" + call.name + "` was denied: identity `"
596 + identity + "` lacks " + level_str
597 + " access.\n\n"
598 "Your MCP key set does not authorize this tool. "
599 "Use `entropic.delegate` to hand off to an identity "
600 "that has the required access.";
601 return msg;
602}
603
612std::optional<Message> ToolExecutor::check_dup_or_approval(
613 LoopContext& ctx, const ToolCall& call) {
614 auto dup_result = check_duplicate(ctx, call);
615 if (!dup_result.empty()) {
616 return handle_duplicate(ctx, call, dup_result);
617 }
618 ctx.consecutive_duplicate_attempts = 0;
619 return check_approval(call)
620 ? std::nullopt
621 : std::optional{create_denied_message(
622 call, "Permission denied")};
623}
624
640std::optional<Message> ToolExecutor::check_schema(
641 const ToolCall& call) {
642 auto schema = server_manager_.get_tool_schema(call.name);
643 if (schema.empty()) { return std::nullopt; }
644 auto args = nlohmann::json::parse(
645 serialize_args(call), nullptr, false);
646 auto err = args.is_discarded()
647 ? std::string{} : validate_tool_args(schema, args);
648 if (err.empty()) { return std::nullopt; }
649 logger->warn("Tool '{}' argument validation failed: {}",
650 call.name, err);
651 return create_denied_message(call, err);
652}
653
667PreconditionCheck ToolExecutor::check_call_preconditions(
668 LoopContext& ctx, const ToolCall& call) {
669 // Issue #14 (v2.1.4): anti-spiral hard block fires FIRST. Cheaper
670 // than schema/auth checks and short-circuits a tool that the
671 // engine has decided to refuse, regardless of whether the call
672 // would otherwise pass other preconditions.
673 PreconditionCheck pc = check_anti_spiral_hard_block(ctx, call);
674 if (pc.rejection.has_value()) {
675 return pc;
676 }
677 if (auto r = check_schema(call); r.has_value()) {
678 pc.rejection = std::move(r);
680 } else if (auto a = check_mcp_authorization(ctx, call);
681 a.has_value()) {
682 pc.rejection = std::move(a);
684 } else if (auto t = check_tier_allowed(ctx, call); t.has_value()) {
685 pc.rejection = std::move(t);
686 pc.kind = ToolResultKind::rejected_unauthorized; // gh#83
687 } else if (auto dup = check_duplicate(ctx, call); !dup.empty()) {
688 pc.rejection = handle_duplicate(ctx, call, dup);
690 } else {
691 pc = check_approval_pc(ctx, call);
692 }
693 return pc;
694}
695
705PreconditionCheck ToolExecutor::check_approval_pc(
706 LoopContext& ctx, const ToolCall& call) {
707 PreconditionCheck pc;
708 ctx.consecutive_duplicate_attempts = 0;
709 if (!check_approval(call)) {
710 pc.rejection = create_denied_message(
711 call, "Permission denied");
713 }
714 return pc;
715}
716
729std::vector<Message> ToolExecutor::process_single_call(
730 LoopContext& ctx, const ToolCall& call) {
731 // Hook: PRE_TOOL_CALL first — fires for every attempt, including
732 // those that a precondition will reject. (E9, 2.0.6-rc19)
733 if (fire_pre_tool_hook(ctx, call)) {
734 auto msg = create_denied_message(call, "Cancelled by hook");
735 // gh#84 (v2.5.1): stamp kind so the engine treats this as a
736 // non-progress outcome for the thinking-budget reset.
737 msg.metadata["result_kind"] =
739 fire_post_tool_hook(ctx, call, "", 0.0,
741 return {std::move(msg)};
742 }
743
744 auto pc = check_call_preconditions(ctx, call);
745 if (pc.rejection.has_value()) {
746 logger->info("Tool '{}' rejected by precondition (kind={})",
747 call.name, result_kind_to_string(pc.kind));
748 // gh#84 (v2.5.1): stamp kind for the engine's budget decision.
749 pc.rejection->metadata["result_kind"] =
750 result_kind_to_string(pc.kind);
751 fire_post_tool_hook(ctx, call, "", 0.0, pc.kind, *pc.rejection);
752 return {std::move(*pc.rejection)};
753 }
754
755 auto exec_start = std::chrono::steady_clock::now();
756 auto [msg, raw_result] = execute_tool(ctx, call);
757 auto exec_ms = std::chrono::duration<double, std::milli>(
758 std::chrono::steady_clock::now() - exec_start).count();
759
760 finalize_tool_call(ctx, call, msg, raw_result, exec_ms);
761
762 return {std::move(msg)};
763}
764
772static ToolResultKind classify_tool_result(const std::string& content) {
773 if (mcp::looks_like_tool_error(content)) {
775 }
776 if (mcp::is_effectively_empty(content)) {
778 }
779 return ToolResultKind::ok;
780}
781
792void ToolExecutor::log_tool_call(LoopContext& ctx, const ToolCall& call,
793 double exec_ms,
794 const std::string& raw_result,
795 ToolResultKind kind) {
796 auto args_log = serialize_args(call);
797 if (args_log.size() > 512) { args_log.resize(512); }
798 logger->info("[tool_call] iter={} tier={} tool={} args={} "
799 "elapsed_ms={:.0f} result_chars={} status={}",
800 ctx.metrics.iterations,
801 ctx.locked_tier.empty() ? "lead" : ctx.locked_tier,
802 call.name, args_log, exec_ms,
803 raw_result.size(), result_kind_to_string(kind));
804}
805
816void ToolExecutor::finalize_tool_call(LoopContext& ctx, const ToolCall& call,
817 Message& msg,
818 const std::string& raw_result,
819 double exec_ms) {
820 // #46 (v2.1.0): cap result content at LoopConfig.max_tool_result_bytes
821 // so a single runaway tool can't exhaust the context budget. Applied
822 // BEFORE classification so kind reflects the bounded form, and BEFORE
823 // record_tool_call so the duplicate cache stores what the model saw.
824 apply_result_size_cap(msg.content);
825 ctx.effective_tool_calls++;
826 msg.metadata["added_at_iteration"] =
827 std::to_string(ctx.metrics.iterations);
828 record_tool_call(ctx, call, raw_result);
829
830 // #44 (v2.1.0): honest byte-level signal — error trumps empty.
831 ToolResultKind kind = classify_tool_result(msg.content);
832 // gh#84 (v2.5.1): stamp the result kind on the message so the
833 // engine can tell genuine progress (ok / ok_empty) from rejections
834 // and errors when deciding whether to reset the thinking budget.
835 msg.metadata["result_kind"] = result_kind_to_string(kind);
836 fire_post_tool_hook(ctx, call, raw_result, exec_ms, kind, msg);
837
838 // Demo ask #5 (v2.1.0): anti-spiral primitive. Track consecutive
839 // same-tool calls; at threshold, populate pending_anti_spiral_warning
840 // so the next turn's reminder tells the model to pivot or complete.
841 update_anti_spiral_tracking(ctx, call.name);
842
843 log_tool_call(ctx, call, exec_ms, raw_result, kind);
844
845 extract_and_process_directives(ctx, raw_result);
846 run_post_tool_hooks(ctx);
847}
848
857bool ToolExecutor::fire_pre_tool_hook(
858 const LoopContext& ctx, const ToolCall& call) {
859 if (hook_iface_.fire_pre == nullptr) { return false; }
860 auto json = build_pre_tool_json(call, ctx.locked_tier,
861 ctx.metrics.iterations);
862 char* mod = nullptr;
863 int rc = hook_iface_.fire_pre(hook_iface_.registry,
864 ENTROPIC_HOOK_PRE_TOOL_CALL, json.c_str(), &mod);
865 free(mod);
866 return rc != 0;
867}
868
877void ToolExecutor::apply_result_size_cap(std::string& content) const {
878 mcp::truncate_to_cap(content, loop_config_.max_tool_result_bytes);
879}
880
889void ToolExecutor::update_anti_spiral_tracking(
890 LoopContext& ctx, const std::string& tool_name) {
891 if (tool_name == ctx.last_tool_name) {
892 ++ctx.consecutive_same_tool_calls;
893 } else {
894 ctx.last_tool_name = tool_name;
895 ctx.consecutive_same_tool_calls = 1;
896 }
897 if (ctx.consecutive_same_tool_calls
898 >= loop_config_.max_consecutive_same_tool) {
899 ctx.pending_anti_spiral_warning =
900 tool_name + " has been called "
901 + std::to_string(ctx.consecutive_same_tool_calls)
902 + " times consecutively; pivot to a different tool or "
903 "complete the task next turn.";
904 }
905}
906
915int ToolExecutor::effective_hard_block_threshold() const {
916 int configured = loop_config_.max_consecutive_same_tool_hard_block;
917 if (configured < 0) {
918 configured = loop_config_.max_consecutive_same_tool + 2;
919 }
920 return configured;
921}
922
938PreconditionCheck ToolExecutor::check_anti_spiral_hard_block(
939 const LoopContext& ctx, const ToolCall& call) const {
940 PreconditionCheck pc;
941 int projected = (call.name == ctx.last_tool_name)
942 ? (ctx.consecutive_same_tool_calls + 1)
943 : 1;
944 int threshold = effective_hard_block_threshold();
945 if (projected >= threshold) {
946 std::string text =
947 "[anti-spiral] tool '" + call.name + "' blocked after "
948 + std::to_string(projected)
949 + " consecutive calls (threshold "
950 + std::to_string(threshold)
951 + "); pivot to a different tool or complete the task.";
952 pc.rejection = create_denied_message(call, text);
954 }
955 return pc;
956}
957
976void ToolExecutor::fire_post_tool_hook(
977 const LoopContext& ctx, const ToolCall& call,
978 const std::string& raw_result, double elapsed_ms,
979 ToolResultKind kind, Message& msg) {
980 if (hook_iface_.fire_post == nullptr) { return; }
981 auto json = build_post_tool_json(
982 call, raw_result, elapsed_ms, ctx.locked_tier,
983 ctx.metrics.iterations, kind);
984 char* out = nullptr;
985 hook_iface_.fire_post(hook_iface_.registry,
986 ENTROPIC_HOOK_POST_TOOL_CALL, json.c_str(), &out);
987 if (out != nullptr) {
988 msg.content = out;
989 free(out);
990 }
991}
992
1001bool ToolExecutor::should_stop_batch(
1002 const LoopContext& ctx,
1003 const std::vector<Message>& /*results*/) const {
1004 return ctx.state == AgentState::COMPLETE
1005 || ctx.pending_delegation.has_value()
1006 || ctx.pending_pipeline.has_value()
1007 || ctx.consecutive_duplicate_attempts >= 3;
1008}
1009
1016void ToolExecutor::run_post_tool_hooks(LoopContext& ctx) {
1017 if (hooks_.after_tool != nullptr) {
1018 hooks_.after_tool(ctx, hooks_.user_data);
1019 }
1020}
1021
1028Message ToolExecutor::create_circuit_breaker_message() {
1029 Message msg;
1030 msg.role = "user";
1031 msg.content =
1032 "STOP: You have called the same tool 3 times with "
1033 "identical arguments. This indicates you are stuck. "
1034 "Please try a completely different approach or respond "
1035 "to the user explaining what's blocking you.";
1036 logger->error("Circuit breaker triggered");
1037 return msg;
1038}
1039
1048Message ToolExecutor::create_duplicate_message(
1049 const ToolCall& call,
1050 const std::string& previous_result) {
1051 bool was_denied =
1052 previous_result.find("was denied") != std::string::npos
1053 || previous_result.find("not available") != std::string::npos;
1054
1055 Message msg;
1056 msg.role = "user";
1057
1058 if (was_denied) {
1059 msg.content =
1060 "Tool `" + call.name + "` is not available to you "
1061 "and retrying will not help. You MUST use a different "
1062 "approach. Do NOT call `" + call.name + "` again.";
1063 } else {
1064 msg.content =
1065 "Tool `" + call.name + "` was already called with "
1066 "the same arguments.\n\nPrevious result:\n" +
1067 previous_result +
1068 "\n\nDo NOT call this tool again. "
1069 "Use the previous result above.";
1070 }
1071 return msg;
1072}
1073
1086std::string ToolExecutor::serialize_args(const ToolCall& call) {
1087 if (!call.arguments_json.empty()) {
1088 return call.arguments_json;
1089 }
1090 nlohmann::json args;
1091 for (const auto& [k, v] : call.arguments) {
1092 args[k] = v;
1093 }
1094 return args.dump();
1095}
1096
1104std::string ToolExecutor::serialize_tool_call(const ToolCall& call) {
1105 nlohmann::json j;
1106 j["id"] = call.id;
1107 j["name"] = call.name;
1108 j["arguments"] = nlohmann::json::object();
1109 for (const auto& [k, v] : call.arguments) {
1110 j["arguments"][k] = v;
1111 }
1112 return j.dump();
1113}
1114
1123void ToolExecutor::fire_tool_complete_callback(
1124 const ToolCall& call,
1125 const std::string& result,
1126 long long ms) {
1127 if (callbacks_.on_tool_complete == nullptr) {
1128 return;
1129 }
1130 auto call_json = serialize_tool_call(call);
1131 callbacks_.on_tool_complete(
1132 call_json.c_str(), result.c_str(),
1133 static_cast<double>(ms), callbacks_.user_data);
1134}
1135
1148std::string ToolExecutor::build_post_tool_json(
1149 const ToolCall& call,
1150 const std::string& raw_result,
1151 double elapsed_ms,
1152 const std::string& tier,
1153 int iteration,
1154 ToolResultKind kind) {
1155 nlohmann::json ctx;
1156 ctx["tool_name"] = call.name;
1157 ctx["args"] = nlohmann::json::parse(serialize_args(call));
1158 ctx["elapsed_ms"] = elapsed_ms;
1159 ctx["tier"] = tier.empty() ? std::string{"lead"} : tier;
1160 ctx["iteration"] = iteration;
1161 ctx["result_kind"] = result_kind_to_string(kind);
1162 try {
1163 auto sr = nlohmann::json::parse(raw_result);
1164 ctx["result"] = sr.value("result", raw_result);
1165 ctx["directives"] = sr.value(
1166 "directives", nlohmann::json::array());
1167 } catch (...) {
1168 ctx["result"] = raw_result;
1169 ctx["directives"] = nlohmann::json::array();
1170 }
1171 return ctx.dump();
1172}
1173
1183std::string ToolExecutor::build_pre_tool_json(
1184 const ToolCall& call,
1185 const std::string& tier,
1186 int iteration) {
1187 nlohmann::json j;
1188 j["tool_name"] = call.name;
1189 j["args"] = nlohmann::json::parse(serialize_args(call));
1190 j["tier"] = tier.empty() ? std::string{"lead"} : tier;
1191 j["iteration"] = iteration;
1192 return j.dump();
1193}
1194
1214static std::vector<std::string> extract_pipeline_stages(
1215 const nlohmann::json& result_json) {
1216 std::vector<std::string> stages;
1217 if (!result_json.contains("stages")) { return stages; }
1218 for (const auto& s : result_json["stages"]) {
1219 stages.push_back(s.get<std::string>());
1220 }
1221 return stages;
1222}
1223
1244static std::unique_ptr<Directive> build_complete_directive(
1245 const nlohmann::json& result_json) {
1246 auto cd = std::make_unique<CompleteDirective>(
1247 result_json.value("summary", ""));
1248 cd->coverage_gap = result_json.value("coverage_gap", false);
1249 cd->gap_description = result_json.value("gap_description", "");
1250 if (result_json.contains("suggested_files")
1251 && result_json["suggested_files"].is_array()) {
1252 cd->suggested_files =
1253 result_json["suggested_files"].get<std::vector<std::string>>();
1254 }
1255 return cd;
1256}
1257
1263static std::unique_ptr<Directive> build_directive(
1264 const nlohmann::json& d, const nlohmann::json& result_json) {
1265 auto type_str = d.value("type", "");
1266 std::unique_ptr<Directive> result;
1267 if (type_str == "stop_processing") {
1268 result = std::make_unique<StopProcessingDirective>();
1269 } else if (type_str == "delegate") {
1270 // gh#32 (v2.1.6): resume_delegation emits action=resume_delegation
1271 // with delegation_id but no target. The directive's target is
1272 // resolved later by the engine after loading the original
1273 // delegation's tier from storage.
1274 result = std::make_unique<DelegateDirective>(
1275 result_json.value("target", ""),
1276 result_json.value("task", ""),
1277 result_json.value("max_turns", -1),
1278 result_json.value("delegation_id", ""));
1279 } else if (type_str == "complete") {
1280 result = build_complete_directive(result_json);
1281 } else if (type_str == "pipeline") {
1282 result = std::make_unique<PipelineDirective>(
1283 extract_pipeline_stages(result_json),
1284 result_json.value("task", ""));
1285 }
1286 return result;
1287}
1288
1297static std::optional<std::pair<nlohmann::json, nlohmann::json>>
1298extract_directive_array(const std::string& raw_result) {
1299 auto resp = nlohmann::json::parse(raw_result, nullptr, false);
1300 if (!resp.is_object() || !resp.contains("directives")) {
1301 return std::nullopt;
1302 }
1303 auto dirs = resp["directives"];
1304 if (!dirs.is_array() || dirs.empty()) { return std::nullopt; }
1305 return std::make_pair(std::move(resp), std::move(dirs));
1306}
1307
1315void ToolExecutor::extract_and_process_directives(
1316 LoopContext& ctx, const std::string& raw_result) {
1317 if (hooks_.process_directives == nullptr) { return; }
1318 auto extracted = extract_directive_array(raw_result);
1319 if (!extracted) { return; }
1320 auto& [resp, dirs] = *extracted;
1321
1322 auto result_json = nlohmann::json::parse(
1323 resp.value("result", "{}"), nullptr, false);
1324
1325 std::vector<std::unique_ptr<Directive>> owned;
1326 for (const auto& d : dirs) {
1327 auto directive = build_directive(d, result_json);
1328 if (directive) { owned.push_back(std::move(directive)); }
1329 }
1330 if (owned.empty()) { return; }
1331
1332 std::vector<const Directive*> ptrs;
1333 ptrs.reserve(owned.size());
1334 for (const auto& d : owned) { ptrs.push_back(d.get()); }
1335 logger->info("Processing {} directives from tool result", ptrs.size());
1336 hooks_.process_directives(ctx, ptrs, hooks_.user_data);
1337}
1338
1339} // namespace entropic
bool is_enforced(const std::string &identity_name) const
Check if an identity has authorization enforcement enabled.
bool check_access(const std::string &identity_name, const std::string &tool_name, MCPAccessLevel required_level) const
Check if a tool call is authorized for an identity.
Manages MCP server instances and routes tool calls.
MCPAccessLevel get_required_access_level(const std::string &tool_name) const
Get the required access level for a tool.
bool is_explicitly_allowed(const std::string &tool_name, const std::string &args_json) const
Check if tool is explicitly allowed (skip prompting).
bool skip_duplicate_check(const std::string &tool_name) const
Check if tool should skip duplicate detection.
std::string get_tool_schema(const std::string &tool_name) const
Get the JSON Schema for a tool's input parameters.
std::string execute(const std::string &tool_name, const std::string &args_json)
Execute a tool call via the appropriate server.
void record(const ToolCallRecord &entry)
Record a completed tool call.
std::vector< Message > process_tool_calls(LoopContext &ctx, const std::vector< ToolCall > &tool_calls)
Process a batch of tool calls.
ToolExecutor(ServerManager &server_manager, const LoopConfig &loop_config, EngineCallbacks &callbacks, ToolExecutorHooks hooks={})
Construct with shared dependencies.
void set_permission_persist(const PermissionPersistInterface &persist)
Set permission persistence interface.
@ ENTROPIC_HOOK_ON_PERMISSION_CHECK
15: Permission check evaluated
Definition hooks.h:51
@ ENTROPIC_HOOK_PRE_TOOL_CALL
3: Before tool execution
Definition hooks.h:39
@ ENTROPIC_HOOK_POST_TOOL_CALL
4: After tool execution returns
Definition hooks.h:40
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Definition logging.cpp:211
double elapsed_ms(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end)
Compute elapsed milliseconds between two time points.
Definition logging.h:203
Activate model on GPU (WARM → ACTIVE).
static std::string check_type(const std::string &key, const std::string &type, const nlohmann::json &val)
Check a single value against a type constraint.
ToolResultKind
Categorical outcome of a single tool invocation.
Definition tool_result.h:31
@ ok
Tool dispatched, returned non-empty content.
@ rejected_schema
Precondition: argument schema violation.
@ rejected_anti_spiral
Anti-spiral hard threshold crossed; tool blocked. (#14, v2.1.4)
@ rejected_duplicate
Precondition: duplicate in recent history.
@ ok_empty
Tool dispatched cleanly but returned no content (v2.1.0, #44)
@ rejected_unauthorized
Tool not in the locked tier's allowed_tools. (gh#83, v2.5.2)
@ error
Tool server returned an error payload.
@ rejected_precondition
Any other precondition reject (auth, tier, hook-cancel)
static std::string parse_tool_result_text(const std::string &result_json)
Extract the "result" text from an MCP result JSON envelope.
static std::vector< std::string > extract_pipeline_stages(const nlohmann::json &result_json)
Extract directives from ServerResponse JSON and process them.
static std::string check_property_constraints(const std::string &key, const nlohmann::json &prop, const nlohmann::json &val)
Check one property's enum and type constraints.
static ToolResultKind classify_tool_result(const std::string &content)
Classify a tool result by its content (error/empty/ok).
const char * mcp_access_level_name(MCPAccessLevel level)
Convert MCPAccessLevel to string representation.
Definition config.cpp:21
static std::unique_ptr< Directive > build_directive(const nlohmann::json &d, const nlohmann::json &result_json)
Build a Directive from a parsed directive + result JSON.
const char * result_kind_to_string(ToolResultKind kind)
Serialize a ToolResultKind to its wire-stable string form.
Definition tool_result.h:50
static std::unique_ptr< Directive > build_complete_directive(const nlohmann::json &result_json)
Build a typed Directive from a directive-descriptor JSON.
static std::optional< std::pair< nlohmann::json, nlohmann::json > > extract_directive_array(const std::string &raw_result)
Pull the "directives" array out of a tool ServerResponse JSON.
std::string truncate_result(const std::string &text, size_t max_len)
Truncate a string to max_len characters with "..." suffix.
static char * dup(const std::string &s)
Heap-allocate a C string copy.
std::string summarize_params(const std::string &args_json)
Extract top-level JSON keys as a comma-separated summary.
static std::string validate_tool_args(const std::string &schema_json, const nlohmann::json &args)
Validate tool arguments against the tool's JSON Schema.
static std::string check_enum(const std::string &key, const nlohmann::json &allowed, const nlohmann::json &val)
Check one property's enum and type constraints.
static std::string check_required_fields(const nlohmann::json &schema, const nlohmann::json &args)
Check required fields are present.
Callback function pointer types for engine events.
void(* on_tool_call)(const char *json, void *ud)
Tool call request.
void(* on_tool_complete)(const char *json, const char *result, double ms, void *ud)
Tool execution done.
void * user_data
Opaque pointer passed to all callbacks.
void(* on_tool_start)(const char *json, void *ud)
Tool execution start.
void(* on_state_change)(int state, void *ud)
AgentState as int.
Configuration for the agentic loop.
int max_consecutive_same_tool
Anti-spiral SOFT threshold: after N consecutive calls of the SAME tool (regardless of arg similarity,...
int max_consecutive_same_tool_hard_block
Anti-spiral HARD threshold: when consecutive same-tool calls exceed this, the engine blocks the call ...
bool auto_approve_tools
Skip tool approval (v1.8.5)
int max_tool_result_bytes
Maximum byte length for a single tool's result content before the engine truncates with a "[....
int max_tool_calls_per_turn
Tool calls per iteration (v1.8.5)
Mutable state carried through the agentic loop.
int consecutive_errors
Error streak counter.
int effective_max_tool_calls_per_turn
Per-identity override (-1 = LoopConfig, P3-18)
AgentState state
Current state.
Permission persistence interface.
A tool call request parsed from model output.
Definition tool_call.h:31
Engine-level hooks called during tool processing.
void(* after_tool)(LoopContext &ctx, void *user_data)
Called after each tool execution.
DirectiveResult(* process_directives)(LoopContext &ctx, const std::vector< const Directive * > &directives, void *user_data)
Process directives from tool results.
void * user_data
Opaque pointer for hooks.
Processes tool calls from model output.
Byte-level classifiers for tool-result content (#44, v2.1.0).
UTF-8 validation + replacement at every system boundary where bytes change ownership.