entropic_server.cpp¶
src/mcp/servers/entropic_server.cpp
@file entropic_server.cpp @brief EntropicServer implementation — engine-level directive tools.
Owners: @tvanfossen
DelegateTool
entropic::DelegateTool::DelegateTool(ToolDefinition def, const std::vector< std::string > &tier_names, std::vector< std::string > require_context_tiers={})Construct and patch input schema with tier names.
src/mcp/servers/entropic_server.cpp:274
Source · 50 lines
DelegateTool(ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers = {});
/**
* @brief Execute delegation.
* @param args_json JSON with "target", "task", "max_turns", "context".
* @return ServerResponse with delegate + stop directives, or a typed
* error with NO directives when the target tier declares
* `requires_context` and none was supplied (gh#162).
* @utility
* @version 2.13.0
*/
ServerResponse execute(const std::string& args_json) override;
private:
/// @brief gh#162: tiers that refuse a delegation carrying no context.
std::vector<std::string> require_context_tiers_;
};
/**
* @brief Construct and patch enum in input schema.
*
* The target enum is patched at construction from the tier names the
* server was given — and those exclude source tiers, so a tier cannot
* delegate to itself.
*
* @param def Tool definition.
* @param tier_names Tier names for target enum.
* @param require_context_tiers Tiers that refuse a contextless
* delegation (gh#162).
* @req REQ-MCP-024
* @req REQ-MCP-013
* @req REQ-DELEG-006
* @version 2.13.0
*/
DelegateTool::DelegateTool(
ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers)
: ToolBase(std::move(def)),
require_context_tiers_(std::move(require_context_tiers)) {
auto schema = nlohmann::json::parse(definition_.input_schema);
schema["properties"]["target"]["enum"] = tier_names;
definition_.input_schema = schema.dump();
logger->info("[delegate] patched enum with {} tiers ({} require context)",
tier_names.size(), require_context_tiers_.size());
}Activity · 4 steps
Requirements
PipelineTool
entropic::PipelineTool::PipelineTool(ToolDefinition def, const std::vector< std::string > &tier_names, std::vector< std::string > require_context_tiers={})Construct and patch input schema with tier names.
src/mcp/servers/entropic_server.cpp:428
Source · 46 lines
PipelineTool(ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers = {});
/**
* @brief Execute pipeline setup.
* @param args_json JSON with "stages" array and "task".
* @return ServerResponse with pipeline + stop directives.
* @utility
* @version 1.8.5
*/
ServerResponse execute(const std::string& args_json) override;
private:
std::vector<std::string> tier_names_; ///< Known tiers for runtime validation.
/// @brief gh#162: stages that refuse a contextless pipeline.
std::vector<std::string> require_context_tiers_;
};
/**
* @brief Construct and patch stage enum in input schema.
*
* The tier list is kept as a member as well as patched into the schema,
* so stages are re-validated at execute time rather than trusting the
* model to have honoured the enum.
*
* @param def Tool definition.
* @param tier_names Tier names for stages enum.
* @req REQ-MCP-024
* @req REQ-MCP-013
* @version 2.10.0
*/
PipelineTool::PipelineTool(
ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers)
: ToolBase(std::move(def)), tier_names_(tier_names),
require_context_tiers_(std::move(require_context_tiers)) {
auto schema = nlohmann::json::parse(definition_.input_schema);
schema["properties"]["stages"]["items"]["enum"] = tier_names;
definition_.input_schema = schema.dump();
logger->info("[pipeline] patched enum with {} tiers",
tier_names.size());
}Activity · 4 steps
Requirements
call_provider
static std::string entropic::call_provider(char *(*fn)(void *), void *ud)
Call a state provider callback and wrap result.
src/mcp/servers/entropic_server.cpp:886
Called by build_snapshot, dispatch_simple_target, inspect_filterable
Calls capi_test_compactor_fn
Source · 13 lines
static std::string call_provider(
char* (*fn)(void*), void* ud) {
if (fn == nullptr) {
return "{}";
}
char* raw = fn(ud);
if (raw == nullptr) {
return "{}";
}
std::string result(raw);
free(raw);
return result;
}Activity · 8 steps
Requirements
execute
ServerResponse entropic::TodoTool::execute(const std::string &args_json) override
Execute todo action (add/update/remove).
src/mcp/servers/entropic_server.cpp:83
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Anchor key for todo state replacement.
* @param args_json Arguments (unused).
* @return "todo_state" anchor key.
* @utility
* @version 1.8.5
*/
std::string anchor_key(
const std::string& args_json) const override;
/**
* @brief Forget a session's list (gh#158).
* @param key Session key.
* @return true when the session had a list.
* @utility
* @version 2.13.0
*/
bool release(const std::string& key) { return lists_.release(key); }
/**
* @brief Sessions holding a list (gh#158).
* @return Session count.
* @utility
* @version 2.13.0
*/
std::size_t session_count() const { return lists_.session_count(); }
private:
/// @brief gh#158: session key → that session's list, under a leaf
/// mutex. Concurrent sessions reach one EntropicServer from several
/// run threads.
SessionScoped<std::vector<TodoItem>> lists_;
};
/**
* @brief Anchor key for context replacement.
* @param args_json Arguments (unused).
* @return "todo_state".
* @utility
* @version 1.8.5
*/
std::string TodoTool::anchor_key(
const std::string& /*args_json*/) const {
return "todo_state";
}
namespace {
/**
* @brief Format a todo list as numbered text.
* @param items The list.
* @return Formatted string, or "(empty)".
* @utility
* @version 2.13.0
*/
std::string format_todo_list(const std::vector<TodoItem>& items) {
if (items.empty()) {
return "(empty)";
}
std::string out;
for (size_t i = 0; i < items.size(); ++i) {
out += std::to_string(i) + ". [" +
items[i].status + "] " +
items[i].content + "\n";
}
return out;
}
/**
* @brief Why an update/remove cannot apply, or "" when it can.
* @param items The list.
* @param action "update" or "remove".
* @param idx Requested index.
* @return "" or the declared `out_of_range` error.
* @utility
* @version 2.14.0
*/
std::string todo_index_error(const std::vector<TodoItem>& items,
const std::string& action, long idx) {
std::string err;
if (0 > idx || idx >= static_cast<long>(items.size())) {
logger->warn("[todo] {} #{}: out of range (list has {})",
action, idx, items.size());
err = tool_error_json("out_of_range", "index " + std::to_string(idx)
+ " is not in the list, which has " + std::to_string(items.size())
+ " item(s) (indices start at 0)");
}
return err;
}
/**
* @brief Apply an add/update/remove action to one session's list.
*
* v2.14.0 (gh#203): an update or remove naming an index the list does not
* have is an `out_of_range` error (it used to change nothing and report
* success); an unknown action is `invalid_args` (it used to be treated as
* remove); `add` honours `status`, which its schema always offered.
*
* @param items The calling session's list.
* @param action One of "add" / "update" / "remove".
* @param args Parsed tool arguments.
* @return "" when applied, else a declared error.
* @utility
* @version 2.14.0
*/
std::string apply_todo_action(std::vector<TodoItem>& items,
const std::string& action,
const nlohmann::json& args) {
std::string err;
const long idx = args.value<long>("index", -1);
if (action == "add") {
std::string content = args.at("content").get<std::string>();
items.push_back({content, args.value("status", std::string("pending"))});
logger->info("[todo] add: {}", content);
} else if (action != "update" && action != "remove") {
err = tool_error_json("invalid_args", "unknown action '" + action
+ "' (add, update or remove)");
} else if (err = todo_index_error(items, action, idx); err.empty()) {54 more lines, not shown
Activity · 1 steps
ServerResponse entropic::DelegateTool::execute(const std::string &args_json) override
Execute delegation.
src/mcp/servers/entropic_server.cpp:287
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
private:
/// @brief gh#162: tiers that refuse a delegation carrying no context.
std::vector<std::string> require_context_tiers_;
};
/**
* @brief Construct and patch enum in input schema.
*
* The target enum is patched at construction from the tier names the
* server was given — and those exclude source tiers, so a tier cannot
* delegate to itself.
*
* @param def Tool definition.
* @param tier_names Tier names for target enum.
* @param require_context_tiers Tiers that refuse a contextless
* delegation (gh#162).
* @req REQ-MCP-024
* @req REQ-MCP-013
* @req REQ-DELEG-006
* @version 2.13.0
*/
DelegateTool::DelegateTool(
ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers)
: ToolBase(std::move(def)),
require_context_tiers_(std::move(require_context_tiers)) {
auto schema = nlohmann::json::parse(definition_.input_schema);
schema["properties"]["target"]["enum"] = tier_names;
definition_.input_schema = schema.dump();
logger->info("[delegate] patched enum with {} tiers ({} require context)",
tier_names.size(), require_context_tiers_.size());
}
/**
* @brief Copy a `context` argument into the result, dropping junk (gh#162).
*
* Entries without a `path` are dropped rather than forwarded: a context
* reference with nothing to open is noise in the child's opening message,
* and small models treat noise as instruction.
*
* @param args Parsed tool arguments.
* @param[out] result Result JSON to populate with a "context" array.
* @return Number of usable references carried through.
* @utility
* @version 2.13.0
*/
static size_t carry_context(const nlohmann::json& args,
nlohmann::json& result) {
auto out = nlohmann::json::array();
if (args.contains("context") && args["context"].is_array()) {
for (const auto& ref : args["context"]) {
if (!ref.is_object()) { continue; }
auto path = ref.value("path", std::string{});
if (path.empty()) { continue; }
nlohmann::json entry;
entry["path"] = path;
entry["lines"] = ref.value("lines", std::string{});
entry["note"] = ref.value("note", std::string{});
out.push_back(std::move(entry));
}
}
size_t n = out.size();
result["context"] = std::move(out);
return n;
}
/**
* @brief Parse delegation args and emit directives.
* @param args_json JSON with "target", "task", optional "max_turns"
* (defaulting to -1 for "engine decides") and optional
* "context" file references (gh#162).
* @return A ServerResponse whose result echoes the delegation and whose
* directives are delegate + stop_processing — the pair that
* hands the turn to the child loop; or, when the target tier
* declares `requires_context` and none was supplied, the declared
* `requires_context` error with NO directives (gh#162).
* @req REQ-MCP-024
* @req REQ-DELEG-006
* @version 2.14.0
*/
ServerResponse DelegateTool::execute(const std::string& args_json) {
auto args = nlohmann::json::parse(args_json);
std::string target = args.at("target").get<std::string>();
std::string task = args.at("task").get<std::string>();
int max_turns = args.value("max_turns", -1);
nlohmann::json result;
result["action"] = "delegate";
result["target"] = target;
result["task"] = task;
result["max_turns"] = max_turns;
auto refs = carry_context(args, result);
// gh#162: a tier that declares requires_context cannot succeed on a
// contextless task, so refuse HERE — a tool error the lead can act on
// in the same turn, rather than a burned child loop whose transcript
// nobody reads.
if (refs == 0
&& std::find(require_context_tiers_.begin(),
require_context_tiers_.end(), target)
!= require_context_tiers_.end()) {
logger->warn("[delegate] refused: tier '{}' requires context", target);
return {tool_error_json("requires_context", "tier \"" + target
+ "\" requires context. Re-issue entropic.delegate with a "
"`context` array naming at least one file path (optionally "
"lines/note) the delegate should read."), {}};
}
logger->info("[delegate] target='{}' task='{}' max_turns={} context={}",
target, task, max_turns, refs);
Directive delegate_d;
delegate_d.type = ENTROPIC_DIRECTIVE_DELEGATE;
Directive stop_d;4 more lines, not shown
Activity · 4 steps
ServerResponse entropic::PipelineTool::execute(const std::string &args_json) override
Execute pipeline setup.
src/mcp/servers/entropic_server.cpp:439
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
private:
std::vector<std::string> tier_names_; ///< Known tiers for runtime validation.
/// @brief gh#162: stages that refuse a contextless pipeline.
std::vector<std::string> require_context_tiers_;
};
/**
* @brief Construct and patch stage enum in input schema.
*
* The tier list is kept as a member as well as patched into the schema,
* so stages are re-validated at execute time rather than trusting the
* model to have honoured the enum.
*
* @param def Tool definition.
* @param tier_names Tier names for stages enum.
* @req REQ-MCP-024
* @req REQ-MCP-013
* @version 2.10.0
*/
PipelineTool::PipelineTool(
ToolDefinition def,
const std::vector<std::string>& tier_names,
std::vector<std::string> require_context_tiers)
: ToolBase(std::move(def)), tier_names_(tier_names),
require_context_tiers_(std::move(require_context_tiers)) {
auto schema = nlohmann::json::parse(definition_.input_schema);
schema["properties"]["stages"]["items"]["enum"] = tier_names;
definition_.input_schema = schema.dump();
logger->info("[pipeline] patched enum with {} tiers",
tier_names.size());
}
/**
* @brief Parse pipeline args, validate stages, emit directives.
*
* gh#129 (v2.10.0): each stage is validated against tier_names_ before
* any directive is emitted. Unknown tier names are rejected with a plain
* error string naming the offending stage and the valid options.
*
* @param args_json JSON with "stages", "task" and optional "context"
* file references (gh#162).
* @return On success, a ServerResponse echoing the stages with
* pipeline + stop_processing directives. On fewer than two
* stages, a stage naming a tier not in tier_names, or a stage
* that declares `requires_context` with none supplied (gh#162),
* an error string quoting the offending stage — with NO
* directives, so nothing is dispatched.
* @req REQ-MCP-024
* @req REQ-DELEG-006
* @version 2.13.0
*/
/**
* @brief Why this pipeline cannot run, or "" when it can (gh#129, gh#162).
*
* Extracted from `PipelineTool::execute` to keep it under the knots
* ABC + returns gates when the context check joined the stage check.
* v2.14.0: each refusal is a declared error — `too_few_stages`,
* `unknown_stage` or `requires_context`.
*
* @param stages Requested stage tiers.
* @param tier_names Configured tiers.
* @param require_context_tiers Tiers that refuse a contextless run.
* @param refs Number of context references supplied.
* @return Declared error JSON, or "" when the pipeline is valid.
* @utility
* @req REQ-MCP-024
* @req REQ-DELEG-006
* @version 2.14.0
*/
static std::string pipeline_rejection(
const std::vector<std::string>& stages,
const std::vector<std::string>& tier_names,
const std::vector<std::string>& require_context_tiers,
size_t refs) {
std::string err;
if (stages.size() < 2) {
logger->warn("[pipeline] rejected: fewer than 2 stages");
err = tool_error_json("too_few_stages", "pipeline requires at least 2 stages");
}
for (const auto& s : stages) {
if (!err.empty()) { break; }
if (std::find(tier_names.begin(), tier_names.end(), s)
== tier_names.end()) {
logger->warn("[pipeline] invalid stage: '{}'", s);
err = tool_error_json("unknown_stage", "unknown stage \"" + s
+ "\". Valid stages: " + nlohmann::json(tier_names).dump());
} else if (refs == 0
&& std::find(require_context_tiers.begin(),
require_context_tiers.end(), s)
!= require_context_tiers.end()) {
// gh#162: one context list seeds every stage, so a stage that
// requires context refuses the whole pipeline — before any
// stage runs, not after the first has burned its turns.
logger->warn("[pipeline] refused: stage '{}' requires context", s);
err = tool_error_json("requires_context", "stage \"" + s
+ "\" requires context. Re-issue entropic.pipeline with a "
"`context` array naming at least one file path the stages "
"should read.");
}
}
return err;
}
/**
* @brief Parse pipeline args, validate stages, emit directives.
*
* gh#129 (v2.10.0): every stage is validated against tier_names_ before
* any directive is emitted. gh#162 (v2.13.0): the context list is carried
* through and a stage declaring `requires_context` refuses the run.
*
* @param args_json JSON with "stages", "task" and optional "context".
* @return On success, a ServerResponse echoing the stages with
* pipeline + stop_processing directives; otherwise an error
* string with NO directives, so nothing is dispatched.
* @req REQ-MCP-024
* @req REQ-DELEG-00630 more lines, not shown
Activity · 4 steps
ServerResponse entropic::CompleteTool::execute(const std::string &args_json) override
Execute completion signal.
src/mcp/servers/entropic_server.cpp:615
Source · 70 lines
ServerResponse execute(const std::string& args_json) override;
};
/**
* @brief Parse summary and emit completion directives.
*
* Issue #10 (v2.1.4): also forwards `coverage_gap` and
* `suggested_files` into the result JSON so the engine's directive
* builder can populate the typed CompleteDirective fields. The
* engine then suppresses auto-relay when coverage_gap is set,
* injecting a `[COVERAGE GAP]` user message into the lead context
* instead.
*
* @param args_json JSON with "summary" and optional "coverage_gap" /
* "gap_description" / "suggested_files".
* @return On success, a ServerResponse carrying the sanitized summary
* with complete + stop_processing directives. When
* coverage_gap is true and gap_description is empty, a
* `missing_gap_description` error with NO directives — the
* validation runs before any directive is emitted.
* @req REQ-MCP-024
* @version 2.10.0
*/
ServerResponse CompleteTool::execute(const std::string& args_json) {
auto args = nlohmann::json::parse(args_json);
std::string summary = args.at("summary").get<std::string>();
bool coverage_gap = args.value("coverage_gap", false);
std::string gap_description =
args.value("gap_description", std::string{});
std::vector<std::string> suggested;
if (args.contains("suggested_files")
&& args["suggested_files"].is_array()) {
suggested = args["suggested_files"]
.get<std::vector<std::string>>();
}
// Issue #10 (v2.1.4): coverage_gap=true REQUIRES a non-empty
// gap_description so the lead context's [COVERAGE GAP] message
// tells the next specialist what to fill in. An empty
// gap_description with coverage_gap=true would be a bare
// "I don't know" with no signal — refuse it at the tool boundary.
if (coverage_gap && gap_description.empty()) {
nlohmann::json err;
err["error"] = "missing_gap_description";
err["message"] =
"coverage_gap=true requires a non-empty gap_description "
"(what's missing from this answer and why).";
return {err.dump(), {}};
}
logger->info("[complete] summary='{}' coverage_gap={} "
"gap_description_len={} suggested_files={}",
summary, coverage_gap,
gap_description.size(), suggested.size());
nlohmann::json result;
result["action"] = "complete";
result["summary"] = entropic::mcp::sanitize_utf8(summary);
result["coverage_gap"] = coverage_gap;
result["gap_description"] = entropic::mcp::sanitize_utf8(gap_description);
result["suggested_files"] = suggested;
Directive complete_d;
complete_d.type = ENTROPIC_DIRECTIVE_COMPLETE;
Directive stop_d;
stop_d.type = ENTROPIC_DIRECTIVE_STOP_PROCESSING;
return {result.dump(), {complete_d, stop_d}};
}Activity · 24 steps
ServerResponse entropic::PhaseChangeTool::execute(const std::string &args_json) override
Execute phase change.
src/mcp/servers/entropic_server.cpp:709
Source · 57 lines
ServerResponse execute(const std::string& args_json) override;
};
/**
* @brief The inline phase_change definition, contract included.
*
* v2.14.0 (gh#203): carries an outputSchema like every bundled
* descriptor, and its Response format is rendered from it.
*
* @return The definition.
* @utility
* @version 2.14.0
*/
static ToolDefinition phase_change_definition() {
ToolDefinition def;
def.name = "phase_change";
def.description = "Switch inference phase";
def.input_schema =
R"({"type":"object","properties":{"phase":{"type":"string"}},"required":["phase"]})";
def.output_schema =
R"({"type":"object","required":["action","phase"],"properties":{"action":{"enum":["phase_change"]},"phase":{"type":"string","description":"the phase requested"}}})";
def.description += render_response_format(def.output_schema);
return def;
}
/**
* @brief Build the phase_change tool from its inline definition.
* @utility
* @version 2.14.0
*/
PhaseChangeTool::PhaseChangeTool()
: ToolBase(phase_change_definition()) {}
/**
* @brief Parse phase and emit directive.
* @param args_json JSON with "phase".
* @return A ServerResponse echoing the requested phase with a single
* phase_change directive for the DirectiveProcessor.
* @req REQ-MCP-024
* @version 1.8.5
*/
ServerResponse PhaseChangeTool::execute(
const std::string& args_json) {
auto args = nlohmann::json::parse(args_json);
std::string phase = args.at("phase").get<std::string>();
logger->info("[phase_change] phase='{}'", phase);
nlohmann::json result;
result["action"] = "phase_change";
result["phase"] = phase;
Directive phase_d;
phase_d.type = ENTROPIC_DIRECTIVE_PHASE_CHANGE;
return {result.dump(), {phase_d}};
}Activity · 7 steps
ServerResponse entropic::PruneContextTool::execute(const std::string &args_json) override
Execute context pruning.
src/mcp/servers/entropic_server.cpp:790
Source · 30 lines
ServerResponse execute(const std::string& args_json) override;
};
/**
* @brief Parse keep_recent and emit prune directive.
* @param args_json JSON with optional "keep_recent" (defaulting to 2
* when omitted).
* @return A ServerResponse echoing the retained-message count with a
* single prune_messages directive.
* @req REQ-MCP-024
* @version 1.8.5
*/
ServerResponse PruneContextTool::execute(
const std::string& args_json) {
auto args = nlohmann::json::parse(args_json);
static constexpr int default_keep = 2;
int keep_recent = args.value("keep_recent", default_keep);
logger->info("[prune_context] keep_recent={}", keep_recent);
nlohmann::json result;
result["action"] = "prune_context";
result["keep_recent"] = keep_recent;
Directive prune_d;
prune_d.type = ENTROPIC_DIRECTIVE_PRUNE_MESSAGES;
return {result.dump(), {prune_d}};
}Activity · 10 steps
ServerResponse entropic::DiagnoseTool::execute(const std::string &args_json) override
Execute diagnostic snapshot.
src/mcp/servers/entropic_server.cpp:846
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Read-only tool requires only READ access.
* @return MCPAccessLevel::READ, relaxing ToolBase's WRITE default
* because this tool only reads engine state.
* @req REQ-MCP-011
* @version 1.9.12
*/
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}
/** @brief Set state provider pointer.
* @param p Provider pointer (must outlive tool).
* @utility
* @version 1.9.12
*/
void set_provider(const entropic_state_provider_t* p) {
provider_ = p;
}
private:
const entropic_state_provider_t* provider_ = nullptr;
};
/**
* @brief Call a state provider callback and wrap result.
*
* Every introspection tool reads engine state through the
* entropic_state_provider_t callback struct, and each individual
* callback is null-checked here rather than dereferenced.
*
* @param fn Callback returning malloc'd string (or nullptr).
* @param ud User data for callback.
* @return The callback's string, copied and its buffer freed; "{}" when
* the callback is absent or returned null.
* @req REQ-MCP-024
* @version 1.9.12
*/
static std::string call_provider(
char* (*fn)(void*), void* ud) {
if (fn == nullptr) {
return "{}";
}
char* raw = fn(ud);
if (raw == nullptr) {
return "{}";
}
std::string result(raw);
free(raw);
return result;
}
/**
* @brief Call history callback with max_entries param.
* @param fn History callback.
* @param max_entries Max entries to return.
* @param ud User data.
* @return JSON string.
* @utility
* @version 1.9.12
*/
static std::string call_history_provider(
char* (*fn)(int, void*), int max_entries, void* ud) {
if (fn == nullptr) {
return "[]";
}
char* raw = fn(max_entries, ud);
if (raw == nullptr) {
return "[]";
}
std::string result(raw);
free(raw);
return result;
}
/**
* @brief Call docs callback with section param.
* @param fn Docs callback.
* @param section Section name (nullptr for full doc).
* @param ud User data.
* @return String content.
* @utility
* @version 1.9.12
*/
static std::string call_docs_provider(
char* (*fn)(const char*, void*),
const char* section, void* ud) {
if (fn == nullptr) {
return "";
}
char* raw = fn(section, ud);
if (raw == nullptr) {
return "";
}
std::string result(raw);
free(raw);
return result;
}
/**
* @brief Build the diagnose snapshot JSON.
* @param provider State provider callbacks.
* @param include_docs Whether to include documentation.
* @param history_limit Max history entries.
* @return Snapshot as JSON object.
* @utility
* @version 1.9.12
*/
static nlohmann::json build_snapshot(
const entropic_state_provider_t& p,
bool include_docs, int history_limit) {
nlohmann::json snap;
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<
std::chrono::milliseconds>(
now.time_since_epoch()).count();58 more lines, not shown
Activity · 1 steps
ServerResponse entropic::InspectTool::execute(const std::string &args_json) override
Execute targeted inspection.
src/mcp/servers/entropic_server.cpp:1050
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Read-only tool requires only READ access.
* @return MCPAccessLevel::READ, relaxing ToolBase's WRITE default
* because this tool only reads engine state.
* @req REQ-MCP-011
* @version 1.9.12
*/
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}
/** @brief Set state provider pointer.
* @param p Provider pointer.
* @utility
* @version 1.9.12
*/
void set_provider(const entropic_state_provider_t* p) {
provider_ = p;
}
private:
const entropic_state_provider_t* provider_ = nullptr;
};
// ── ContextInspectTool ──────────────────────────────────────────
/**
* @brief Tool for inspecting the current context window contents.
*
* Returns each message with role, content preview, and estimated
* token count so the model can assess its own context saturation.
*
* @utility
* @version 2.0.6-rc16
*/
class ContextInspectTool : public ToolBase {
public:
/**
* @brief Construct from tool definition.
* @param def Tool definition loaded from entropic/context_inspect.json.
* @utility
* @version 2.0.6-rc16
*/
explicit ContextInspectTool(ToolDefinition def)
: ToolBase(std::move(def)) {}
/**
* @brief Return context window contents as a message array.
* @param args_json JSON with optional "max_messages" (0 = all).
* @return ServerResponse with [{role, content_preview, token_count_est}].
* @utility
* @version 2.0.6-rc16
*/
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Read-only tool requires only READ access.
* @return MCPAccessLevel::READ, relaxing ToolBase's WRITE default
* because this tool only reads engine state.
* @req REQ-MCP-011
* @version 2.0.6-rc16
*/
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}
/** @brief Set state provider pointer.
* @param p Provider pointer.
* @utility
* @version 2.0.6-rc16
*/
void set_provider(const entropic_state_provider_t* p) {
provider_ = p;
}
private:
const entropic_state_provider_t* provider_ = nullptr;
};
/**
* @brief Collect keys from a JSON object into a vector.
* @param j JSON object.
* @return Vector of key strings.
* @utility
* @version 1.9.12
*/
static std::vector<std::string> collect_object_keys(
const nlohmann::json& j) {
std::vector<std::string> keys;
for (auto it = j.begin(); it != j.end(); ++it) {
keys.push_back(it.key());
}
return keys;
}
/**
* @brief Collect "name" fields from a JSON array of objects.
* @param j JSON array.
* @return Vector of name strings.
* @utility
* @version 1.9.12
*/
static std::vector<std::string> collect_array_names(
const nlohmann::json& j) {
std::vector<std::string> names;
for (const auto& item : j) {
if (item.is_object() && item.contains("name")) {
names.push_back(item["name"].get<std::string>());
}
}
return names;
}
/**
* @brief List available keys from a JSON value for error messages.
* @param j JSON object or array with "name" fields.
* @return Comma-separated key list.
* @utility189 more lines, not shown
Activity · 1 steps
ServerResponse entropic::ContextInspectTool::execute(const std::string &args_json) override
Return context window contents as a message array.
src/mcp/servers/entropic_server.cpp:1105
Source · 120 lines
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Read-only tool requires only READ access.
* @return MCPAccessLevel::READ, relaxing ToolBase's WRITE default
* because this tool only reads engine state.
* @req REQ-MCP-011
* @version 2.0.6-rc16
*/
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}
/** @brief Set state provider pointer.
* @param p Provider pointer.
* @utility
* @version 2.0.6-rc16
*/
void set_provider(const entropic_state_provider_t* p) {
provider_ = p;
}
private:
const entropic_state_provider_t* provider_ = nullptr;
};
/**
* @brief Collect keys from a JSON object into a vector.
* @param j JSON object.
* @return Vector of key strings.
* @utility
* @version 1.9.12
*/
static std::vector<std::string> collect_object_keys(
const nlohmann::json& j) {
std::vector<std::string> keys;
for (auto it = j.begin(); it != j.end(); ++it) {
keys.push_back(it.key());
}
return keys;
}
/**
* @brief Collect "name" fields from a JSON array of objects.
* @param j JSON array.
* @return Vector of name strings.
* @utility
* @version 1.9.12
*/
static std::vector<std::string> collect_array_names(
const nlohmann::json& j) {
std::vector<std::string> names;
for (const auto& item : j) {
if (item.is_object() && item.contains("name")) {
names.push_back(item["name"].get<std::string>());
}
}
return names;
}
/**
* @brief List available keys from a JSON value for error messages.
* @param j JSON object or array with "name" fields.
* @return Comma-separated key list.
* @utility
* @version 1.9.12
*/
static std::string list_available_keys(const nlohmann::json& j) {
auto keys = j.is_object() ? collect_object_keys(j)
: collect_array_names(j);
std::string result;
for (const auto& k : keys) {
if (!result.empty()) { result += ", "; }
result += k;
}
return result;
}
/**
* @brief Select one entry of a provider's JSON by key (object key or
* array element `name`).
* @param json_str Raw JSON string.
* @param key Key to extract.
* @param label Label for the error message.
* @param[out] data The selected entry.
* @return "" when found, else the declared `not_found` error listing
* what is available.
* @utility
* @version 2.14.0
*/
static std::string filter_json_by_key(
const std::string& json_str,
const std::string& key,
const std::string& label,
nlohmann::json& data) {
auto j = nlohmann::json::parse(json_str);
if (j.is_object() && j.contains(key)) {
data = j[key];
} else if (j.is_array()) {
for (const auto& item : j) {
if (item.value("name", "") == key) { data = item; }
}
}
return data.is_null()
? tool_error_json("not_found", label + " '" + key
+ "' not found. Available: " + list_available_keys(j))
: std::string{};
}
/**
* @brief Inspect a filterable target (config/identity/tool).
* @param fn Provider callback returning JSON.
* @param ud Provider user_data.
* @param key Filter key (empty = full).
* @param label Error message label.
* @param[out] data The whole value, or the selected entry.
* @return "" on success, else the declared `not_found` error.
* @utility
* @version 2.14.0
*/170 more lines, not shown
Activity · 1 steps
ServerResponse entropic::FollowupTool::execute(const std::string &args_json) override
Execute a followup query.
src/mcp/servers/entropic_server.cpp:1426
Source · 88 lines
ServerResponse execute(const std::string& args_json) override;
/**
* @brief Read-only — requires only READ access.
* @return MCPAccessLevel::READ, relaxing ToolBase's WRITE default
* because this tool only reads prior delegation records.
* @req REQ-MCP-011
* @version 2.1.6
*/
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}
/** @brief Store provider pointer (non-owning).
* @param p Provider pointer.
* @utility
* @version 2.1.6
*/
void set_provider(const entropic_state_provider_t* p) {
provider_ = p;
}
private:
const entropic_state_provider_t* provider_ = nullptr;
};
/**
* @brief Wrap the provider's records in the declared `{"results": [...]}`.
*
* v2.14.0 (gh#203): followup.json always promised this envelope; the tool
* passed the provider's output through verbatim — a bare array. Records
* are reduced to the four fields i_mcp_server.h declares.
*
* @param raw Provider JSON array, or nullptr.
* @return `{"results": [{delegation_id, target_tier, summary,
* completed_at}]}`.
* @req REQ-MCP-024
* @version 2.14.0
*/
static std::string followup_results(const char* raw) {
auto rows = nlohmann::json::parse(raw == nullptr ? "[]" : raw, nullptr, false);
nlohmann::json results = nlohmann::json::array();
for (const auto& r : rows.is_array() ? rows : nlohmann::json::array()) {
nlohmann::json rec;
rec["delegation_id"] = r.value("delegation_id", "");
rec["target_tier"] = r.value("target_tier", "");
rec["summary"] = r.value("summary", "");
rec["completed_at"] = r.value("completed_at", "");
results.push_back(std::move(rec));
}
nlohmann::json out;
out["results"] = std::move(results);
return out.dump();
}
/**
* @brief Execute a followup query against prior delegations.
* @param args_json JSON with "query" and optional "max_results"
* (default 3).
* @return A ServerResponse with NO directives whose result is the
* declared `{"results": [...]}`, or a declared error (v2.14.0:
* codes, where the message used to BE the code): `invalid_args`
* for a non-object or empty query, `storage_unavailable` when no
* search provider is wired.
* @req REQ-MCP-024
* @version 2.14.0
*/
ServerResponse FollowupTool::execute(const std::string& args_json) {
auto args = nlohmann::json::parse(args_json, nullptr, false);
std::string body;
if (args.is_discarded() || !args.is_object()
|| args.value("query", "").empty()) {
body = tool_error_json("invalid_args", "'query' is required and must be non-empty");
} else if (provider_ == nullptr || provider_->search_delegations == nullptr) {
logger->warn("[followup] no search_delegations provider configured");
body = tool_error_json("storage_unavailable", "delegation storage not available");
} else {
std::string query = args.value("query", "");
int max_results = args.value("max_results", 3);
char* raw = provider_->search_delegations(
query.c_str(), max_results, provider_->user_data);
body = followup_results(raw);
std::free(raw);
logger->info("[followup] query='{}' max_results={} -> {}",
query, max_results, body);
}
return {body, {}};
}Activity · 1 steps
ServerResponse entropic::ResumeDelegationTool::execute(const std::string &args_json) override
Emit a resume-flavored delegate directive.
src/mcp/servers/entropic_server.cpp:1559
Source · 48 lines
ServerResponse execute(const std::string& args_json) override;
};
/**
* @brief Parse resume args and emit a resume-flavored DelegateDirective.
* @param args_json JSON {delegation_id?, target?, task, max_turns?}.
* @return On valid arguments, a ServerResponse with delegate +
* stop_processing directives. On non-object args, a missing
* task, or neither delegation_id nor target (gh#162), the declared
* `invalid_args` error with NO directives — validation precedes any directive
* emission.
* @req REQ-MCP-024
* @version 2.14.0
*/
ServerResponse ResumeDelegationTool::execute(const std::string& args_json) {
auto args = nlohmann::json::parse(args_json, nullptr, false);
if (args.is_discarded() || !args.is_object()) {
return {tool_error_json("invalid_args", "an arguments object is required"), {}};
}
std::string delegation_id = args.value("delegation_id", "");
std::string target = args.value("target", "");
std::string task = args.value("task", "");
int max_turns = args.value("max_turns", -1);
// gh#162: an id OR a tier. Reaching this tool used to cost a followup
// round trip on a slow local model before any work started.
if (task.empty() || (delegation_id.empty() && target.empty())) {
return {tool_error_json("invalid_args",
"'task' and one of 'delegation_id' or 'target' are required"),
{}};
}
bool by_target = delegation_id.empty();
logger->info("[resume_delegation] id='{}' target='{}' task='{}' "
"max_turns={}", delegation_id, target, task, max_turns);
nlohmann::json result;
result["action"] = "resume_delegation";
result["delegation_id"] = delegation_id;
result["target"] = target;
result["resume_by_target"] = by_target;
result["task"] = task;
result["max_turns"] = max_turns;
Directive delegate_d;
delegate_d.type = ENTROPIC_DIRECTIVE_DELEGATE;
Directive stop_d;
stop_d.type = ENTROPIC_DIRECTIVE_STOP_PROCESSING;
return {result.dump(), {delegate_d, stop_d}};
}Activity · 23 steps
Requirements
followup_results
static std::string entropic::followup_results(const char *raw)
Wrap the provider's records in the declared {"results": [...]} .
src/mcp/servers/entropic_server.cpp:1465
Source · 15 lines
static std::string followup_results(const char* raw) {
auto rows = nlohmann::json::parse(raw == nullptr ? "[]" : raw, nullptr, false);
nlohmann::json results = nlohmann::json::array();
for (const auto& r : rows.is_array() ? rows : nlohmann::json::array()) {
nlohmann::json rec;
rec["delegation_id"] = r.value("delegation_id", "");
rec["target_tier"] = r.value("target_tier", "");
rec["summary"] = r.value("summary", "");
rec["completed_at"] = r.value("completed_at", "");
results.push_back(std::move(rec));
}
nlohmann::json out;
out["results"] = std::move(results);
return out.dump();
}Activity · 12 steps
Requirements
pipeline_rejection
static std::string entropic::pipeline_rejection(const std::vector< std::string > &stages, const std::vector< std::string > &tier_names, const std::vector< std::string > &require_context_tiers, size_t refs)
Parse pipeline args, validate stages, emit directives.
src/mcp/servers/entropic_server.cpp:512
Source · 33 lines
static std::string pipeline_rejection(
const std::vector<std::string>& stages,
const std::vector<std::string>& tier_names,
const std::vector<std::string>& require_context_tiers,
size_t refs) {
std::string err;
if (stages.size() < 2) {
logger->warn("[pipeline] rejected: fewer than 2 stages");
err = tool_error_json("too_few_stages", "pipeline requires at least 2 stages");
}
for (const auto& s : stages) {
if (!err.empty()) { break; }
if (std::find(tier_names.begin(), tier_names.end(), s)
== tier_names.end()) {
logger->warn("[pipeline] invalid stage: '{}'", s);
err = tool_error_json("unknown_stage", "unknown stage \"" + s
+ "\". Valid stages: " + nlohmann::json(tier_names).dump());
} else if (refs == 0
&& std::find(require_context_tiers.begin(),
require_context_tiers.end(), s)
!= require_context_tiers.end()) {
// gh#162: one context list seeds every stage, so a stage that
// requires context refuses the whole pipeline — before any
// stage runs, not after the first has burned its turns.
logger->warn("[pipeline] refused: stage '{}' requires context", s);
err = tool_error_json("requires_context", "stage \"" + s
+ "\" requires context. Re-issue entropic.pipeline with a "
"`context` array naming at least one file path the stages "
"should read.");
}
}
return err;
}Activity · 15 steps
Requirements
register_core_tools
int entropic::EntropicServer::register_core_tools(const std::string &tools_dir)
Register core tools (todo, complete, phase_change, prune).
src/mcp/servers/entropic_server.cpp:1623
Called by EntropicServer
Calls CompleteTool, PhaseChangeTool, PruneContextTool, TodoTool, load_tool_definition
Source · 24 lines
int EntropicServer::register_core_tools(
const std::string& tools_dir) {
auto todo_def = load_tool_definition(
"todo", "entropic", tools_dir);
todo_ = std::make_unique<TodoTool>(std::move(todo_def));
register_tool(todo_.get());
auto complete_def = load_tool_definition(
"complete", "entropic", tools_dir);
complete_ = std::make_unique<CompleteTool>(
std::move(complete_def));
register_tool(complete_.get());
phase_change_ = std::make_unique<PhaseChangeTool>();
register_tool(phase_change_.get());
auto prune_def = load_tool_definition(
"prune_context", "entropic", tools_dir);
prune_context_ = std::make_unique<PruneContextTool>(
std::move(prune_def));
register_tool(prune_context_.get());
return 4;
}Activity · 12 steps
Requirements
register_delegation_tools
int entropic::EntropicServer::register_delegation_tools(const std::string &tools_dir, const std::vector< std::string > &tier_names, const std::vector< std::string > &require_context_tiers={})Register delegation tools if multi-tier.
src/mcp/servers/entropic_server.cpp:1678
Called by EntropicServer
Calls DelegateTool, PipelineTool, ResumeDelegationTool, load_tool_definition
Source · 29 lines
int EntropicServer::register_delegation_tools(
const std::string& tools_dir,
const std::vector<std::string>& tier_names,
const std::vector<std::string>& require_context_tiers) {
if (tier_names.empty()) {
return 0;
}
auto delegate_def = load_tool_definition(
"delegate", "entropic", tools_dir);
delegate_ = std::make_unique<DelegateTool>(
std::move(delegate_def), tier_names, require_context_tiers);
register_tool(delegate_.get());
auto pipeline_def = load_tool_definition(
"pipeline", "entropic", tools_dir);
pipeline_ = std::make_unique<PipelineTool>(
std::move(pipeline_def), tier_names, require_context_tiers);
register_tool(pipeline_.get());
// gh#32 (v2.1.6): resume_delegation lives alongside delegate
// because it produces the same directive kind (resume-flavored).
auto resume_def = load_tool_definition(
"resume_delegation", "entropic", tools_dir);
resume_delegation_ = std::make_unique<ResumeDelegationTool>(
std::move(resume_def), tier_names);
register_tool(resume_delegation_.get());
return 3;
}Activity · 12 steps
Requirements
register_introspection_tools
int entropic::EntropicServer::register_introspection_tools(const std::string &tools_dir)
Register introspection tools (diagnose, inspect, context_inspect).
src/mcp/servers/entropic_server.cpp:1721
Called by EntropicServer
Calls ContextInspectTool, DiagnoseTool, FollowupTool, InspectTool, load_tool_definition
Source · 22 lines
int EntropicServer::register_introspection_tools(
const std::string& tools_dir) {
diagnose_ = std::make_unique<DiagnoseTool>(
load_tool_definition("diagnose", "entropic", tools_dir));
register_tool(diagnose_.get());
inspect_ = std::make_unique<InspectTool>(
load_tool_definition("inspect", "entropic", tools_dir));
register_tool(inspect_.get());
context_inspect_ = std::make_unique<ContextInspectTool>(
load_tool_definition("context_inspect", "entropic", tools_dir));
register_tool(context_inspect_.get());
// gh#32 (v2.1.6): followup is read-only and consumes the same
// state_provider plumbing as diagnose/inspect.
followup_ = std::make_unique<FollowupTool>(
load_tool_definition("followup", "entropic", tools_dir));
register_tool(followup_.get());
return 4;
}Activity · 9 steps
Requirements
release_session
bool entropic::EntropicServer::release_session(const std::string &key) override
Release key 's todo list (gh#158).
src/mcp/servers/entropic_server.cpp:1844
Source · 3 lines
bool EntropicServer::release_session(const std::string& key) {
return todo_->release(key);
}Activity · 1 steps
Requirements
required_access_level
MCPAccessLevel entropic::DiagnoseTool::required_access_level() const override
Read-only tool requires only READ access.
src/mcp/servers/entropic_server.cpp:855
Source · 3 lines
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}Activity · 1 steps
MCPAccessLevel entropic::InspectTool::required_access_level() const override
Read-only tool requires only READ access.
src/mcp/servers/entropic_server.cpp:1059
Source · 3 lines
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}Activity · 1 steps
MCPAccessLevel entropic::ContextInspectTool::required_access_level() const override
Read-only tool requires only READ access.
src/mcp/servers/entropic_server.cpp:1114
Source · 3 lines
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}Activity · 1 steps
MCPAccessLevel entropic::FollowupTool::required_access_level() const override
Read-only — requires only READ access.
src/mcp/servers/entropic_server.cpp:1435
Source · 3 lines
MCPAccessLevel required_access_level() const override {
return MCPAccessLevel::READ;
}Activity · 1 steps
Requirements
requires_approval
bool entropic::EntropicServer::requires_approval(const std::string &tool_name) const override
Engine directives never need the host's approval (v2.14.6).
src/mcp/servers/entropic_server.cpp:1806
Source · 4 lines
bool EntropicServer::requires_approval(
const std::string& /*tool_name*/) const {
return false;
}Activity · 1 steps
Requirements
session_count
std::size_t entropic::EntropicServer::session_count() const override
Sessions holding a todo list on this server (gh#158).
src/mcp/servers/entropic_server.cpp:1854
Source · 3 lines
std::size_t EntropicServer::session_count() const {
return todo_->session_count();
}Activity · 1 steps
std::size_t entropic::TodoTool::session_count() const
Sessions holding a list (gh#158).
src/mcp/servers/entropic_server.cpp:110
Source · 1 line
std::size_t session_count() const { return lists_.session_count(); }Activity · 1 steps
Requirements
set_state_provider
void entropic::EntropicServer::set_state_provider(const entropic_state_provider_t &provider)
Set the engine state provider for introspection tools.
src/mcp/servers/entropic_server.cpp:1824
Called by SCENARIO, TEST_CASE, TEST_CASE, TEST_CASE, wire_state_provider
Calls set_provider
Source · 11 lines
void EntropicServer::set_state_provider(
const entropic_state_provider_t& provider) {
state_provider_ = provider;
diagnose_->set_provider(&state_provider_);
inspect_->set_provider(&state_provider_);
context_inspect_->set_provider(&state_provider_);
if (followup_) {
followup_->set_provider(&state_provider_);
}
logger->info("State provider set for introspection tools");
}Activity · 7 steps
Requirements
skip_duplicate_check
bool entropic::EntropicServer::skip_duplicate_check(const std::string &tool_name) const override
delegate and pipeline skip duplicate check.
src/mcp/servers/entropic_server.cpp:1786
Source · 4 lines
bool EntropicServer::skip_duplicate_check(
const std::string& tool_name) const {
return tool_name == "delegate" || tool_name == "pipeline";
}