bash.cpp¶
src/mcp/servers/bash.cpp
@file bash.cpp @brief BashServer implementation — shell command execution under an enforced timeout, one process group per command.
Owners: @tvanfossen
BashServer
entropic::BashServer::BashServer(const std::filesystem::path &working_dir, const std::string &data_dir, int timeout=30)
Construct with working directory and data dir.
src/mcp/servers/bash.cpp:528
Called by init_builtins, make_bash_server
Calls ExecuteTool, load_tool_definition, register_tool
Source · 19 lines
BashServer::BashServer(
const std::filesystem::path& working_dir,
const std::string& data_dir,
int timeout)
: MCPServerBase("bash")
, working_dir_(working_dir)
, timeout_(timeout) {
auto def = load_tool_definition(
"execute", "bash", data_dir + "/tools");
execute_tool_ = std::make_unique<ExecuteTool>(
std::move(def), *this);
register_tool(execute_tool_.get());
logger->info("BashServer initialized: cwd='{}' timeout={}s",
working_dir_.string(), timeout_);
}Activity · 4 steps
Requirements
cancelled_error
nlohmann::json entropic::anonymous_namespace{bash.cpp}::cancelled_error(const ShellRun &run)The typed error the model sees when its run was interrupted (gh#172).
src/mcp/servers/bash.cpp:391
Source · 10 lines
nlohmann::json cancelled_error(const ShellRun& run) {
nlohmann::json err;
err["error"] = "cancelled";
err["message"] = "The session was interrupted while this command ran; "
"it was stopped together with every process it started. Output "
"printed before then is in `output`.";
err["elapsed_ms"] = run.elapsed_ms;
err["output"] = run.output;
return err;
}Activity · 6 steps
Requirements
collect_until_exit
ShellStop entropic::anonymous_namespace{bash.cpp}::collect_until_exit(pid_t pid, int fd, Clock::time_point deadline, std::string &out)Collect output until the shell exits, the deadline passes, or the run is cancelled.
src/mcp/servers/bash.cpp:246
Source · 15 lines
ShellStop collect_until_exit(pid_t pid, int fd, Clock::time_point deadline,
std::string& out) {
bool open = true;
ShellStop stop = ShellStop::running;
while (stop == ShellStop::running) {
if (open) {
open = pump(fd, out, kPollMs);
} else {
// The shell closed its output but is still running.
std::this_thread::sleep_for(std::chrono::milliseconds(kPollMs));
}
stop = poll_stop(pid, deadline);
}
return stop;
}Activity · 9 steps
Requirements
drain
void entropic::anonymous_namespace{bash.cpp}::drain(int fd, std::string &out)Read what the pipe still holds once the group is dead.
src/mcp/servers/bash.cpp:273
Source · 13 lines
void drain(int fd, std::string& out) {
const auto until = Clock::now() + kDrainGrace;
bool open = true;
while (open && Clock::now() < until) {
open = pump(fd, out, kPollMs);
}
if (open) {
logger->warn("bash: output pipe still open {} ms after the process "
"group was killed — a process that left the group "
"holds it; returning without its output",
kDrainGrace.count());
}
}Activity · 6 steps
Requirements
execute
ServerResponse entropic::ExecuteTool::execute(const std::string &args_json) override
Execute a shell command.
src/mcp/servers/bash.cpp:459
Source · 53 lines
ServerResponse execute(const std::string& args_json) override;
private:
BashServer& server_;
};
/**
* @brief Execute a shell command. Operator approval is the gate.
*
* Security model: the engine's tool-call approval flow gates whether
* this method runs at all. There is no command-content allowlist or
* denylist here; the operator approves a specific `command` value
* shown in the prompt, and that's what runs. The only validation we
* do is on `working_dir`, because that field is concatenated into a
* shell `cd` clause and could smuggle commands the operator never
* saw.
*
* v2.13.0: the server's timeout is ENFORCED — see run_shell. A command
* that hits it returns the typed `timeout` error instead of an exit code.
*
* @param args_json JSON with "command" and optional "working_dir"
* (defaulting to the server's own working directory).
* @return A ServerResponse with no directives whose result is a JSON
* object carrying the process exit_code and combined
* stdout+stderr output; or the typed `timeout` error (limit,
* elapsed, partial output) when the command outlived the limit;
* or the working_dir rejection error when the cwd failed
* validation — in which case no shell ran.
* @req REQ-MCP-023
* @version 2.14.0
*/
ServerResponse ExecuteTool::execute(const std::string& args_json) {
auto args = nlohmann::json::parse(args_json);
std::string command = args.at("command").get<std::string>();
std::string cwd = args.value(
"working_dir", server_.working_dir().string());
logger->info("[bash.execute] cmd='{}' cwd='{}'", command, cwd);
if (!is_safe_cwd(cwd)) {
logger->warn("Rejected unsafe working_dir: '{}'", cwd);
return {"Error: working_dir is not an existing directory or "
"contains shell metacharacters", {}};
}
std::string full_cmd =
"cd " + cwd + " && " + command + " 2>&1";
const int limit = server_.timeout();
auto run = run_shell(full_cmd, limit);
return {shell_result(run, limit, command).dump(), {}};
}Activity · 11 steps
Requirements
get_permission_pattern
std::string entropic::BashServer::get_permission_pattern(const std::string &tool_name, const std::string &args_json) const override
Permission pattern: "execute:{base_cmd} *".
src/mcp/servers/bash.cpp:572
Source · 15 lines
BashServer::get_permission_pattern(const std::string& tool_name, const std::string& args_json) const {
std::string base_cmd = "unknown";
try {
auto args = nlohmann::json::parse(args_json);
std::string cmd = args.at("command").get<std::string>();
auto space = cmd.find(' ');
base_cmd = (space != std::string::npos)
? cmd.substr(0, space) : cmd;
} catch (const std::exception& e) {
logger->warn("Failed to parse command for permission: {}",
e.what());
}
return tool_name + ":" + base_cmd + " *";
}Activity · 3 steps
Requirements
is_safe_cwd
static bool entropic::is_safe_cwd(const std::string &cwd)
Reject working_dir values that would smuggle shell syntax.
src/mcp/servers/bash.cpp:61
Source · 8 lines
static bool is_safe_cwd(const std::string& cwd) {
static constexpr const char* unsafe_chars = ";&|`$<>\n\r\\\"'*?(){}[]";
if (cwd.find_first_of(unsafe_chars) != std::string::npos) {
return false;
}
std::error_code ec;
return std::filesystem::is_directory(cwd, ec);
}Activity · 5 steps
Requirements
poll_stop
ShellStop entropic::anonymous_namespace{bash.cpp}::poll_stop(pid_t pid, Clock::time_point deadline)One poll's verdict: exited, out of time, cancelled, or running.
src/mcp/servers/bash.cpp:223
Source · 11 lines
ShellStop poll_stop(pid_t pid, Clock::time_point deadline) {
ShellStop stop = ShellStop::running;
if (shell_exited(pid)) {
stop = ShellStop::exited;
} else if (entropic::current_run_cancelled()) {
stop = ShellStop::cancelled;
} else if (Clock::now() >= deadline) {
stop = ShellStop::deadline;
}
return stop;
}Activity · 10 steps
Requirements
pump
bool entropic::anonymous_namespace{bash.cpp}::pump(int fd, std::string &out, int wait_ms)Read whatever the pipe holds, waiting at most wait_ms .
src/mcp/servers/bash.cpp:163
Source · 12 lines
bool pump(int fd, std::string& out, int wait_ms) {
pollfd pfd{fd, POLLIN, 0};
if (::poll(&pfd, 1, wait_ms) <= 0) {
return true; // nothing yet (or EINTR): still open
}
std::array<char, 4096> buf{};
ssize_t n = ::read(fd, buf.data(), buf.size());
if (n > 0) {
out.append(buf.data(), static_cast<size_t>(n));
}
return n > 0 || (n < 0 && (errno == EINTR || errno == EAGAIN));
}Activity · 8 steps
Requirements
reap
int entropic::anonymous_namespace{bash.cpp}::reap(pid_t pid)Reap the shell and translate its status.
src/mcp/servers/bash.cpp:295
Source · 14 lines
int reap(pid_t pid) {
int status = 0;
pid_t rc = -1;
do {
rc = ::waitpid(pid, &status, 0);
} while (rc == -1 && errno == EINTR);
int code = -1;
if (rc == pid && WIFEXITED(status)) {
code = WEXITSTATUS(status);
} else if (rc == pid && WIFSIGNALED(status)) {
code = 128 + WTERMSIG(status);
}
return code;
}Activity · 11 steps
Requirements
run_shell
ShellRun entropic::anonymous_namespace{bash.cpp}::run_shell(const std::string &cmd, int timeout_s)Run one command to completion or to its deadline.
src/mcp/servers/bash.cpp:324
Source · 23 lines
ShellRun run_shell(const std::string& cmd, int timeout_s) {
ShellRun run;
const auto start = Clock::now();
int fd = -1;
const pid_t pid = spawn_shell(cmd, fd);
if (pid < 0) {
run.output = "Failed to start /bin/sh";
return run;
}
const auto stop = collect_until_exit(
pid, fd, start + std::chrono::seconds(timeout_s), run.output);
run.timed_out = stop == ShellStop::deadline;
run.cancelled = stop == ShellStop::cancelled;
// The whole group: a timed-out or cancelled tree, or what a finished
// command left running in the background.
::kill(-pid, SIGKILL);
drain(fd, run.output);
::close(fd);
run.exit_code = reap(pid);
run.elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
Clock::now() - start).count();
return run;
}Activity · 16 steps
Requirements
set_working_dir
bool entropic::BashServer::set_working_dir(const std::string &path) override
Set working directory.
src/mcp/servers/bash.cpp:600
Source · 5 lines
bool BashServer::set_working_dir(const std::string& path) {
working_dir_ = path;
logger->info("Working directory set to: {}", path);
return true;
}Activity · 3 steps
Requirements
shell_exited
bool entropic::anonymous_namespace{bash.cpp}::shell_exited(pid_t pid)Has the shell exited? Leaves it a ZOMBIE (WNOWAIT).
src/mcp/servers/bash.cpp:190
Source · 6 lines
bool shell_exited(pid_t pid) {
siginfo_t info{};
int rc = ::waitid(P_PID, static_cast<id_t>(pid), &info,
WEXITED | WNOHANG | WNOWAIT);
return (rc == 0 && info.si_pid == pid) || (rc == -1 && errno == ECHILD);
}Activity · 3 steps
Requirements
shell_result
nlohmann::json entropic::anonymous_namespace{bash.cpp}::shell_result(const ShellRun &run, int limit_s, const std::string &command)The tool result for one finished, timed-out or cancelled run.
src/mcp/servers/bash.cpp:411
Source · 19 lines
nlohmann::json shell_result(const ShellRun& run, int limit_s,
const std::string& command) {
nlohmann::json result;
if (run.cancelled) {
logger->info("Bash: CANCELLED after {} ms — process group killed, "
"cmd='{}'", run.elapsed_ms, command);
result = cancelled_error(run);
} else if (run.timed_out) {
logger->warn("Bash: TIMEOUT after {} ms (limit {} s) — process "
"group killed, cmd='{}'", run.elapsed_ms, limit_s, command);
result = timeout_error(run, limit_s);
} else {
logger->info("Bash: exit={}, output={} chars, {} ms, cmd='{}'",
run.exit_code, run.output.size(), run.elapsed_ms, command);
result["exit_code"] = run.exit_code;
result["output"] = run.output;
}
return result;
}Activity · 13 steps
Requirements
spawn_shell
pid_t entropic::anonymous_namespace{bash.cpp}::spawn_shell(const std::string &cmd, int &read_fd)Spawn /bin/sh -c cmd as the leader of a NEW process group.
src/mcp/servers/bash.cpp:121
Source · 32 lines
pid_t spawn_shell(const std::string& cmd, int& read_fd) {
int fds[2] = {-1, -1};
read_fd = -1;
if (::pipe2(fds, O_CLOEXEC) != 0) {
logger->error("bash: pipe2 failed: {}", std::strerror(errno));
return -1;
}
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null",
O_RDONLY, 0);
posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO);
posix_spawn_file_actions_adddup2(&actions, fds[1], STDERR_FILENO);
posix_spawnattr_t attr;
posix_spawnattr_init(&attr);
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
posix_spawnattr_setpgroup(&attr, 0); // pgid = the child's own pid
const char* argv[] = {"/bin/sh", "-c", cmd.c_str(), nullptr};
pid_t pid = -1;
int rc = ::posix_spawn(&pid, "/bin/sh", &actions, &attr,
const_cast<char* const*>(argv), environ);
posix_spawnattr_destroy(&attr);
posix_spawn_file_actions_destroy(&actions);
::close(fds[1]);
if (rc != 0) {
logger->error("bash: posix_spawn failed: {}", std::strerror(rc));
::close(fds[0]);
pid = -1;
}
read_fd = pid > 0 ? fds[0] : -1;
return pid;
}Activity · 26 steps
Requirements
timeout
int entropic::BashServer::timeout() const
Get the enforced per-command timeout.
src/mcp/servers/bash.cpp:623
Source · 3 lines
int BashServer::timeout() const {
return timeout_;
}Activity · 1 steps
Requirements
timeout_error
nlohmann::json entropic::anonymous_namespace{bash.cpp}::timeout_error(const ShellRun &run, int limit_s)The typed error the model sees when a command hits the limit.
src/mcp/servers/bash.cpp:362
Source · 17 lines
nlohmann::json timeout_error(const ShellRun& run, int limit_s) {
std::array<char, 32> secs{};
std::snprintf(secs.data(), secs.size(), "%.1f",
static_cast<double>(run.elapsed_ms) / 1000.0);
nlohmann::json err;
err["error"] = "timeout";
err["message"] = "Command exceeded the bash tool's "
+ std::to_string(limit_s) + " s timeout (ran " + secs.data()
+ " s) and was killed, together with every process it started. "
"Output printed before the kill is in `output`. Split the work "
"into shorter commands; the limit is set by the operator "
"(mcp.bash.timeout_seconds).";
err["timeout_seconds"] = limit_s;
err["elapsed_ms"] = run.elapsed_ms;
err["output"] = run.output;
return err;
}Activity · 9 steps
Requirements
working_dir
const std::filesystem::path & entropic::BashServer::working_dir() const
Get the working directory.
src/mcp/servers/bash.cpp:613
Source · 3 lines
const std::filesystem::path& BashServer::working_dir() const {
return working_dir_;
}