Skip to main content

tea_coding/
mcp_config.rs

1//! Trusted MCP settings conversion and late child-environment resolution.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::error::Error;
5use std::ffi::{OsStr, OsString};
6use std::fmt;
7use std::path::PathBuf;
8use std::process::Command;
9use std::str::FromStr as _;
10use std::time::Duration;
11
12use serde::{Deserialize, Serialize};
13use tea_mcp::{
14    MAX_MCP_ENVIRONMENT_NAME_BYTES, MAX_MCP_ENVIRONMENT_VARIABLES, McpArgumentResource,
15    McpLifecyclePolicy, McpLimits, McpReconnectPolicy, McpRemoteToolName, McpServerConfig,
16    McpServerId, McpToolDeclaration, McpToolPolicy, McpTransportConfig,
17};
18use tea_protocol::ToolIdempotency;
19use tea_tools::{
20    ToolConcurrency, ToolEffect, ToolExecutionSemantics, ToolName, ToolResourceAccess,
21    ToolRetrySafety, ToolTimeout,
22};
23
24use crate::{CodingError, CodingErrorCode};
25
26/// Maximum explicitly configured MCP servers in one resolved product profile.
27pub const MAX_CONFIGURED_MCP_SERVERS: usize = 32;
28/// Maximum bytes admitted from one resolved environment value.
29pub const MAX_MCP_ENVIRONMENT_VALUE_BYTES: usize = 64 * 1024;
30/// Maximum aggregate bytes admitted into one MCP child environment.
31pub const MAX_MCP_ENVIRONMENT_VALUE_TOTAL_BYTES: usize = 256 * 1024;
32
33/// Strict serializable settings for one explicitly configured MCP server.
34#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase", deny_unknown_fields)]
36pub struct McpServerSettings {
37    /// Stable canonical server ID.
38    pub id: String,
39    /// Exact shell-free transport settings.
40    pub transport: McpTransportSettings,
41    /// Exact environment variable names resolved only at spawn time.
42    #[serde(default)]
43    pub inherited_environment: Vec<String>,
44    /// Host-owned remote tool policies.
45    #[serde(default)]
46    pub tools: Vec<McpToolSettings>,
47    /// Optional protocol and output limit overrides.
48    #[serde(default)]
49    pub limits: McpLimitsSettings,
50    /// Optional lifecycle deadline overrides.
51    #[serde(default)]
52    pub lifecycle: McpLifecycleSettings,
53    /// Explicit reconnect policy; absent means disabled.
54    #[serde(default)]
55    pub reconnect: Option<McpReconnectSettings>,
56}
57
58impl McpServerSettings {
59    /// Converts trusted sparse settings into one fully validated pure config.
60    ///
61    /// # Errors
62    ///
63    /// Rejects malformed identities, paths, arguments, environment names,
64    /// policies, limits, or lifecycle values before any process can start.
65    pub fn resolve(&self) -> Result<McpServerConfig, CodingError> {
66        let id = McpServerId::from_str(&self.id).map_err(|_| invalid_settings())?;
67        let transport = self.transport.resolve()?;
68        let tools = self
69            .tools
70            .iter()
71            .map(McpToolSettings::resolve)
72            .collect::<Result<Vec<_>, _>>()?;
73        let reconnect = self
74            .reconnect
75            .as_ref()
76            .map(McpReconnectSettings::resolve)
77            .transpose()?
78            .unwrap_or_default();
79        McpServerConfig::new(
80            id,
81            transport,
82            self.inherited_environment.clone(),
83            tools,
84            self.limits.resolve()?,
85            self.lifecycle.resolve()?,
86            reconnect,
87        )
88        .map_err(|_| invalid_settings())
89    }
90}
91
92impl fmt::Debug for McpServerSettings {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        formatter
95            .debug_struct("McpServerSettings")
96            .field("id", &self.id)
97            .field("transport", &self.transport)
98            .field(
99                "inherited_environment_count",
100                &self.inherited_environment.len(),
101            )
102            .field("tool_count", &self.tools.len())
103            .field("limits", &self.limits)
104            .field("lifecycle", &self.lifecycle)
105            .field("reconnect", &self.reconnect)
106            .finish()
107    }
108}
109
110/// Supported serializable MCP transport settings.
111#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
113pub enum McpTransportSettings {
114    /// Exact stdio executable and argument vector.
115    Stdio {
116        /// Absolute executable path. It is never resolved through `PATH`.
117        executable: PathBuf,
118        /// Exact UTF-8 argument vector passed without a shell.
119        #[serde(default)]
120        arguments: Vec<String>,
121    },
122}
123
124impl McpTransportSettings {
125    fn resolve(&self) -> Result<McpTransportConfig, CodingError> {
126        match self {
127            Self::Stdio {
128                executable,
129                arguments,
130            } => {
131                McpTransportConfig::stdio(executable.clone(), arguments.iter().map(OsString::from))
132                    .map_err(|_| invalid_settings())
133            }
134        }
135    }
136}
137
138impl fmt::Debug for McpTransportSettings {
139    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match self {
141            Self::Stdio { arguments, .. } => formatter
142                .debug_struct("Stdio")
143                .field("executable", &"<redacted>")
144                .field("argument_count", &arguments.len())
145                .finish(),
146        }
147    }
148}
149
150/// Strict settings for one exact remote MCP tool policy.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase", deny_unknown_fields)]
153pub struct McpToolSettings {
154    /// Exact remote tool name.
155    pub remote_name: String,
156    /// Optional canonical local alias.
157    #[serde(default)]
158    pub alias: Option<String>,
159    /// Complete declaration that enables the tool; absent keeps it disabled.
160    #[serde(default)]
161    pub declaration: Option<McpToolDeclarationSettings>,
162}
163
164impl McpToolSettings {
165    fn resolve(&self) -> Result<McpToolPolicy, CodingError> {
166        let remote =
167            McpRemoteToolName::new(self.remote_name.clone()).map_err(|_| invalid_settings())?;
168        let mut policy = if let Some(declaration) = &self.declaration {
169            McpToolPolicy::enabled(remote, declaration.resolve()?)
170        } else {
171            McpToolPolicy::new(remote)
172        };
173        if let Some(alias) = &self.alias {
174            policy = policy.with_alias(ToolName::from_str(alias).map_err(|_| invalid_settings())?);
175        }
176        Ok(policy)
177    }
178}
179
180/// Complete host-owned effects, resources, and execution declaration.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase", deny_unknown_fields)]
183pub struct McpToolDeclarationSettings {
184    /// Authoritative effects; remote annotations cannot narrow these.
185    pub effects: Vec<ToolEffect>,
186    /// Pure top-level argument resource mappings.
187    #[serde(default)]
188    pub resources: Vec<McpArgumentResourceSettings>,
189    /// Invocation idempotency classification.
190    pub idempotency: ToolIdempotency,
191    /// Permitted retry behavior.
192    pub retry_safety: McpRetrySafetySettings,
193    /// Scheduler concurrency behavior.
194    pub concurrency: McpConcurrencySettings,
195    /// Caller-owned invocation timeout.
196    pub timeout_millis: u64,
197}
198
199impl McpToolDeclarationSettings {
200    fn resolve(&self) -> Result<McpToolDeclaration, CodingError> {
201        let resources = self
202            .resources
203            .iter()
204            .map(McpArgumentResourceSettings::resolve)
205            .collect::<Result<Vec<_>, _>>()?;
206        let timeout =
207            ToolTimeout::from_millis(self.timeout_millis).map_err(|_| invalid_settings())?;
208        let execution = ToolExecutionSemantics::new(
209            self.idempotency,
210            self.retry_safety.into(),
211            self.concurrency.into(),
212            timeout,
213        )
214        .map_err(|_| invalid_settings())?;
215        McpToolDeclaration::new(self.effects.clone(), resources, execution)
216            .map_err(|_| invalid_settings())
217    }
218}
219
220/// Serializable argument-to-resource mapping.
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase", deny_unknown_fields)]
223pub struct McpArgumentResourceSettings {
224    /// Top-level string argument name.
225    pub argument: String,
226    /// Canonical resource scheme.
227    pub scheme: String,
228    /// Requested resource access.
229    pub access: ToolResourceAccess,
230}
231
232impl McpArgumentResourceSettings {
233    fn resolve(&self) -> Result<McpArgumentResource, CodingError> {
234        McpArgumentResource::new(&self.argument, &self.scheme, self.access)
235            .map_err(|_| invalid_settings())
236    }
237}
238
239/// Serializable retry-safety setting.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(rename_all = "snake_case")]
242pub enum McpRetrySafetySettings {
243    /// Never retry the invocation.
244    Never,
245    /// Retry only after an explicit informed decision.
246    ExplicitOnly,
247    /// Permit automatic retry at known-safe boundaries.
248    Automatic,
249}
250
251impl From<McpRetrySafetySettings> for ToolRetrySafety {
252    fn from(value: McpRetrySafetySettings) -> Self {
253        match value {
254            McpRetrySafetySettings::Never => Self::Never,
255            McpRetrySafetySettings::ExplicitOnly => Self::ExplicitOnly,
256            McpRetrySafetySettings::Automatic => Self::Automatic,
257        }
258    }
259}
260
261/// Serializable tool concurrency setting.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "snake_case")]
264pub enum McpConcurrencySettings {
265    /// Independent invocations may execute concurrently.
266    Parallel,
267    /// Invocations share a serial lane.
268    Serial,
269    /// Invocations require an exclusive lane.
270    Exclusive,
271}
272
273impl From<McpConcurrencySettings> for ToolConcurrency {
274    fn from(value: McpConcurrencySettings) -> Self {
275        match value {
276            McpConcurrencySettings::Parallel => Self::Parallel,
277            McpConcurrencySettings::Serial => Self::Serial,
278            McpConcurrencySettings::Exclusive => Self::Exclusive,
279        }
280    }
281}
282
283/// Sparse protocol and output limit overrides.
284#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase", deny_unknown_fields)]
286pub struct McpLimitsSettings {
287    /// Maximum raw frame bytes.
288    pub max_frame_bytes: Option<usize>,
289    /// Maximum frozen descriptor bytes.
290    pub max_descriptor_bytes: Option<usize>,
291    /// Maximum terminal result bytes.
292    pub max_result_bytes: Option<usize>,
293    /// Maximum private retained stderr bytes.
294    pub max_stderr_bytes: Option<usize>,
295    /// Maximum tools admitted from the descriptor.
296    pub max_tools: Option<usize>,
297    /// Maximum notifications between lifecycle checkpoints.
298    pub max_notifications: Option<usize>,
299    /// Maximum progress events for one invocation.
300    pub max_progress_events: Option<usize>,
301    /// Maximum concurrent requests to one server.
302    pub max_in_flight_requests: Option<usize>,
303}
304
305impl McpLimitsSettings {
306    fn resolve(&self) -> Result<McpLimits, CodingError> {
307        let mut limits = McpLimits::default();
308        macro_rules! apply_limit {
309            ($field:ident, $method:ident) => {
310                if let Some(value) = self.$field {
311                    limits = limits.$method(value).map_err(|_| invalid_settings())?;
312                }
313            };
314        }
315        apply_limit!(max_frame_bytes, with_max_frame_bytes);
316        apply_limit!(max_descriptor_bytes, with_max_descriptor_bytes);
317        apply_limit!(max_result_bytes, with_max_result_bytes);
318        apply_limit!(max_stderr_bytes, with_max_stderr_bytes);
319        apply_limit!(max_tools, with_max_tools);
320        apply_limit!(max_notifications, with_max_notifications);
321        apply_limit!(max_progress_events, with_max_progress_events);
322        apply_limit!(max_in_flight_requests, with_max_in_flight_requests);
323        Ok(limits)
324    }
325}
326
327/// Sparse lifecycle timeout overrides in milliseconds.
328#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
329#[serde(rename_all = "camelCase", deny_unknown_fields)]
330pub struct McpLifecycleSettings {
331    /// Process startup timeout.
332    pub startup_timeout_millis: Option<u64>,
333    /// Protocol handshake timeout.
334    pub handshake_timeout_millis: Option<u64>,
335    /// Cooperative cancellation timeout.
336    pub cancellation_timeout_millis: Option<u64>,
337    /// Graceful service shutdown timeout.
338    pub graceful_shutdown_timeout_millis: Option<u64>,
339    /// Process termination timeout.
340    pub termination_timeout_millis: Option<u64>,
341    /// Forced-kill timeout.
342    pub kill_timeout_millis: Option<u64>,
343}
344
345impl McpLifecycleSettings {
346    fn resolve(&self) -> Result<McpLifecyclePolicy, CodingError> {
347        let defaults = McpLifecyclePolicy::default();
348        McpLifecyclePolicy::new(
349            selected_duration(self.startup_timeout_millis, defaults.startup_timeout())?,
350            selected_duration(self.handshake_timeout_millis, defaults.handshake_timeout())?,
351            selected_duration(
352                self.cancellation_timeout_millis,
353                defaults.cancellation_timeout(),
354            )?,
355            selected_duration(
356                self.graceful_shutdown_timeout_millis,
357                defaults.graceful_shutdown_timeout(),
358            )?,
359            selected_duration(
360                self.termination_timeout_millis,
361                defaults.termination_timeout(),
362            )?,
363            selected_duration(self.kill_timeout_millis, defaults.kill_timeout())?,
364        )
365        .map_err(|_| invalid_settings())
366    }
367}
368
369/// Explicit bounded reconnect settings.
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase", deny_unknown_fields)]
372pub struct McpReconnectSettings {
373    /// Maximum reconnect attempts.
374    pub max_attempts: u32,
375    /// Initial reconnect delay.
376    pub initial_backoff_millis: u64,
377    /// Maximum reconnect delay.
378    pub max_backoff_millis: u64,
379}
380
381impl McpReconnectSettings {
382    fn resolve(&self) -> Result<McpReconnectPolicy, CodingError> {
383        McpReconnectPolicy::bounded(
384            self.max_attempts,
385            Duration::from_millis(self.initial_backoff_millis),
386            Duration::from_millis(self.max_backoff_millis),
387        )
388        .map_err(|_| invalid_settings())
389    }
390}
391
392/// Stable failure classification for late MCP environment resolution.
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub enum McpEnvironmentErrorCode {
395    /// The configured variable was absent from the resolver.
396    MissingVariable,
397    /// A variable name was invalid for a child process.
398    InvalidName,
399    /// A resolved value was invalid or exceeded a hard bound.
400    InvalidValue,
401    /// The resolver failed without exposing its private diagnostic.
402    Resolution,
403}
404
405/// Name-only, value-independent MCP environment resolution failure.
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct McpEnvironmentError {
408    code: McpEnvironmentErrorCode,
409    name: String,
410}
411
412impl McpEnvironmentError {
413    /// Creates a value-independent error for one requested variable name.
414    ///
415    /// Invalid names are replaced with a constant placeholder so external
416    /// resolver diagnostics cannot inject control text.
417    #[must_use]
418    pub fn new(code: McpEnvironmentErrorCode, name: &str) -> Self {
419        Self {
420            code,
421            name: safe_environment_name(name),
422        }
423    }
424
425    /// Returns the stable failure classification.
426    #[must_use]
427    pub const fn code(&self) -> McpEnvironmentErrorCode {
428        self.code
429    }
430
431    /// Returns only the configured variable name, never its value.
432    #[must_use]
433    pub fn name(&self) -> &str {
434        &self.name
435    }
436}
437
438impl fmt::Display for McpEnvironmentError {
439    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
440        write!(
441            formatter,
442            "{:?}: MCP environment variable {} could not be resolved",
443            self.code, self.name
444        )
445    }
446}
447
448impl Error for McpEnvironmentError {}
449
450/// Bounded environment value whose debug output is always redacted.
451#[derive(Clone, PartialEq, Eq)]
452pub struct McpEnvironmentValue(OsString);
453
454impl McpEnvironmentValue {
455    /// Creates a bounded value for one validated variable name.
456    ///
457    /// # Errors
458    ///
459    /// Rejects invalid names, NUL-containing values, or values over 64 KiB.
460    pub fn try_new(name: &str, value: impl Into<OsString>) -> Result<Self, McpEnvironmentError> {
461        if !valid_environment_name(name) {
462            return Err(McpEnvironmentError::new(
463                McpEnvironmentErrorCode::InvalidName,
464                name,
465            ));
466        }
467        let value = value.into();
468        let (bytes, has_nul) = os_bytes(&value);
469        if bytes > MAX_MCP_ENVIRONMENT_VALUE_BYTES || has_nul {
470            return Err(McpEnvironmentError::new(
471                McpEnvironmentErrorCode::InvalidValue,
472                name,
473            ));
474        }
475        Ok(Self(value))
476    }
477
478    /// Exposes the value only at the child-process environment boundary.
479    #[must_use]
480    pub fn as_os_str(&self) -> &OsStr {
481        &self.0
482    }
483
484    fn into_os_string(self) -> OsString {
485        self.0
486    }
487}
488
489impl fmt::Debug for McpEnvironmentValue {
490    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
491        formatter.write_str("**REDACTED**")
492    }
493}
494
495/// Object-safe late resolver for explicitly allowlisted environment names.
496pub trait McpEnvironmentResolver: fmt::Debug + Send + Sync {
497    /// Resolves one exact name at process-spawn time.
498    ///
499    /// # Errors
500    ///
501    /// Returns only stable name/code diagnostics without the private value.
502    fn resolve(&self, name: &str) -> Result<Option<McpEnvironmentValue>, McpEnvironmentError>;
503}
504
505/// Hermetic map-backed resolver for embedders and tests.
506#[derive(Clone)]
507pub struct StaticMcpEnvironmentResolver {
508    values: BTreeMap<String, McpEnvironmentValue>,
509}
510
511impl StaticMcpEnvironmentResolver {
512    /// Validates and captures a bounded injected environment.
513    ///
514    /// # Errors
515    ///
516    /// Rejects invalid/duplicate names, too many values, or oversized values.
517    pub fn new(values: BTreeMap<String, OsString>) -> Result<Self, McpEnvironmentError> {
518        if values.len() > MAX_MCP_ENVIRONMENT_VARIABLES {
519            return Err(McpEnvironmentError::new(
520                McpEnvironmentErrorCode::InvalidValue,
521                "<collection>",
522            ));
523        }
524        let mut resolved = BTreeMap::new();
525        let mut canonical = BTreeSet::new();
526        let mut total = 0usize;
527        for (name, value) in values {
528            if !canonical.insert(canonical_environment_name(&name)) {
529                return Err(McpEnvironmentError::new(
530                    McpEnvironmentErrorCode::InvalidName,
531                    &name,
532                ));
533            }
534            let value = McpEnvironmentValue::try_new(&name, value)?;
535            total = total
536                .checked_add(os_bytes(value.as_os_str()).0)
537                .ok_or_else(|| {
538                    McpEnvironmentError::new(McpEnvironmentErrorCode::InvalidValue, &name)
539                })?;
540            if total > MAX_MCP_ENVIRONMENT_VALUE_TOTAL_BYTES {
541                return Err(McpEnvironmentError::new(
542                    McpEnvironmentErrorCode::InvalidValue,
543                    &name,
544                ));
545            }
546            resolved.insert(canonical_environment_name(&name), value);
547        }
548        Ok(Self { values: resolved })
549    }
550}
551
552impl fmt::Debug for StaticMcpEnvironmentResolver {
553    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
554        formatter
555            .debug_struct("StaticMcpEnvironmentResolver")
556            .field("value_count", &self.values.len())
557            .finish()
558    }
559}
560
561impl McpEnvironmentResolver for StaticMcpEnvironmentResolver {
562    fn resolve(&self, name: &str) -> Result<Option<McpEnvironmentValue>, McpEnvironmentError> {
563        if !valid_environment_name(name) {
564            return Err(McpEnvironmentError::new(
565                McpEnvironmentErrorCode::InvalidName,
566                name,
567            ));
568        }
569        Ok(self.values.get(&canonical_environment_name(name)).cloned())
570    }
571}
572
573/// Resolver that reads the live process environment only when called.
574#[derive(Debug, Clone, Copy, Default)]
575pub struct ProcessMcpEnvironmentResolver;
576
577impl McpEnvironmentResolver for ProcessMcpEnvironmentResolver {
578    fn resolve(&self, name: &str) -> Result<Option<McpEnvironmentValue>, McpEnvironmentError> {
579        if !valid_environment_name(name) {
580            return Err(McpEnvironmentError::new(
581                McpEnvironmentErrorCode::InvalidName,
582                name,
583            ));
584        }
585        std::env::var_os(name)
586            .map(|value| McpEnvironmentValue::try_new(name, value))
587            .transpose()
588    }
589}
590
591/// Exact, bounded child environment resolved from an empty map.
592pub struct McpChildEnvironment {
593    values: BTreeMap<String, McpEnvironmentValue>,
594}
595
596impl McpChildEnvironment {
597    /// Returns sorted exact names without exposing values.
598    pub fn names(&self) -> impl Iterator<Item = &str> {
599        self.values.keys().map(String::as_str)
600    }
601
602    /// Clears inherited process state and applies only these reviewed values.
603    pub fn apply_to(&self, command: &mut Command) {
604        command.env_clear();
605        command.envs(
606            self.values
607                .iter()
608                .map(|(name, value)| (name, value.as_os_str())),
609        );
610    }
611
612    /// Consumes the environment into exact process name/value pairs.
613    pub fn into_variables(self) -> impl Iterator<Item = (String, OsString)> {
614        self.values
615            .into_iter()
616            .map(|(name, value)| (name, value.into_os_string()))
617    }
618}
619
620impl fmt::Debug for McpChildEnvironment {
621    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
622        formatter
623            .debug_struct("McpChildEnvironment")
624            .field("names", &self.values.keys().collect::<Vec<_>>())
625            .finish()
626    }
627}
628
629/// Resolves one server's exact allowlist into an otherwise empty environment.
630///
631/// On Windows, `SYSTEMROOT` is the sole reviewed platform necessity. No path,
632/// proxy, credential, home, or loader variable is inherited implicitly.
633///
634/// # Errors
635///
636/// Fails closed when any required name is absent or a value exceeds bounds.
637pub fn resolve_mcp_environment(
638    server: &McpServerConfig,
639    resolver: &dyn McpEnvironmentResolver,
640) -> Result<McpChildEnvironment, McpEnvironmentError> {
641    let names = PLATFORM_ENVIRONMENT_NAMES
642        .iter()
643        .copied()
644        .chain(server.inherited_environment().iter().map(String::as_str));
645    let mut values = BTreeMap::new();
646    let mut canonical = BTreeSet::new();
647    let mut total = 0usize;
648    for name in names {
649        if !canonical.insert(canonical_environment_name(name)) {
650            continue;
651        }
652        let value = resolver.resolve(name)?.ok_or_else(|| {
653            McpEnvironmentError::new(McpEnvironmentErrorCode::MissingVariable, name)
654        })?;
655        total = total
656            .checked_add(os_bytes(value.as_os_str()).0)
657            .ok_or_else(|| McpEnvironmentError::new(McpEnvironmentErrorCode::InvalidValue, name))?;
658        if total > MAX_MCP_ENVIRONMENT_VALUE_TOTAL_BYTES {
659            return Err(McpEnvironmentError::new(
660                McpEnvironmentErrorCode::InvalidValue,
661                name,
662            ));
663        }
664        values.insert(name.to_owned(), value);
665    }
666    Ok(McpChildEnvironment { values })
667}
668
669pub(crate) fn merge_mcp_server_settings(
670    resolved: &mut Vec<McpServerConfig>,
671    layer: &[McpServerSettings],
672) -> Result<(), CodingError> {
673    if layer.len() > MAX_CONFIGURED_MCP_SERVERS {
674        return Err(invalid_settings());
675    }
676    let mut servers = resolved
677        .iter()
678        .cloned()
679        .map(|server| (server.id().as_str().to_owned(), server))
680        .collect::<BTreeMap<_, _>>();
681    let mut layer_ids = BTreeSet::new();
682    for settings in layer {
683        let server = settings.resolve()?;
684        let id = server.id().as_str().to_owned();
685        if !layer_ids.insert(id.clone()) {
686            return Err(invalid_settings());
687        }
688        servers.insert(id, server);
689    }
690    if servers.len() > MAX_CONFIGURED_MCP_SERVERS {
691        return Err(invalid_settings());
692    }
693    *resolved = servers.into_values().collect();
694    Ok(())
695}
696
697pub(crate) fn validate_mcp_server_aliases(servers: &[McpServerConfig]) -> Result<(), CodingError> {
698    let mut aliases = BTreeSet::new();
699    for server in servers {
700        for tool in server.tools() {
701            if let Some(alias) = tool.resolved_alias(server.id())
702                && !aliases.insert(alias)
703            {
704                return Err(invalid_settings());
705            }
706        }
707    }
708    Ok(())
709}
710
711fn selected_duration(value: Option<u64>, default: Duration) -> Result<Duration, CodingError> {
712    let millis =
713        value.unwrap_or(u64::try_from(default.as_millis()).map_err(|_| invalid_settings())?);
714    Ok(Duration::from_millis(millis))
715}
716
717fn valid_environment_name(name: &str) -> bool {
718    let mut bytes = name.bytes();
719    name.len() <= MAX_MCP_ENVIRONMENT_NAME_BYTES
720        && bytes
721            .next()
722            .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
723        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
724}
725
726fn safe_environment_name(name: &str) -> String {
727    if valid_environment_name(name) {
728        name.to_owned()
729    } else {
730        "<invalid>".to_owned()
731    }
732}
733
734#[cfg(windows)]
735fn canonical_environment_name(name: &str) -> String {
736    name.to_ascii_uppercase()
737}
738
739#[cfg(not(windows))]
740fn canonical_environment_name(name: &str) -> String {
741    name.to_owned()
742}
743
744#[cfg(windows)]
745const PLATFORM_ENVIRONMENT_NAMES: &[&str] = &["SYSTEMROOT"];
746#[cfg(not(windows))]
747const PLATFORM_ENVIRONMENT_NAMES: &[&str] = &[];
748
749#[cfg(unix)]
750fn os_bytes(value: &OsStr) -> (usize, bool) {
751    use std::os::unix::ffi::OsStrExt as _;
752
753    let bytes = value.as_bytes();
754    (bytes.len(), bytes.contains(&0))
755}
756
757#[cfg(windows)]
758fn os_bytes(value: &OsStr) -> (usize, bool) {
759    use std::os::windows::ffi::OsStrExt as _;
760
761    value
762        .encode_wide()
763        .fold((0usize, false), |(bytes, nul), unit| {
764            (bytes.saturating_add(2), nul || unit == 0)
765        })
766}
767
768#[cfg(not(any(unix, windows)))]
769fn os_bytes(value: &OsStr) -> (usize, bool) {
770    let value = value.to_string_lossy();
771    (value.len(), value.contains('\0'))
772}
773
774fn invalid_settings() -> CodingError {
775    CodingError::new(CodingErrorCode::InvalidInput, "MCP settings are invalid")
776}