1use 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
26pub const MAX_CONFIGURED_MCP_SERVERS: usize = 32;
28pub const MAX_MCP_ENVIRONMENT_VALUE_BYTES: usize = 64 * 1024;
30pub const MAX_MCP_ENVIRONMENT_VALUE_TOTAL_BYTES: usize = 256 * 1024;
32
33#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase", deny_unknown_fields)]
36pub struct McpServerSettings {
37 pub id: String,
39 pub transport: McpTransportSettings,
41 #[serde(default)]
43 pub inherited_environment: Vec<String>,
44 #[serde(default)]
46 pub tools: Vec<McpToolSettings>,
47 #[serde(default)]
49 pub limits: McpLimitsSettings,
50 #[serde(default)]
52 pub lifecycle: McpLifecycleSettings,
53 #[serde(default)]
55 pub reconnect: Option<McpReconnectSettings>,
56}
57
58impl McpServerSettings {
59 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#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
113pub enum McpTransportSettings {
114 Stdio {
116 executable: PathBuf,
118 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase", deny_unknown_fields)]
153pub struct McpToolSettings {
154 pub remote_name: String,
156 #[serde(default)]
158 pub alias: Option<String>,
159 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase", deny_unknown_fields)]
183pub struct McpToolDeclarationSettings {
184 pub effects: Vec<ToolEffect>,
186 #[serde(default)]
188 pub resources: Vec<McpArgumentResourceSettings>,
189 pub idempotency: ToolIdempotency,
191 pub retry_safety: McpRetrySafetySettings,
193 pub concurrency: McpConcurrencySettings,
195 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase", deny_unknown_fields)]
223pub struct McpArgumentResourceSettings {
224 pub argument: String,
226 pub scheme: String,
228 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(rename_all = "snake_case")]
242pub enum McpRetrySafetySettings {
243 Never,
245 ExplicitOnly,
247 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "snake_case")]
264pub enum McpConcurrencySettings {
265 Parallel,
267 Serial,
269 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase", deny_unknown_fields)]
286pub struct McpLimitsSettings {
287 pub max_frame_bytes: Option<usize>,
289 pub max_descriptor_bytes: Option<usize>,
291 pub max_result_bytes: Option<usize>,
293 pub max_stderr_bytes: Option<usize>,
295 pub max_tools: Option<usize>,
297 pub max_notifications: Option<usize>,
299 pub max_progress_events: Option<usize>,
301 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
329#[serde(rename_all = "camelCase", deny_unknown_fields)]
330pub struct McpLifecycleSettings {
331 pub startup_timeout_millis: Option<u64>,
333 pub handshake_timeout_millis: Option<u64>,
335 pub cancellation_timeout_millis: Option<u64>,
337 pub graceful_shutdown_timeout_millis: Option<u64>,
339 pub termination_timeout_millis: Option<u64>,
341 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase", deny_unknown_fields)]
372pub struct McpReconnectSettings {
373 pub max_attempts: u32,
375 pub initial_backoff_millis: u64,
377 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub enum McpEnvironmentErrorCode {
395 MissingVariable,
397 InvalidName,
399 InvalidValue,
401 Resolution,
403}
404
405#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct McpEnvironmentError {
408 code: McpEnvironmentErrorCode,
409 name: String,
410}
411
412impl McpEnvironmentError {
413 #[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 #[must_use]
427 pub const fn code(&self) -> McpEnvironmentErrorCode {
428 self.code
429 }
430
431 #[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#[derive(Clone, PartialEq, Eq)]
452pub struct McpEnvironmentValue(OsString);
453
454impl McpEnvironmentValue {
455 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 #[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
495pub trait McpEnvironmentResolver: fmt::Debug + Send + Sync {
497 fn resolve(&self, name: &str) -> Result<Option<McpEnvironmentValue>, McpEnvironmentError>;
503}
504
505#[derive(Clone)]
507pub struct StaticMcpEnvironmentResolver {
508 values: BTreeMap<String, McpEnvironmentValue>,
509}
510
511impl StaticMcpEnvironmentResolver {
512 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#[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
591pub struct McpChildEnvironment {
593 values: BTreeMap<String, McpEnvironmentValue>,
594}
595
596impl McpChildEnvironment {
597 pub fn names(&self) -> impl Iterator<Item = &str> {
599 self.values.keys().map(String::as_str)
600 }
601
602 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 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
629pub 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}