mirror of
https://github.com/openai/codex.git
synced 2026-11-06 20:20:34 +00:00
This PR reorganizes things slightly so that:
- Instead of a single multitool executable, `codex-exec-server`, we now
have two executables:
- `codex-exec-mcp-server` to launch the MCP server
- `codex-execve-wrapper` is the `execve(2)` wrapper to use with the
`BASH_EXEC_WRAPPER` environment variable
- `BASH_EXEC_WRAPPER` must be a single executable: it cannot be a
command string composed of an executable with args (i.e., it no longer
adds the `escalate` subcommand, as before)
- `codex-exec-mcp-server` takes `--bash` and `--execve` as options.
Though if `--execve` is not specified, the MCP server will check the
directory containing `std::env::current_exe()` and attempt to use the
file named `codex-execve-wrapper` within it. In development, this works
out since these executables are side-by-side in the `target/debug`
folder.
With respect to testing, this also fixes an important bug in
`dummy_exec_policy()`, as I was using `ends_with()` as if it applied to
a `String`, but in this case, it is used with a `&Path`, so the
semantics are slightly different.
Putting this all together, I was able to test this by running the
following:
```
~/code/codex/codex-rs$ npx @modelcontextprotocol/inspector \
./target/debug/codex-exec-mcp-server --bash ~/code/bash/bash
```
If I try to run `git status` in `/Users/mbolin/code/codex` via the
`shell` tool from the MCP server:
<img width="1589" height="1335" alt="image"
src="https://github.com/user-attachments/assets/9db6aea8-7fbc-4675-8b1f-ec446685d6c4"
/>
then I get prompted with the following elicitation, as expected:
<img width="1589" height="1335" alt="image"
src="https://github.com/user-attachments/assets/21b68fe0-494d-4562-9bad-0ddc55fc846d"
/>
Though a current limitation is that the `shell` tool defaults to a
timeout of 10s, which means I only have 10s to respond to the
elicitation. Ideally, the time spent waiting for a response from a human
should not count against the timeout for the command execution. I will
address this in a subsequent PR.
---
Note `~/code/bash/bash` was created by doing:
```
cd ~/code
git clone https://github.com/bminor/bash
cd bash
git checkout a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b
<apply the patch below>
./configure
make
```
The patch:
```
diff --git a/execute_cmd.c b/execute_cmd.c
index 070f5119..d20ad2b9 100644
--- a/execute_cmd.c
+++ b/execute_cmd.c
@@ -6129,6 +6129,19 @@ shell_execve (char *command, char **args, char **env)
char sample[HASH_BANG_BUFSIZ];
size_t larray;
+ char* exec_wrapper = getenv("BASH_EXEC_WRAPPER");
+ if (exec_wrapper && *exec_wrapper && !whitespace (*exec_wrapper))
+ {
+ char *orig_command = command;
+
+ larray = strvec_len (args);
+
+ memmove (args + 2, args, (++larray) * sizeof (char *));
+ args[0] = exec_wrapper;
+ args[1] = orig_command;
+ command = exec_wrapper;
+ }
+
```
142 lines
4.1 KiB
Rust
142 lines
4.1 KiB
Rust
use std::path::PathBuf;
|
|
use std::time::Duration;
|
|
|
|
use anyhow::Context as _;
|
|
use anyhow::Result;
|
|
use rmcp::ErrorData as McpError;
|
|
use rmcp::RoleServer;
|
|
use rmcp::ServerHandler;
|
|
use rmcp::ServiceExt;
|
|
use rmcp::handler::server::router::tool::ToolRouter;
|
|
use rmcp::handler::server::wrapper::Parameters;
|
|
use rmcp::model::*;
|
|
use rmcp::schemars;
|
|
use rmcp::service::RequestContext;
|
|
use rmcp::service::RunningService;
|
|
use rmcp::tool;
|
|
use rmcp::tool_handler;
|
|
use rmcp::tool_router;
|
|
use rmcp::transport::stdio;
|
|
|
|
use crate::posix::escalate_server::EscalateServer;
|
|
use crate::posix::escalate_server::{self};
|
|
use crate::posix::mcp_escalation_policy::ExecPolicy;
|
|
use crate::posix::mcp_escalation_policy::McpEscalationPolicy;
|
|
|
|
/// Path to our patched bash.
|
|
const CODEX_BASH_PATH_ENV_VAR: &str = "CODEX_BASH_PATH";
|
|
|
|
pub(crate) fn get_bash_path() -> Result<PathBuf> {
|
|
std::env::var(CODEX_BASH_PATH_ENV_VAR)
|
|
.map(PathBuf::from)
|
|
.context(format!("{CODEX_BASH_PATH_ENV_VAR} must be set"))
|
|
}
|
|
|
|
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
|
|
pub struct ExecParams {
|
|
/// The bash string to execute.
|
|
pub command: String,
|
|
/// The working directory to execute the command in. Must be an absolute path.
|
|
pub workdir: String,
|
|
/// The timeout for the command in milliseconds.
|
|
pub timeout_ms: Option<u64>,
|
|
}
|
|
|
|
#[derive(Debug, serde::Serialize, schemars::JsonSchema)]
|
|
pub struct ExecResult {
|
|
pub exit_code: i32,
|
|
pub output: String,
|
|
pub duration: Duration,
|
|
pub timed_out: bool,
|
|
}
|
|
|
|
impl From<escalate_server::ExecResult> for ExecResult {
|
|
fn from(result: escalate_server::ExecResult) -> Self {
|
|
Self {
|
|
exit_code: result.exit_code,
|
|
output: result.output,
|
|
duration: result.duration,
|
|
timed_out: result.timed_out,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct ExecTool {
|
|
tool_router: ToolRouter<ExecTool>,
|
|
bash_path: PathBuf,
|
|
execve_wrapper: PathBuf,
|
|
policy: ExecPolicy,
|
|
}
|
|
|
|
#[tool_router]
|
|
impl ExecTool {
|
|
pub fn new(bash_path: PathBuf, execve_wrapper: PathBuf, policy: ExecPolicy) -> Self {
|
|
Self {
|
|
tool_router: Self::tool_router(),
|
|
bash_path,
|
|
execve_wrapper,
|
|
policy,
|
|
}
|
|
}
|
|
|
|
/// Runs a shell command and returns its output. You MUST provide the workdir as an absolute path.
|
|
#[tool]
|
|
async fn shell(
|
|
&self,
|
|
context: RequestContext<RoleServer>,
|
|
Parameters(params): Parameters<ExecParams>,
|
|
) -> Result<CallToolResult, McpError> {
|
|
let escalate_server = EscalateServer::new(
|
|
self.bash_path.clone(),
|
|
self.execve_wrapper.clone(),
|
|
McpEscalationPolicy::new(self.policy, context),
|
|
);
|
|
let result = escalate_server
|
|
.exec(
|
|
params.command,
|
|
// TODO: use ShellEnvironmentPolicy
|
|
std::env::vars().collect(),
|
|
PathBuf::from(¶ms.workdir),
|
|
params.timeout_ms,
|
|
)
|
|
.await
|
|
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
|
|
Ok(CallToolResult::success(vec![Content::json(
|
|
ExecResult::from(result),
|
|
)?]))
|
|
}
|
|
}
|
|
|
|
#[tool_handler]
|
|
impl ServerHandler for ExecTool {
|
|
fn get_info(&self) -> ServerInfo {
|
|
ServerInfo {
|
|
protocol_version: ProtocolVersion::V_2025_06_18,
|
|
capabilities: ServerCapabilities::builder().enable_tools().build(),
|
|
server_info: Implementation::from_build_env(),
|
|
instructions: Some(
|
|
"This server provides a tool to execute shell commands and return their output."
|
|
.to_string(),
|
|
),
|
|
}
|
|
}
|
|
|
|
async fn initialize(
|
|
&self,
|
|
_request: InitializeRequestParam,
|
|
_context: RequestContext<RoleServer>,
|
|
) -> Result<InitializeResult, McpError> {
|
|
Ok(self.get_info())
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn serve(
|
|
bash_path: PathBuf,
|
|
execve_wrapper: PathBuf,
|
|
policy: ExecPolicy,
|
|
) -> Result<RunningService<RoleServer, ExecTool>, rmcp::service::ServerInitializeError> {
|
|
let tool = ExecTool::new(bash_path, execve_wrapper, policy);
|
|
tool.serve(stdio()).await
|
|
}
|