external_bridge.cpp¶
src/facade/external_bridge.cpp
@file external_bridge.cpp @brief Unix socket MCP bridge implementation.
Owners: @tvanfossen
ExternalBridge
entropic::ExternalBridge::ExternalBridge(entropic_handle_t handle, const ExternalMCPConfig &config, const std::filesystem::path &project_dir)
Construct with engine handle and config.
src/facade/external_bridge.cpp:1410
Called by StartedBridgeFixture, start_external_bridge
Calls compute_socket_path, config
Source · 9 lines
ExternalBridge::ExternalBridge(
entropic_handle_t handle,
const ExternalMCPConfig& config,
const std::filesystem::path& project_dir)
: handle_(handle), config_(config) {
socket_path_ = config.socket_path.has_value()
? config.socket_path.value()
: compute_socket_path(project_dir);
}Activity · 1 steps
Requirements
accept_loop
void entropic::ExternalBridge::accept_loop()
Background thread: accept connections and serve.
src/facade/external_bridge.cpp:1748
Source · 45 lines
void ExternalBridge::accept_loop() {
while (running_.load()) {
struct pollfd pfd{};
pfd.fd = listen_fd_;
pfd.events = POLLIN;
int rc = poll(&pfd, 1, 500); // 500ms timeout for shutdown check
if (rc <= 0) { continue; }
int client_fd = accept(listen_fd_, nullptr, nullptr);
if (client_fd < 0) { continue; }
if (!peer_uid_matches(client_fd)) {
::close(client_fd); // v2.1.7 (gh#34): cross-uid attempt
continue;
}
logger->info("External MCP client connected (fd={})", client_fd);
auto ct = std::make_unique<ClientThread>();
ct->fd = client_fd;
// Capture a raw pointer for the thread body so the unique_ptr
// can stay in client_threads_ without aliasing.
ClientThread* raw = ct.get();
// gh#59 (v2.3.1): propagate the handle log scope into the
// per-client thread so its `serve_client` logs route to the
// owning handle's session.log.
int log_id = handle_ ? handle_->log_id : 0;
ct->thread = std::thread([this, raw, log_id]() {
entropic::log::HandleLogScope scope(log_id);
serve_client(raw->fd);
{
std::lock_guard<std::mutex> fd_lock(raw->fd_mutex);
::close(raw->fd);
raw->fd = -1;
}
logger->info("External MCP client disconnected");
raw->finished.store(true);
});
std::lock_guard<std::mutex> lock(client_threads_mutex_);
client_threads_.push_back(std::move(ct));
reap_finished_clients_locked();
}
}Activity · 22 steps
Requirements
Flows
any_cancelling_left
static bool entropic::any_cancelling_left(ExternalBridge *bridge, const std::string &session_key)
True while one session's task is still phase=cancelling.
src/facade/external_bridge.cpp:745
Source · 10 lines
static bool any_cancelling_left(ExternalBridge* bridge,
const std::string& session_key) {
std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);
bool left = false;
for (auto& [_, task] : bridge->tasks_for_cancel()) {
left = left || (task.session_key == session_key
&& task.phase == "cancelling");
}
return left;
}Activity · 5 steps
Requirements
ask_in_turn
static json entropic::ask_in_turn(entropic_handle_t handle, ExternalBridge *bridge, const json &args, const std::string &session_key, int client_fd, const json &progress_token)
Run a sync ask once this session's turn comes up (gh#144, gh#205).
src/facade/external_bridge.cpp:1064
Called by dispatch_ask
Calls ask_streaming, handle_ask, handle_ask_plain, held, turn_timeout_result, waited_ms
Source · 11 lines
static json ask_in_turn(entropic_handle_t handle, ExternalBridge* bridge,
const json& args, const std::string& session_key,
int client_fd, const json& progress_token) {
TurnTicket ticket(bridge, session_key);
if (!ticket.held()) {
return turn_timeout_result(bridge, ticket.waited_ms());
}
return bridge->ask_streaming()
? handle_ask(handle, args, session_key, client_fd, progress_token)
: handle_ask_plain(handle, args, session_key);
}Activity · 4 steps
Requirements
async_sentinel_dir
std::filesystem::path entropic::ExternalBridge::async_sentinel_dir() const
Sentinel directory (lazy: returns empty path until the engine's log_dir is configured).
src/facade/external_bridge.cpp:2366
Source · 7 lines
std::filesystem::path ExternalBridge::async_sentinel_dir() const {
std::filesystem::path root = async_sentinel_root_override_;
if (root.empty() && handle_ != nullptr) {
root = handle_->config.log_dir;
}
return root.empty() ? std::filesystem::path{} : (root / "async");
}Activity · 4 steps
Requirements
async_worker
void entropic::ExternalBridge::async_worker(const std::string &prompt, const std::string &task_id, int client_fd, const std::string &session_key, const std::string &tier)
Body of one async ask: wait, run, record, notify the owner.
src/facade/external_bridge.cpp:2168
Called by run_async_ask
Calls attach_phase_observer, begin_turn_wait, cleanup_expired_tasks, commit_async_final_state, derive_async_final_state, detach_phase_observer, end_turn_wait, fail_task_engine_busy, notify_client, run_plain_turn, task_complete_notification, update_task_phase
Source · 26 lines
void ExternalBridge::async_worker(const std::string& prompt,
const std::string& task_id, int client_fd,
const std::string& session_key,
const std::string& tier) {
long waited_ms = 0;
if (!begin_turn_wait(kTurnWaitTimeoutMs, &waited_ms, session_key)) {
fail_task_engine_busy(task_id, waited_ms);
return;
}
update_task_phase(task_id, "running", "running");
attach_phase_observer(task_id);
char* result_json = nullptr;
auto err = run_plain_turn(handle_, session_key, tier, prompt,
&result_json);
detach_phase_observer();
end_turn_wait(session_key);
auto final_state = derive_async_final_state(handle_, err, result_json,
prompt, session_key);
commit_async_final_state(task_id, final_state.status,
final_state.phase, final_state.text);
notify_client(client_fd,
task_complete_notification(task_id, final_state.status));
cleanup_expired_tasks();
logger->info("Async task {} completed: {}", task_id, final_state.status);
}Activity · 15 steps
Requirements
attach_phase_observer
void entropic::ExternalBridge::attach_phase_observer(const std::string &task_id)
Run an async entropic.ask in a background thread.
src/facade/external_bridge.cpp:1944
Called by SCENARIO, async_worker
Calls entropic_set_state_observer, phase_observer_cb
Source · 8 lines
void ExternalBridge::attach_phase_observer(const std::string& task_id) {
{
std::lock_guard<std::mutex> lock(tasks_mutex_);
active_task_id_ = task_id;
attached_gen_ = ++observer_gen_;
}
entropic_set_state_observer(handle_, phase_observer_cb, this);
}Activity · 4 steps
Requirements
begin_turn_wait
bool entropic::ExternalBridge::begin_turn_wait(long timeout_ms, long *waited_ms_out, const std::string &session_key="")
Take a ticket and wait for this caller's turn on the engine.
src/facade/external_bridge.cpp:1302
Source · 32 lines
bool ExternalBridge::begin_turn_wait(long timeout_ms, long* waited_ms_out,
const std::string& session_key) {
const auto t0 = std::chrono::steady_clock::now();
const std::string key = lane_for(session_key);
std::unique_lock<std::mutex> lock(turn_mutex_);
TurnLane& lane = lanes_[key]; // map nodes are stable across inserts
const uint64_t ticket = lane.next_ticket++;
const bool first = (ticket == lane.now_serving);
if (!first) { ++lane.waiters; }
const bool ours = turn_cv_.wait_for(
lock, std::chrono::milliseconds(timeout_ms),
[&] { return lane.now_serving == ticket; });
if (!first) { --lane.waiters; }
if (waited_ms_out != nullptr) {
*waited_ms_out = static_cast<long>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count());
}
if (!ours) {
// Timed out. Record the ticket as abandoned so that when the line
// reaches it, it is skipped rather than waited on forever. Do NOT
// advance now_serving_ here: it currently names ANOTHER caller's
// in-flight turn, and stepping over it would hand the engine to two
// callers at once — the exact race this queue exists to prevent.
lane.abandoned.insert(ticket);
return false;
}
lane.busy = true;
return true;
}Activity · 18 steps
Requirements
bind_and_listen
static bool entropic::bind_and_listen(int fd, const std::filesystem::path &path)
Bind+listen on an AF_UNIX socket, applying 0600 perms.
src/facade/external_bridge.cpp:1483
Source · 15 lines
static bool bind_and_listen(int fd, const std::filesystem::path& path) {
auto s = path.string();
if (s.size() >= sizeof(sockaddr_un::sun_path)) { return false; }
struct sockaddr_un addr{};
addr.sun_family = AF_UNIX;
std::strncpy(addr.sun_path, s.c_str(),
sizeof(addr.sun_path) - 1);
if (bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
return false;
}
::chmod(s.c_str(), S_IRUSR | S_IWUSR); // 0600 — owner only
// v2.14.0: several clients may connect at once; a backlog of 1 refused
// the second while the accept loop was busy with the first.
return listen(fd, SOMAXCONN) == 0;
}Activity · 10 steps
Requirements
bind_session_workspace
static std::string entropic::bind_session_workspace(entropic_handle_t handle, const std::string &session_key, const std::string &workspace)
Bind a session to the requested workspace, idempotently (gh#205).
src/facade/external_bridge.cpp:1029
Called by dispatch_ask
Calls bound_workspace, entropic_last_error, entropic_session_bind_workspace, resolve_workspace
Source · 17 lines
static std::string bind_session_workspace(entropic_handle_t handle,
const std::string& session_key,
const std::string& workspace) {
std::string err;
if (workspace.empty()) { return err; }
const std::string name = resolve_workspace(handle, workspace, err);
const std::string current = err.empty()
? bound_workspace(handle, session_key) : std::string{};
if (err.empty() && current != name) {
if (entropic_session_bind_workspace(handle, session_key.c_str(),
name.c_str()) != ENTROPIC_OK) {
const char* msg = entropic_last_error(handle);
err = msg ? msg : "workspace bind failed";
}
}
return err;
}Activity · 10 steps
Requirements
broadcast_notification
void entropic::ExternalBridge::broadcast_notification(const nlohmann::json ¬if)
Write a JSON-RPC notification to every subscribed fd.
src/facade/external_bridge.cpp:2294
Source · 7 lines
void ExternalBridge::broadcast_notification(const json& notif) {
const auto payload = notif.dump() + "\n";
std::lock_guard<std::mutex> lock(subscribers_mutex_);
for (auto it = subscribers_.begin(); it != subscribers_.end();) {
it = send_nonblocking(*it, payload) ? std::next(it) : subscribers_.erase(it);
}
}Activity · 4 steps
Requirements
cancel_inflight_async_tasks
static void entropic::cancel_inflight_async_tasks(entropic_handle_t handle, ExternalBridge *bridge, const std::string &session_key)
Cancel any async tasks currently running on the bridge.
src/facade/external_bridge.cpp:772
Called by handle_clear
Calls any_cancelling_left, detach_phase_observer, entropic_interrupt_session, mark_tasks_cancelling
Source · 13 lines
static void cancel_inflight_async_tasks(
entropic_handle_t handle, ExternalBridge* bridge,
const std::string& session_key) {
if (bridge == nullptr) { return; }
// v2.14.0: THIS session's run only. entropic_interrupt is handle-wide —
// clearing session A used to cancel session B's turn.
entropic_interrupt_session(handle, session_key.c_str());
if (!mark_tasks_cancelling(bridge, session_key)) { return; }
for (int i = 0; i < 20 && any_cancelling_left(bridge, session_key); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
bridge->detach_phase_observer(); // bump gen; silences any stale observer
}Activity · 8 steps
Requirements
cleanup_expired_tasks
void entropic::ExternalBridge::cleanup_expired_tasks()
Remove tasks older than TTL from the registry.
src/facade/external_bridge.cpp:2332
Source · 21 lines
void ExternalBridge::cleanup_expired_tasks() {
auto cutoff = std::chrono::steady_clock::now()
- std::chrono::minutes(15);
auto sentinel_dir = async_sentinel_dir();
std::lock_guard<std::mutex> lock(tasks_mutex_);
for (auto it = tasks_.begin(); it != tasks_.end(); ) {
if (it->second.created < cutoff) {
if (!sentinel_dir.empty()) {
for (const char* suffix :
{".done", ".failed", ".cancelled"}) {
std::error_code ec;
std::filesystem::remove(
sentinel_dir / (it->first + suffix), ec);
}
}
it = tasks_.erase(it);
} else {
++it;
}
}
}Activity · 12 steps
Requirements
create_listen_socket
static int entropic::create_listen_socket(const std::filesystem::path &path)
Create, bind, and listen on a unix domain socket.
src/facade/external_bridge.cpp:1514
Source · 17 lines
static int create_listen_socket(const std::filesystem::path& path) {
prepare_socket_dir(path.parent_path());
if (!socket_path_safe(path)) { return -1; }
std::filesystem::remove(path);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
bool ok = (fd >= 0) && bind_and_listen(fd, path);
if (!ok) {
logger->error("Socket setup failed for {}: {}",
path.string(), std::strerror(errno));
if (fd >= 0) { ::close(fd); }
return -1;
}
// v2.14.0: the old line labelled ~/.entropic as "project_dir(canonical)".
logger->info("External MCP bridge ready: socket={}", path.string());
return fd;
}Activity · 13 steps
Requirements
derive_async_final_state
static AsyncFinalState entropic::derive_async_final_state(entropic_handle_t handle, entropic_error_t err, char *result_json, const std::string &prompt, const std::string &session_key)
Translate entropic_run's return code into a final task state.
src/facade/external_bridge.cpp:682
Called by async_worker
Calls entropic_free, entropic_free, entropic_last_error, final_text_or_reason, session_tool_names
Source · 30 lines
static AsyncFinalState derive_async_final_state(
entropic_handle_t handle,
entropic_error_t err,
char* result_json,
const std::string& prompt,
const std::string& session_key) {
AsyncFinalState s{"error", "failed", ""};
const char* msg = entropic_last_error(handle);
if (err == ENTROPIC_ERROR_CANCELLED
|| err == ENTROPIC_ERROR_INTERRUPTED) {
s = {"cancelled", "cancelled", msg ? msg : "cancelled"};
} else if (err == ENTROPIC_ERROR_TURN_FAILED) {
// gh#209/#212 (v2.14.5): the turn ran and the engine failed it.
// last_error carries the reason and any unconfirmed text.
s.text = std::string("error: turn failed — ") + (msg ? msg : "unknown");
} else if (err != ENTROPIC_OK) {
s.text = msg ? msg : "unknown error";
} else {
// gh#130 (v2.10.2): same selection rule as the sync paths. This one
// had no fallback at all, so a stalled async ask reported
// status="done" with empty text — even less diagnosable than the
// sync path's "(no response)". gh#209: bounded to this turn.
const auto names = session_tool_names(handle, session_key);
s = {"done", "done",
facade_text::final_text_or_reason(result_json, prompt.c_str(),
&names)};
}
entropic_free(result_json);
return s;
}Activity · 15 steps
Requirements
detach_phase_observer
void entropic::ExternalBridge::detach_phase_observer()
Clear the phase observer installed by attach_phase_observer.
src/facade/external_bridge.cpp:1965
Called by SCENARIO, async_worker, cancel_inflight_async_tasks
Source · 8 lines
void ExternalBridge::detach_phase_observer() {
{
std::lock_guard<std::mutex> lock(tasks_mutex_);
++observer_gen_;
active_task_id_.clear();
}
entropic_set_state_observer(handle_, nullptr, nullptr);
}Activity · 4 steps
Requirements
dispatch
std::string entropic::ExternalBridge::dispatch(const std::string &request, int client_fd)
Dispatch one JSON-RPC request and return the response.
src/facade/external_bridge.cpp:1883
Called by SCENARIO, ask, call, call_release, handle_post, stream_call
Calls dispatch_tool, initialize_result, rpc_err, rpc_ok, tool_definitions
Source · 26 lines
std::string ExternalBridge::dispatch(
const std::string& request, int client_fd) {
auto req = json::parse(request, nullptr, false);
// Parse error or notification (no id) → no dispatch
if (req.is_discarded() || !req.contains("id")) {
return req.is_discarded()
? rpc_err(nullptr, -32700, "Parse error")
: std::string{};
}
json id = req["id"];
std::string method = req.value("method", std::string{});
json params = req.value("params", json::object());
json result;
if (method == "initialize") { result = initialize_result(config_); }
else if (method == "tools/list") { result = {{"tools", tool_definitions(config_)}}; }
else if (method == "tools/call") {
auto id_str = id.is_string() ? id.get<std::string>()
: id.dump();
result = dispatch_tool(handle_, this, params, client_fd, id_str);
}
else if (method == "shutdown" || method == "exit") { result = json::object(); }
else { return rpc_err(id, -32601, "Unknown method: " + method); }
return rpc_ok(id, result);
}Activity · 22 steps
Requirements
dispatch_ask
static json entropic::dispatch_ask(entropic_handle_t handle, ExternalBridge *bridge, const json &args, int client_fd, const json &progress_token)
Route entropic.ask — sync (streaming) or async.
src/facade/external_bridge.cpp:1087
Called by dispatch_tool
Calls ask_in_turn, bind_session_workspace, generate_task_id, run_async_ask, tool_text
Source · 29 lines
static json dispatch_ask(entropic_handle_t handle,
ExternalBridge* bridge,
const json& args,
int client_fd,
const json& progress_token) {
// gh#144 (v2.12.0): optional. Absent means the shared default session,
// i.e. exactly what every pre-2.12.0 client already gets.
const std::string session_key = args.value("session", std::string{});
// gh#205 (v2.14.0): bind the session to its repository before it runs.
const std::string ws_err = bind_session_workspace(
handle, session_key, args.value("workspace", std::string{}));
json result;
if (!ws_err.empty()) {
result = tool_text("error: " + ws_err);
} else if (args.value("async", false)) {
// The async worker takes its own ticket inside run_async_ask — it
// must not hold one here, or registering the task would block behind
// an in-flight turn and defeat the point of async.
auto task_id = generate_task_id();
bridge->run_async_ask(
args.value("prompt", ""), task_id, client_fd, session_key,
args.value("tier", std::string{}));
result = tool_text("async task started: " + task_id);
} else {
result = ask_in_turn(handle, bridge, args, session_key, client_fd,
progress_token);
}
return result;
}Activity · 13 steps
Requirements
dispatch_tool
static json entropic::dispatch_tool(entropic_handle_t handle, ExternalBridge *bridge, const json ¶ms, int client_fd, const std::string &call_id)
Dispatch a tools/call to the appropriate handler.
src/facade/external_bridge.cpp:1263
Called by dispatch
Calls config, dispatch_ask, strip_tool_prefix, tool_handlers, tool_text
Source · 28 lines
static json dispatch_tool(entropic_handle_t handle,
ExternalBridge* bridge,
const json& params,
int client_fd,
const std::string& call_id) {
std::string name = params.value("name", std::string{});
json args = params.value("arguments", json::object());
// gh#145: strip the configured namespace, then match bare suffixes
// against the same table tool_definitions() advertised from.
const std::string suffix =
facade::strip_tool_prefix(
bridge->config().tool_prefix, name);
if (suffix == tool_suffix::kAsk) {
// v2.14.0: the client's own _meta.progressToken when it sent one
// (MCP), else the request id so pre-2.14.0 clients keep streaming.
json token = call_id;
if (params.contains("_meta") && params["_meta"].is_object()
&& params["_meta"].contains("progressToken")) {
token = params["_meta"]["progressToken"];
}
return dispatch_ask(handle, bridge, args, client_fd, token);
}
const auto& handlers = tool_handlers();
const auto it = handlers.find(suffix);
return it == handlers.end()
? tool_text("error: unknown tool '" + name + "'")
: it->second(handle, bridge, args);
}Activity · 11 steps
Requirements
end_turn_wait
void entropic::ExternalBridge::end_turn_wait(const std::string &session_key="")
Hand the turn to the next ticket in this session's lane.
src/facade/external_bridge.cpp:1340
Source · 19 lines
void ExternalBridge::end_turn_wait(const std::string& session_key) {
{
std::lock_guard<std::mutex> lock(turn_mutex_);
auto it = lanes_.find(lane_for(session_key));
if (it != lanes_.end()) {
TurnLane& lane = it->second;
lane.busy = false;
++lane.now_serving;
// Step over anyone who gave up while waiting, or the line stalls
// on a ticket whose owner is long gone.
while (lane.abandoned.erase(lane.now_serving) > 0) {
++lane.now_serving;
}
// An idle lane holds nothing worth keeping.
if (lane.now_serving == lane.next_ticket) { lanes_.erase(it); }
}
}
turn_cv_.notify_all();
}Activity · 11 steps
Requirements
final_answer_from_context
static json entropic::final_answer_from_context(entropic_handle_t handle, const std::string &session_key, entropic_error_t err, const std::string &prompt)
Read the live conversation and render the operator-visible answer.
src/facade/external_bridge.cpp:445
Called by handle_ask
Calls entropic_free, entropic_free, entropic_session_context_get, render_turn
Source · 10 lines
static json final_answer_from_context(entropic_handle_t handle,
const std::string& session_key,
entropic_error_t err,
const std::string& prompt) {
char* msgs_json = nullptr;
entropic_session_context_get(handle, session_key.c_str(), &msgs_json);
auto result = render_turn(handle, session_key, err, msgs_json, prompt);
entropic_free(msgs_json);
return result;
}Activity · 5 steps
Requirements
handle_ask
static json entropic::handle_ask(entropic_handle_t handle, const json &args, const std::string &session_key, int client_fd, const json &progress_token)
Handle entropic.ask — stream tokens then return final text.
src/facade/external_bridge.cpp:558
Called by ask_in_turn
Calls entropic_last_error, final_answer_from_context, on_token, run_stream_turn, send_progress, tool_error, tool_text
Source · 26 lines
static json handle_ask(entropic_handle_t handle, const json& args,
const std::string& session_key,
int client_fd, const json& progress_token) {
auto it = args.find("prompt");
if (it == args.end() || !it->is_string()) {
return tool_text("error: missing 'prompt' argument");
}
std::string prompt = it->get<std::string>();
// Stream tokens as progress notifications
struct StreamCtx { int fd; json token; uint64_t seq; };
StreamCtx sctx{client_fd, progress_token, 0};
auto on_token = [](const char* tok, size_t len, void* ud) {
auto* ctx = static_cast<StreamCtx*>(ud);
send_progress(ctx->fd, std::string(tok, len), ctx->token, ++ctx->seq);
};
// gh#205: a requested tier locks the turn; absent routes as before.
auto err = run_stream_turn(handle, session_key,
args.value("tier", std::string{}), prompt,
on_token, &sctx);
if (err != ENTROPIC_OK && err != ENTROPIC_ERROR_TURN_FAILED) {
const char* msg = entropic_last_error(handle);
return tool_error(std::string("error: ") + (msg ? msg : "unknown"));
}
return final_answer_from_context(handle, session_key, err, prompt);
}Activity · 12 steps
Requirements
handle_ask_plain
static json entropic::handle_ask_plain(entropic_handle_t handle, const json &args, const std::string &session_key)
Handle entropic.ask — non-streaming path (gh#115, v2.9.12).
src/facade/external_bridge.cpp:518
Called by ask_in_turn
Calls entropic_free, entropic_free, entropic_last_error, render_turn, run_plain_turn, tool_error, tool_text
Source · 22 lines
static json handle_ask_plain(entropic_handle_t handle, const json& args,
const std::string& session_key) {
auto it = args.find("prompt");
if (it == args.end() || !it->is_string()) {
return tool_text("error: missing 'prompt' argument");
}
char* result_json = nullptr;
const auto prompt = it->get<std::string>();
auto err = run_plain_turn(handle, session_key,
args.value("tier", std::string{}), // gh#205
prompt, &result_json);
json out;
if (err == ENTROPIC_OK || err == ENTROPIC_ERROR_TURN_FAILED) {
// Resolve before the free — render_turn reads that buffer.
out = render_turn(handle, session_key, err, result_json, prompt);
} else {
const char* msg = entropic_last_error(handle);
out = tool_error(std::string("error: ") + (msg ? msg : "unknown"));
}
entropic_free(result_json);
return out;
}Activity · 14 steps
Requirements
handle_ask_status
json entropic::ExternalBridge::handle_ask_status(const nlohmann::json &args)
Handle entropic.ask_status — check async task state.
src/facade/external_bridge.cpp:843
Source · 15 lines
json ExternalBridge::handle_ask_status(const json& args) {
auto tid = args.value("task_id", std::string{});
std::lock_guard<std::mutex> lock(tasks_mutex_);
auto it = tasks_.find(tid);
if (it == tasks_.end()) {
return tool_text("error: unknown task_id");
}
json status = {{"status", it->second.status},
{"phase", it->second.phase}};
if (!it->second.result.empty()) {
auto key = (it->second.status == "error") ? "error" : "result";
status[key] = it->second.result;
}
return tool_text(status.dump());
}Activity · 10 steps
Requirements
handle_clear
static json entropic::handle_clear(entropic_handle_t handle, ExternalBridge *bridge, const std::string &session_key)
entropic.context_clear MCP tool handler.
src/facade/external_bridge.cpp:798
Called by tool_handlers
Calls cancel_inflight_async_tasks, entropic_session_context_clear, tool_text
Source · 16 lines
static json handle_clear(entropic_handle_t handle,
ExternalBridge* bridge,
const std::string& session_key) {
cancel_inflight_async_tasks(handle, bridge, session_key);
// gh#144 (v2.12.0): clear ONLY the named session. The unscoped clear
// wiped every caller's context, which the issue correctly observed "is
// not isolation" — with two callers active there is no ordering in which
// it is correct.
auto err = entropic_session_context_clear(handle, session_key.c_str());
if (err != ENTROPIC_OK) {
return tool_text("error: clear failed");
}
return tool_text(session_key.empty()
? "conversation cleared"
: "conversation cleared for session '" + session_key + "'");
}Activity · 5 steps
Requirements
handle_count
static json entropic::handle_count(entropic_handle_t handle, const std::string &session_key)
Handle entropic.context_count .
src/facade/external_bridge.cpp:822
Source · 7 lines
static json handle_count(entropic_handle_t handle,
const std::string& session_key) {
size_t count = 0;
// gh#144 (v2.12.0): count only the named session.
entropic_session_context_count(handle, session_key.c_str(), &count);
return tool_text(std::to_string(count));
}Activity · 3 steps
Requirements
handle_release
static json entropic::handle_release(entropic_handle_t handle)
release : unload every resident model, keep everything else.
src/facade/external_bridge.cpp:1155
Called by tool_handlers
Calls entropic_last_error, entropic_release_model, resident_tiers, tool_text
Source · 21 lines
static json handle_release(entropic_handle_t handle) {
const std::string before = resident_tiers(handle);
const entropic_error_t rc = entropic_release_model(handle, nullptr);
json result;
if (rc == ENTROPIC_ERROR_ALREADY_RUNNING) {
result = tool_text("error: a turn is running on this engine; nothing "
"was released — retry when it finishes");
result["isError"] = true;
} else if (rc != ENTROPIC_OK) {
const char* why = entropic_last_error(handle);
result = tool_text(std::string("error: release failed: ")
+ (why != nullptr ? why : "unknown"));
result["isError"] = true;
} else {
result = tool_text(before.empty()
? "released: nothing was resident"
: "released: " + before + " — sessions kept; the next ask reloads");
}
logger->info("[release] rc={} resident_before='{}'", static_cast<int>(rc), before);
return result;
}Activity · 15 steps
Requirements
handle_shutdown
static json entropic::handle_shutdown(entropic_handle_t handle, ExternalBridge *bridge)
Handle .shutdown : stop the host over MCP (v2.14.6).
src/facade/external_bridge.cpp:1195
Source · 19 lines
static json handle_shutdown(entropic_handle_t handle, ExternalBridge* bridge) {
if (!bridge->config().allow_shutdown) {
return tool_text("error: unknown tool 'shutdown'");
}
const bool claimed = handle->engine == nullptr
|| handle->engine->try_begin_turn("__shutdown__", /*exclusive=*/true);
if (!claimed) {
return tool_error("error: a turn is running on this engine; not "
"stopping — retry when it finishes");
}
logger->warn("[shutdown] accepted over MCP — stopping the host");
std::thread([] {
// Let the reply reach the client before teardown closes the listener.
std::this_thread::sleep_for(std::chrono::milliseconds(250));
::kill(::getpid(), SIGTERM);
}).detach();
return tool_text("stopping: the host is shutting down — models unloaded, "
"sessions ended, token removed");
}Activity · 8 steps
Requirements
handle_status
static json entropic::handle_status(entropic_handle_t handle, const ExternalBridge *bridge)
Handle the status tool.
src/facade/external_bridge.cpp:604
Called by tool_handlers
Calls entropic_context_count, entropic_free, entropic_free, entropic_metrics_json, entropic_session_list, entropic_version, tool_text, turn_in_flight, turn_queue_depth
Source · 26 lines
static json handle_status(entropic_handle_t handle,
const ExternalBridge* bridge) {
size_t count = 0;
entropic_context_count(handle, &count);
std::ostringstream os;
os << "entropic " << entropic_version()
<< "\nmessages: " << count
<< "\nbusy: " << (bridge->turn_in_flight() ? "true" : "false")
<< "\nqueue_depth: " << bridge->turn_queue_depth();
// gh#144 (v2.12.0): which callers this host is serving, and how much
// history each holds.
char* sessions = nullptr;
if (entropic_session_list(handle, &sessions) == ENTROPIC_OK
&& sessions != nullptr) {
os << "\nsessions: " << sessions;
entropic_free(sessions);
}
// Metrics + per-tier breakdown (P2-15 follow-up, 2.0.6-rc16.2)
char* mjson = nullptr;
if (entropic_metrics_json(handle, &mjson) == ENTROPIC_OK
&& mjson != nullptr) {
os << "\nmetrics: " << mjson;
entropic_free(mjson);
}
return tool_text(os.str());
}Activity · 13 steps
Requirements
initialize_result
static json entropic::initialize_result(const ExternalMCPConfig &cfg)
Build the MCP initialize response payload.
src/facade/external_bridge.cpp:1859
Source · 10 lines
static json initialize_result(const ExternalMCPConfig& cfg) {
const std::string name =
cfg.server_name.empty() ? "entropic" : cfg.server_name;
return {
{"protocolVersion", "2025-06-18"},
{"serverInfo", {{"name", name},
{"version", entropic_version()}}},
{"capabilities", {{"tools", json::object()}}}
};
}Activity · 2 steps
Requirements
mark_tasks_cancelling
static bool entropic::mark_tasks_cancelling(ExternalBridge *bridge, const std::string &session_key)
Mark one session's queued/running tasks as cancelling.
src/facade/external_bridge.cpp:721
Source · 15 lines
static bool mark_tasks_cancelling(ExternalBridge* bridge,
const std::string& session_key) {
std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);
bool any = false;
for (auto& [_, task] : bridge->tasks_for_cancel()) {
// v2.14.0: only the cleared session's tasks.
if (task.session_key != session_key) { continue; }
if (task.status == "queued" || task.status == "running") {
task.status = "cancelled";
task.phase = "cancelling";
any = true;
}
}
return any;
}Activity · 10 steps
Requirements
peer_uid_matches
static bool entropic::peer_uid_matches(int client_fd)
Validate that the connecting peer shares the engine's UID.
src/facade/external_bridge.cpp:1546
Source · 17 lines
static bool peer_uid_matches(int client_fd) {
struct ucred cred{};
socklen_t len = sizeof(cred);
if (getsockopt(client_fd, SOL_SOCKET, SO_PEERCRED,
&cred, &len) != 0) {
logger->warn("SO_PEERCRED failed on fd={}: {}",
client_fd, std::strerror(errno));
return false;
}
if (cred.uid != ::geteuid()) {
logger->warn(
"Rejecting MCP client on fd={}: peer uid {} != engine uid {}",
client_fd, cred.uid, ::geteuid());
return false;
}
return true;
}Activity · 9 steps
Requirements
Flows
prepare_socket_dir
static void entropic::prepare_socket_dir(const std::filesystem::path &parent)
Prepare the socket containing directory with 0700 perms.
src/facade/external_bridge.cpp:1440
Source · 5 lines
static void prepare_socket_dir(const std::filesystem::path& parent) {
std::error_code ec;
std::filesystem::create_directories(parent, ec);
::chmod(parent.c_str(), S_IRWXU); // 0700
}Activity · 3 steps
Requirements
reap_finished_clients_locked
void entropic::ExternalBridge::reap_finished_clients_locked()
Reap finished client threads from client_threads_.
src/facade/external_bridge.cpp:1711
Source · 11 lines
void ExternalBridge::reap_finished_clients_locked() {
auto it = client_threads_.begin();
while (it != client_threads_.end()) {
if ((*it)->finished.load()) {
if ((*it)->thread.joinable()) { (*it)->thread.join(); }
it = client_threads_.erase(it);
} else {
++it;
}
}
}Activity · 8 steps
Flows
render_turn
static json entropic::render_turn(entropic_handle_t handle, const std::string &session_key, entropic_error_t err, const char *convo, const std::string &prompt)
Render a finished turn as the ask tool result.
src/facade/external_bridge.cpp:413
Called by final_answer_from_context, handle_ask_plain
Calls entropic_last_error, final_text_or_reason, session_tool_names, tool_error, tool_text
Source · 12 lines
static json render_turn(entropic_handle_t handle, const std::string& session_key,
entropic_error_t err, const char* convo,
const std::string& prompt) {
if (err == ENTROPIC_ERROR_TURN_FAILED) {
const char* msg = entropic_last_error(handle);
return tool_error(std::string("error: turn failed — ")
+ (msg ? msg : "unknown"));
}
const auto names = session_tool_names(handle, session_key);
return tool_text(
facade_text::final_text_or_reason(convo, prompt.c_str(), &names));
}Activity · 5 steps
Requirements
run_async_ask
void entropic::ExternalBridge::run_async_ask(const std::string &prompt, const std::string &task_id, int client_fd, const std::string &session_key="", const std::string &tier="")
Run an ask on a background worker and notify its owner.
src/facade/external_bridge.cpp:2074
Called by SCENARIO, TEST_CASE, dispatch_ask
Calls async_worker, reap_finished_async_locked
Source · 34 lines
void ExternalBridge::run_async_ask(
const std::string& prompt,
const std::string& task_id,
int client_fd,
const std::string& session_key,
const std::string& tier) {
{
std::lock_guard<std::mutex> lock(tasks_mutex_);
AsyncTask t;
t.status = "queued";
t.phase = "queued";
t.created = std::chrono::steady_clock::now();
t.session_key = session_key; // v2.14.0: clear cancels per session
t.owner_fd = client_fd; // v2.14.0: only the owner is notified
tasks_[task_id] = std::move(t);
}
// gh#59 (v2.3.1): the async-ask worker runs entropic_run on this
// handle's behalf — scope its logs to the owning handle.
int log_id = handle_ ? handle_->log_id : 0;
// v2.14.2: owned and joined by stop(), no longer detached — a detached
// worker outliving the bridge touched freed memory (TSan).
auto worker = std::make_unique<AsyncWorker>();
AsyncWorker* raw = worker.get();
std::lock_guard<std::mutex> lock(async_workers_mutex_);
reap_finished_async_locked();
worker->thread = std::thread([this, raw, prompt, task_id, client_fd,
log_id, session_key, tier]() {
entropic::log::HandleLogScope scope(log_id);
async_worker(prompt, task_id, client_fd, session_key, tier);
raw->finished.store(true);
});
async_workers_.push_back(std::move(worker));
}Activity · 15 steps
Requirements
sentinel_suffix_for_status
static const char * entropic::sentinel_suffix_for_status(const std::string &status)
Map a terminal status string to a sentinel filename suffix.
src/facade/external_bridge.cpp:2390
Source · 10 lines
static const char* sentinel_suffix_for_status(
const std::string& status) {
const char* suffix = ".done";
if (status == "error") {
suffix = ".failed";
} else if (status == "cancelled") {
suffix = ".cancelled";
}
return suffix;
}Activity · 7 steps
Requirements
serve_client
void entropic::ExternalBridge::serve_client(int client_fd)
Serve a single connected client until disconnect.
src/facade/external_bridge.cpp:1822
Source · 21 lines
void ExternalBridge::serve_client(int client_fd) {
subscribe(client_fd);
struct Unsub {
ExternalBridge* self;
int fd;
~Unsub() { self->unsubscribe(fd); }
} guard{this, client_fd};
while (running_.load()) {
auto line = read_line(client_fd);
if (line.empty()) { break; }
auto response = dispatch(line, client_fd);
if (response.empty()) { continue; } // notification — no reply
response += '\n';
ssize_t written = write(client_fd, response.c_str(),
response.size());
if (written < 0) { break; }
}
}Activity · 13 steps
Requirements
Flows
session_tool_names
static facade_text::ToolNames entropic::session_tool_names(entropic_handle_t handle, const std::string &session_key)
The tool names a session's turns can see (gh#212 bare-name rule).
src/facade/external_bridge.cpp:385
Called by derive_async_final_state, render_turn
Calls tool_names_of, workspace_servers
Source · 6 lines
static facade_text::ToolNames session_tool_names(entropic_handle_t handle,
const std::string& session_key) {
auto* servers = entropic::workspace_servers(handle, session_key);
return servers != nullptr ? facade_text::tool_names_of(servers->list_tools())
: facade_text::ToolNames{};
}Activity · 2 steps
Requirements
set_async_sentinel_root
void entropic::ExternalBridge::set_async_sentinel_root(const std::filesystem::path &root)
Override the async sentinel root directory.
src/facade/external_bridge.cpp:2379
Source · 4 lines
void ExternalBridge::set_async_sentinel_root(
const std::filesystem::path& root) {
async_sentinel_root_override_ = root;
}Activity · 1 steps
Requirements
socket_path_safe
static bool entropic::socket_path_safe(const std::filesystem::path &path)
Reject a pre-existing path that is a symlink or non-socket.
src/facade/external_bridge.cpp:1459
Source · 15 lines
static bool socket_path_safe(const std::filesystem::path& path) {
struct stat st{};
if (::lstat(path.c_str(), &st) != 0) {
return errno == ENOENT; // absent is fine
}
bool is_symlink = S_ISLNK(st.st_mode);
bool is_socket = S_ISSOCK(st.st_mode);
if (!is_socket || is_symlink) {
logger->error(
"Refusing to bind: {} is a {} (expected unix socket)",
path.string(),
is_symlink ? "symlink" : "non-socket file");
}
return is_socket && !is_symlink;
}Activity · 8 steps
Requirements
start
bool entropic::ExternalBridge::start()
Start the background accept loop.
src/facade/external_bridge.cpp:1570
Called by SCENARIO, TEST_CASE, start_external_bridge
Calls accept_loop, create_listen_socket
Source · 55 lines
bool ExternalBridge::start() {
// v2.14.0: a key that bounds nothing must say so rather than look like
// a control (cf. gh#175).
if (config_.rate_limit != ExternalMCPConfig{}.rate_limit) {
logger->warn("mcp.external.rate_limit={} is not enforced and is "
"ignored", config_.rate_limit);
}
// Refuse to start if another handle in this process already owns
// this socket path. The pre-fix create_listen_socket call unlinks
// any existing socket file before binding — that's correct for
// crashed-prior-process recovery, but if a live in-process bridge
// owned that file, the unlink stole its binding silently. The
// claim must happen *before* create_listen_socket so a concurrent
// start() on a colliding path cannot pass the check and then race
// into the unlink.
std::error_code ec;
auto canonical =
std::filesystem::weakly_canonical(socket_path_, ec).string();
if (ec) { canonical = socket_path_.string(); }
{
std::lock_guard lk(s_bound_sockets_mu);
if (!s_bound_sockets.insert(canonical).second) {
logger->warn(
"External MCP bridge: socket {} already bound by another "
"handle in this process; declining to start. Set "
"external.socket_path to a distinct path per handle "
"if you need per-handle bridges.",
canonical);
return false;
}
}
listen_fd_ = create_listen_socket(socket_path_);
if (listen_fd_ < 0) {
std::lock_guard lk(s_bound_sockets_mu);
s_bound_sockets.erase(canonical);
return false;
}
bound_canonical_ = canonical;
running_.store(true);
// gh#59 (v2.3.1): the accept thread (and the per-client serve
// threads it spawns) need to log on this handle's behalf — install
// a HandleLogScope at the top of each thread body so spdlog lines
// route through HandleAwareSink to this handle's session.log.
int log_id = handle_ ? handle_->log_id : 0;
accept_thread_ = std::thread([this, log_id]() {
entropic::log::HandleLogScope scope(log_id);
accept_loop();
});
logger->info("External MCP bridge listening on {}",
socket_path_.string());
return true;
}Activity · 21 steps
Requirements
stop
void entropic::ExternalBridge::stop()
Stop the accept loop and close the socket.
src/facade/external_bridge.cpp:1646
Called by SCENARIO, TEST_CASE, entropic_destroy, ~ExternalBridge, ~StartedBridgeFixture
Calls join_async_workers
Source · 52 lines
void ExternalBridge::stop() {
running_.store(false);
// v2.14.0: the accept thread READS listen_fd_ every poll, so it must be
// joined before listen_fd_ is written. shutdown() wakes a blocked
// poll/accept without touching the variable; the loop then sees
// running_ == false (it re-checks at least every 500 ms regardless).
// Closing first was a data race TSan reported the first time a test
// destroyed a handle with the bridge enabled.
if (listen_fd_ >= 0) { ::shutdown(listen_fd_, SHUT_RDWR); }
if (accept_thread_.joinable()) {
accept_thread_.join();
}
if (listen_fd_ >= 0) {
::close(listen_fd_);
listen_fd_ = -1;
}
// Wake every connected client's blocking read so the per-client
// thread can observe the disconnect and exit. shutdown(SHUT_RDWR)
// on a connected socket returns EOF to the peer; the read in
// serve_client returns 0 and read_line returns "" → exits.
std::vector<std::unique_ptr<ClientThread>> drained;
{
std::lock_guard<std::mutex> lock(client_threads_mutex_);
drained = std::move(client_threads_);
client_threads_.clear();
}
for (auto& ct : drained) {
// v2.14.2: under the client's fd_mutex — its thread may be closing
// the same descriptor right now (TSan).
std::lock_guard<std::mutex> fd_lock(ct->fd_mutex);
if (ct->fd >= 0) { ::shutdown(ct->fd, SHUT_RDWR); }
}
for (auto& ct : drained) {
if (ct->thread.joinable()) { ct->thread.join(); }
}
join_async_workers(); // v2.14.2: no worker may outlive the bridge
// Clean up socket file
std::error_code ec;
std::filesystem::remove(socket_path_, ec);
// Release our claim on the canonical path so a later handle in
// this process can re-bind. Use the exact string we inserted in
// start(); recomputing weakly_canonical here could differ if the
// path was deleted mid-run.
if (!bound_canonical_.empty()) {
std::lock_guard lk(s_bound_sockets_mu);
s_bound_sockets.erase(bound_canonical_);
bound_canonical_.clear();
}
}Activity · 26 steps
Requirements
Flows
subscribe
void entropic::ExternalBridge::subscribe(int fd)
Add a connected fd to the subscriber set.
src/facade/external_bridge.cpp:2206
Source · 4 lines
void ExternalBridge::subscribe(int fd) {
std::lock_guard<std::mutex> lock(subscribers_mutex_);
subscribers_.insert(fd);
}Activity · 2 steps
Requirements
Flows
tool_definitions
static json entropic::tool_definitions(const ExternalMCPConfig &cfg)
MCP tool definitions exposed by the bridge.
src/facade/external_bridge.cpp:302
Called by dispatch
Calls ask_status_tool, ask_tool, no_args_tool, session_scoped_tool
Source · 26 lines
static json tool_definitions(const ExternalMCPConfig& cfg) {
auto tools = json::array({
ask_tool(cfg),
ask_status_tool(cfg),
no_args_tool(cfg, tool_suffix::kStatus,
"Engine version and message count."),
session_scoped_tool(cfg, tool_suffix::kContextClear,
"Clear conversation history."),
session_scoped_tool(cfg, tool_suffix::kContextCount,
"Return the message count."),
// v2.14.3: the one way an MCP client can give the card back.
no_args_tool(cfg, tool_suffix::kRelease,
"Unload every loaded model to free GPU/host memory. "
"Sessions and their conversations are kept; the next "
"ask reloads the model. Call when you are done for "
"now. Refused while a turn is running — retry then."),
});
// v2.14.6: only when the host opted in (entropic serve --allow-shutdown).
if (cfg.allow_shutdown) {
tools.push_back(no_args_tool(cfg, tool_suffix::kShutdown,
"Stop this host process: models are unloaded, every session "
"ends, the token is removed. Refused while a turn is running — "
"retry then. Use release instead to only free the GPU."));
}
return tools;
}Activity · 4 steps
Requirements
tool_handlers
static const std::unordered_map< std::string, ToolHandler > & entropic::tool_handlers()
Non-ask tools by suffix (v2.14.3).
src/facade/external_bridge.cpp:1229
Called by dispatch_tool
Calls handle_ask_status, handle_clear, handle_count, handle_release, handle_shutdown, handle_status
Source · 17 lines
static const std::unordered_map<std::string, ToolHandler>& tool_handlers() {
static const std::unordered_map<std::string, ToolHandler> table = {
{tool_suffix::kAskStatus, [](entropic_handle_t, ExternalBridge* b, const json& a) {
return b->handle_ask_status(a); }},
{tool_suffix::kStatus, [](entropic_handle_t h, ExternalBridge* b, const json&) {
return handle_status(h, b); }},
{tool_suffix::kContextClear, [](entropic_handle_t h, ExternalBridge* b, const json& a) {
return handle_clear(h, b, a.value("session", std::string{})); }},
{tool_suffix::kContextCount, [](entropic_handle_t h, ExternalBridge*, const json& a) {
return handle_count(h, a.value("session", std::string{})); }},
{tool_suffix::kRelease, [](entropic_handle_t h, ExternalBridge*, const json&) {
return handle_release(h); }},
{tool_suffix::kShutdown, [](entropic_handle_t h, ExternalBridge* b, const json&) {
return handle_shutdown(h, b); }},
};
return table;
}Activity · 2 steps
Requirements
turn_timeout_result
json entropic::anonymous_namespace{external_bridge.cpp}::turn_timeout_result(const ExternalBridge *bridge, long waited_ms)The tool result returned when the queue deadline expired.
src/facade/external_bridge.cpp:947
Source · 7 lines
json turn_timeout_result(const ExternalBridge* bridge, long waited_ms) {
std::ostringstream os;
os << "error: engine busy — waited " << waited_ms << " ms with "
<< bridge->turn_queue_depth() << " request(s) still ahead. "
<< "Another caller's turn is still running; retry shortly.";
return tool_text(os.str());
}Activity · 3 steps
Requirements
unsubscribe
void entropic::ExternalBridge::unsubscribe(int fd)
Remove an fd from the subscriber set.
src/facade/external_bridge.cpp:2217
Source · 4 lines
void ExternalBridge::unsubscribe(int fd) {
std::lock_guard<std::mutex> lock(subscribers_mutex_);
subscribers_.erase(fd);
}Activity · 2 steps
Requirements
update_task_phase
void entropic::ExternalBridge::update_task_phase(const std::string &task_id, const std::string &status, const std::string &phase)
Update status/phase for a tracked task atomically.
src/facade/external_bridge.cpp:2310
Source · 9 lines
void ExternalBridge::update_task_phase(const std::string& task_id,
const std::string& status,
const std::string& phase) {
std::lock_guard<std::mutex> lock(tasks_mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end()) { return; }
it->second.status = status;
it->second.phase = phase;
}Activity · 6 steps
Requirements
write_sentinel
void entropic::ExternalBridge::write_sentinel(const std::string &task_id, const std::string &status)
Write the sentinel file for an async task completion.
src/facade/external_bridge.cpp:2416
Called by SCENARIO, TEST_CASE, commit_async_final_state, fail_task_engine_busy
Source · 19 lines
void ExternalBridge::write_sentinel(const std::string& task_id,
const std::string& status) {
auto dir = async_sentinel_dir();
if (dir.empty()) { return; }
std::error_code ec;
std::filesystem::create_directories(dir, ec);
if (ec) {
logger->warn("write_sentinel: mkdir {} failed: {}",
dir.string(), ec.message());
return;
}
auto path = dir / (task_id + sentinel_suffix_for_status(status));
std::ofstream out(path);
if (!out.is_open()) {
logger->warn("write_sentinel: open {} failed", path.string());
return;
}
out << status << '\n';
}Activity · 14 steps
Requirements
~ExternalBridge
entropic::ExternalBridge::~ExternalBridge()
Destructor — stop if running.
src/facade/external_bridge.cpp:1425
The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.