Skip to content

Commit 976cd0c

Browse files
feat(sdk): add MCP server configuration support
Add ability to configure MCP servers programmatically via the SDK. Features: - New `mcp` option accepts Record<string, McpServerConfig> for stdio and HTTP transports - New `inheritMcp` option (default: true) controls whether global MCPs from config.toml are inherited - MCP config can be set at Codex level (inherited by threads) or Thread level (overrides Codex) TypeScript API: - McpStdioTransport: command, args, env, envVars, cwd - McpHttpTransport: url, bearerTokenEnvVar, httpHeaders, envHttpHeaders - McpServerConfig: enabled, startupTimeoutSec, toolTimeoutSec, enabledTools, disabledTools Rust implementation: - Converts camelCase JSON keys to snake_case TOML format - Passes MCP config via raw_overrides to codex-core - When inheritMcp=false, clears mcp_servers={} before adding custom servers Includes comprehensive tests for both TypeScript (15 tests) and Rust (14 tests). Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 85bfce8 commit 976cd0c

17 files changed

Lines changed: 951 additions & 11 deletions

‎sdk/native/package.json‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@codex-native/sdk",
3-
"version": "0.0.35",
3+
"version": "0.0.38",
44
"description": "Native NAPI-based Codex SDK - complete standalone implementation.",
55
"main": "dist/index.cjs",
66
"module": "dist/index.mjs",
@@ -47,14 +47,14 @@
4747
]
4848
},
4949
"optionalDependencies": {
50-
"@codex-native/sdk-darwin-arm64": "0.0.35",
51-
"@codex-native/sdk-darwin-x64": "0.0.35",
52-
"@codex-native/sdk-linux-arm64-gnu": "0.0.35",
53-
"@codex-native/sdk-linux-x64-gnu": "0.0.35",
54-
"@codex-native/sdk-linux-arm64-musl": "0.0.35",
55-
"@codex-native/sdk-linux-x64-musl": "0.0.35",
56-
"@codex-native/sdk-win32-arm64-msvc": "0.0.35",
57-
"@codex-native/sdk-win32-x64-msvc": "0.0.35"
50+
"@codex-native/sdk-darwin-arm64": "0.0.38",
51+
"@codex-native/sdk-darwin-x64": "0.0.38",
52+
"@codex-native/sdk-linux-arm64-gnu": "0.0.38",
53+
"@codex-native/sdk-linux-x64-gnu": "0.0.38",
54+
"@codex-native/sdk-linux-arm64-musl": "0.0.38",
55+
"@codex-native/sdk-linux-x64-musl": "0.0.38",
56+
"@codex-native/sdk-win32-arm64-msvc": "0.0.38",
57+
"@codex-native/sdk-win32-x64-msvc": "0.0.38"
5858
},
5959
"dependencies": {
6060
"@modelcontextprotocol/sdk": "^1.22.0",

‎sdk/native/rust-bindings/run/cli_builder.rs‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,40 @@
1+
/// Convert a camelCase string to snake_case
2+
fn camel_to_snake(s: &str) -> String {
3+
let mut result = String::with_capacity(s.len() + 4);
4+
for (i, ch) in s.chars().enumerate() {
5+
if ch.is_uppercase() {
6+
if i > 0 {
7+
result.push('_');
8+
}
9+
result.push(ch.to_ascii_lowercase());
10+
} else {
11+
result.push(ch);
12+
}
13+
}
14+
result
15+
}
16+
17+
/// Convert a JSON value to TOML inline format string, converting camelCase keys to snake_case
18+
fn json_to_toml_inline(value: &JsonValue) -> String {
19+
match value {
20+
JsonValue::Null => "null".to_string(),
21+
JsonValue::Bool(b) => b.to_string(),
22+
JsonValue::Number(n) => n.to_string(),
23+
JsonValue::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
24+
JsonValue::Array(arr) => {
25+
let items: Vec<String> = arr.iter().map(json_to_toml_inline).collect();
26+
format!("[{}]", items.join(", "))
27+
}
28+
JsonValue::Object(obj) => {
29+
let pairs: Vec<String> = obj
30+
.iter()
31+
.map(|(k, v)| format!("{} = {}", camel_to_snake(k), json_to_toml_inline(v)))
32+
.collect();
33+
format!("{{ {} }}", pairs.join(", "))
34+
}
35+
}
36+
}
37+
138
pub fn build_cli(
239
options: &InternalRunRequest,
340
schema_path: Option<PathBuf>,
@@ -77,6 +114,22 @@ pub fn build_cli(
77114
}
78115
}
79116

117+
// Handle MCP server configuration
118+
// If inherit_mcp is false, clear all globally registered MCP servers first
119+
if !options.inherit_mcp {
120+
raw_overrides.push("mcp_servers={}".to_string());
121+
}
122+
123+
// Add each MCP server from the options
124+
if let Some(mcp) = &options.mcp {
125+
if let JsonValue::Object(servers) = mcp {
126+
for (server_name, server_config) in servers {
127+
let toml_value = json_to_toml_inline(server_config);
128+
raw_overrides.push(format!("mcp_servers.{server_name}={toml_value}"));
129+
}
130+
}
131+
}
132+
80133
Cli {
81134
command,
82135
images: options.images.clone(),

‎sdk/native/rust-bindings/run/parsing.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ impl ConversationConfigRequest {
2727
reasoning_effort,
2828
reasoning_summary,
2929
full_auto: self.full_auto.unwrap_or(true),
30+
mcp: None,
31+
inherit_mcp: true,
3032
})
3133
}
3234
}
@@ -98,6 +100,8 @@ impl RunRequest {
98100
reasoning_effort,
99101
reasoning_summary,
100102
full_auto: self.full_auto.unwrap_or(true),
103+
mcp: self.mcp,
104+
inherit_mcp: self.inherit_mcp.unwrap_or(true),
101105
})
102106
}
103107
}
@@ -139,6 +143,8 @@ impl ForkRequest {
139143
full_auto: self.full_auto,
140144
review_mode: None,
141145
review_hint: None,
146+
mcp: None,
147+
inherit_mcp: None,
142148
};
143149

144150
let run_options = run_request.into_internal()?;

‎sdk/native/rust-bindings/run/tests.rs‎

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ mod tests_run {
2929
reasoning_effort: None,
3030
reasoning_summary: None,
3131
full_auto: true,
32+
mcp: None,
33+
inherit_mcp: true,
3234
}
3335
}
3436

@@ -66,4 +68,221 @@ mod tests_run {
6668
assert!(validate_model_name(Some("gpt-4.1"), false, Some("github")).is_ok());
6769
}
6870

71+
// MCP Configuration Tests
72+
mod mcp_tests {
73+
use super::*;
74+
75+
#[test]
76+
fn camel_to_snake_converts_correctly() {
77+
assert_eq!(camel_to_snake("bearerTokenEnvVar"), "bearer_token_env_var");
78+
assert_eq!(camel_to_snake("httpHeaders"), "http_headers");
79+
assert_eq!(camel_to_snake("envHttpHeaders"), "env_http_headers");
80+
assert_eq!(camel_to_snake("startupTimeoutSec"), "startup_timeout_sec");
81+
assert_eq!(camel_to_snake("toolTimeoutSec"), "tool_timeout_sec");
82+
assert_eq!(camel_to_snake("enabledTools"), "enabled_tools");
83+
assert_eq!(camel_to_snake("disabledTools"), "disabled_tools");
84+
assert_eq!(camel_to_snake("envVars"), "env_vars");
85+
assert_eq!(camel_to_snake("command"), "command");
86+
assert_eq!(camel_to_snake("url"), "url");
87+
}
88+
89+
#[test]
90+
fn json_to_toml_inline_string() {
91+
let json = JsonValue::String("hello".to_string());
92+
assert_eq!(json_to_toml_inline(&json), "\"hello\"");
93+
}
94+
95+
#[test]
96+
fn json_to_toml_inline_string_escapes_quotes() {
97+
let json = JsonValue::String("hello \"world\"".to_string());
98+
assert_eq!(json_to_toml_inline(&json), "\"hello \\\"world\\\"\"");
99+
}
100+
101+
#[test]
102+
fn json_to_toml_inline_number() {
103+
let json = JsonValue::Number(serde_json::Number::from(42));
104+
assert_eq!(json_to_toml_inline(&json), "42");
105+
}
106+
107+
#[test]
108+
fn json_to_toml_inline_bool() {
109+
assert_eq!(json_to_toml_inline(&JsonValue::Bool(true)), "true");
110+
assert_eq!(json_to_toml_inline(&JsonValue::Bool(false)), "false");
111+
}
112+
113+
#[test]
114+
fn json_to_toml_inline_array() {
115+
let json = serde_json::json!(["a", "b", "c"]);
116+
assert_eq!(json_to_toml_inline(&json), "[\"a\", \"b\", \"c\"]");
117+
}
118+
119+
#[test]
120+
fn json_to_toml_inline_object_converts_keys() {
121+
let json = serde_json::json!({
122+
"bearerTokenEnvVar": "TOKEN",
123+
"httpHeaders": {}
124+
});
125+
let result = json_to_toml_inline(&json);
126+
// The result should contain snake_case keys
127+
assert!(result.contains("bearer_token_env_var"));
128+
assert!(result.contains("http_headers"));
129+
}
130+
131+
#[test]
132+
fn json_to_toml_inline_stdio_config() {
133+
let json = serde_json::json!({
134+
"command": "npx",
135+
"args": ["-y", "my-mcp-server"],
136+
"env": {"NODE_ENV": "production"},
137+
"envVars": ["HOME", "PATH"],
138+
"cwd": "/app"
139+
});
140+
let result = json_to_toml_inline(&json);
141+
assert!(result.contains("command = \"npx\""));
142+
assert!(result.contains("args = [\"-y\", \"my-mcp-server\"]"));
143+
assert!(result.contains("env_vars = [\"HOME\", \"PATH\"]"));
144+
assert!(result.contains("cwd = \"/app\""));
145+
}
146+
147+
#[test]
148+
fn json_to_toml_inline_http_config() {
149+
let json = serde_json::json!({
150+
"url": "https://api.example.com/mcp",
151+
"bearerTokenEnvVar": "API_TOKEN"
152+
});
153+
let result = json_to_toml_inline(&json);
154+
assert!(result.contains("url = \"https://api.example.com/mcp\""));
155+
assert!(result.contains("bearer_token_env_var = \"API_TOKEN\""));
156+
}
157+
158+
#[test]
159+
fn build_cli_includes_mcp_servers() {
160+
let mut req = base_internal_request();
161+
req.mcp = Some(serde_json::json!({
162+
"test-server": {
163+
"command": "npx",
164+
"args": ["test"]
165+
}
166+
}));
167+
168+
let cli = build_cli(&req, None, false);
169+
let overrides: Vec<&str> = cli.config_overrides.raw_overrides
170+
.iter()
171+
.map(|s| s.as_str())
172+
.collect();
173+
174+
// Check that MCP server is in overrides
175+
assert!(overrides.iter().any(|o| o.starts_with("mcp_servers.test-server=")));
176+
}
177+
178+
#[test]
179+
fn build_cli_clears_mcp_when_inherit_false() {
180+
let mut req = base_internal_request();
181+
req.inherit_mcp = false;
182+
req.mcp = Some(serde_json::json!({
183+
"custom": {"command": "test"}
184+
}));
185+
186+
let cli = build_cli(&req, None, false);
187+
let overrides: Vec<&str> = cli.config_overrides.raw_overrides
188+
.iter()
189+
.map(|s| s.as_str())
190+
.collect();
191+
192+
// Should have mcp_servers={} to clear global config first
193+
assert!(overrides.contains(&"mcp_servers={}"));
194+
// And then the custom server
195+
assert!(overrides.iter().any(|o| o.starts_with("mcp_servers.custom=")));
196+
}
197+
198+
#[test]
199+
fn build_cli_does_not_clear_mcp_when_inherit_true() {
200+
let mut req = base_internal_request();
201+
req.inherit_mcp = true;
202+
req.mcp = Some(serde_json::json!({
203+
"custom": {"command": "test"}
204+
}));
205+
206+
let cli = build_cli(&req, None, false);
207+
let overrides: Vec<&str> = cli.config_overrides.raw_overrides
208+
.iter()
209+
.map(|s| s.as_str())
210+
.collect();
211+
212+
// Should NOT have mcp_servers={} when inheriting
213+
assert!(!overrides.contains(&"mcp_servers={}"));
214+
// But should still have the custom server
215+
assert!(overrides.iter().any(|o| o.starts_with("mcp_servers.custom=")));
216+
}
217+
218+
#[test]
219+
fn run_request_parses_mcp_config() {
220+
let request = RunRequest {
221+
prompt: "test".to_string(),
222+
input_items: None,
223+
thread_id: None,
224+
images: None,
225+
model: None,
226+
model_provider: None,
227+
oss: None,
228+
sandbox_mode: None,
229+
approval_mode: None,
230+
workspace_write_options: None,
231+
review_mode: None,
232+
review_hint: None,
233+
working_directory: None,
234+
skip_git_repo_check: Some(true),
235+
output_schema: None,
236+
tool_choice: None,
237+
base_url: None,
238+
api_key: None,
239+
linux_sandbox_path: None,
240+
reasoning_effort: None,
241+
reasoning_summary: None,
242+
full_auto: None,
243+
mcp: Some(serde_json::json!({
244+
"server1": {"command": "npx", "args": ["test"]}
245+
})),
246+
inherit_mcp: Some(false),
247+
};
248+
249+
let internal = request.into_internal().expect("parse should succeed");
250+
assert!(internal.mcp.is_some());
251+
assert!(!internal.inherit_mcp);
252+
}
253+
254+
#[test]
255+
fn run_request_defaults_inherit_mcp_to_true() {
256+
let request = RunRequest {
257+
prompt: "test".to_string(),
258+
input_items: None,
259+
thread_id: None,
260+
images: None,
261+
model: None,
262+
model_provider: None,
263+
oss: None,
264+
sandbox_mode: None,
265+
approval_mode: None,
266+
workspace_write_options: None,
267+
review_mode: None,
268+
review_hint: None,
269+
working_directory: None,
270+
skip_git_repo_check: Some(true),
271+
output_schema: None,
272+
tool_choice: None,
273+
base_url: None,
274+
api_key: None,
275+
linux_sandbox_path: None,
276+
reasoning_effort: None,
277+
reasoning_summary: None,
278+
full_auto: None,
279+
mcp: None,
280+
inherit_mcp: None,
281+
};
282+
283+
let internal = request.into_internal().expect("parse should succeed");
284+
assert!(internal.inherit_mcp);
285+
}
286+
}
287+
69288
}

‎sdk/native/rust-bindings/run/types.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ pub struct RunRequest {
4141
pub reasoning_summary: Option<String>,
4242
#[napi(js_name = "fullAuto")]
4343
pub full_auto: Option<bool>,
44+
/// MCP servers to register, keyed by server name. Passed as JSON value.
45+
pub mcp: Option<JsonValue>,
46+
/// When false, ignores globally registered MCP servers from config.toml.
47+
#[napi(js_name = "inheritMcp")]
48+
pub inherit_mcp: Option<bool>,
4449
}
4550

4651
#[napi(object)]
@@ -208,4 +213,8 @@ pub struct InternalRunRequest {
208213
pub reasoning_effort: Option<ReasoningEffort>,
209214
pub reasoning_summary: Option<ReasoningSummary>,
210215
pub full_auto: bool,
216+
/// MCP servers to register, keyed by server name. Serialized as JSON for config override.
217+
pub mcp: Option<JsonValue>,
218+
/// When false, ignores globally registered MCP servers from config.toml.
219+
pub inherit_mcp: bool,
211220
}

0 commit comments

Comments
 (0)