1use std::collections::BTreeMap;
11use std::fmt;
12
13use crate::adapters::caps::{Caps, CommandRef, DisableMech, ToolFilterMech};
14use crate::env::Os;
15use crate::error::{CoreError, ErrorCode};
16use crate::formats::{NativeMap, NativeValue};
17use crate::model::server::{ServerFields, Transport};
18
19#[derive(Debug, Clone, PartialEq)]
23pub struct RenderedServer {
24 pub name: String,
26 pub launch: Launch,
27 pub enabled: bool,
31 pub tools: ToolLists,
35 pub passthrough: NativeMap,
38}
39
40impl RenderedServer {
41 pub fn new(name: impl Into<String>, launch: Launch) -> Self {
43 Self {
44 name: name.into(),
45 launch,
46 enabled: true,
47 tools: ToolLists::default(),
48 passthrough: NativeMap::new(),
49 }
50 }
51}
52
53#[derive(Debug, Clone, PartialEq)]
55pub enum Launch {
56 Stdio(StdioLaunch),
57 Http(RemoteLaunch),
58 Sse(RemoteLaunch),
59}
60
61impl Launch {
62 pub const fn transport(&self) -> Transport {
63 match self {
64 Launch::Stdio(_) => Transport::Stdio,
65 Launch::Http(_) => Transport::Http,
66 Launch::Sse(_) => Transport::Sse,
67 }
68 }
69}
70
71#[derive(Debug, Clone, Default, PartialEq)]
72pub struct StdioLaunch {
73 pub command: String,
74 pub args: Vec<String>,
75 pub env: BTreeMap<String, String>,
76 pub forward_env: Vec<String>,
80 pub cwd: Option<String>,
81}
82
83#[derive(Debug, Clone, Default, PartialEq)]
84pub struct RemoteLaunch {
85 pub url: String,
86 pub headers: BTreeMap<String, String>,
87 pub headers_helper: Option<String>,
90 pub bearer_env: Option<String>,
93 pub headers_env: BTreeMap<String, String>,
96}
97
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct ToolLists {
101 pub allow: Option<Vec<String>>,
102 pub deny: Option<Vec<String>>,
103}
104
105impl ToolLists {
106 pub fn is_empty(&self) -> bool {
107 self.allow.is_none() && self.deny.is_none()
108 }
109}
110
111#[derive(Debug, Clone, Copy)]
113pub struct WriteCx<'a> {
114 pub os: Os,
115 pub existing: Option<&'a NativeValue>,
118}
119
120#[derive(Debug, Clone, Default, PartialEq)]
127pub struct ServerDef {
128 pub fields: ServerFields,
130 pub headers_helper: Option<String>,
131 pub disabled: bool,
133 pub tools: ToolLists,
135 pub passthrough: NativeMap,
137 pub unmapped: NativeMap,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, Hash)]
146pub struct Canonical(String);
147
148impl Canonical {
149 pub fn of(value: &NativeValue) -> Self {
151 let mut text = String::new();
152 write_canonical(value, &mut text);
153 Self(text)
154 }
155
156 pub fn as_str(&self) -> &str {
157 &self.0
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
164pub enum MapError {
165 UnsupportedTransport { transport: String },
168 UnsupportedField { field: String },
170 InvalidName { name: String },
172 UnexpectedShape {
174 field: String,
175 expected: &'static str,
176 },
177}
178
179impl MapError {
180 pub const fn code(&self) -> ErrorCode {
181 match self {
182 MapError::UnsupportedTransport { .. } => ErrorCode::UnsupportedTransport,
183 MapError::UnsupportedField { .. } => ErrorCode::UnsupportedField,
184 MapError::InvalidName { .. } => ErrorCode::InvalidId,
185 MapError::UnexpectedShape { .. } => ErrorCode::UnexpectedShape,
186 }
187 }
188}
189
190impl fmt::Display for MapError {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 MapError::UnsupportedTransport { transport } => {
194 write!(f, "the client cannot run {transport:?} servers")
195 }
196 MapError::UnsupportedField { field } => {
197 write!(f, "the client has no native field for `{field}`")
198 }
199 MapError::InvalidName { name } => {
200 write!(
201 f,
202 "{name:?} is not a valid entry name for the client; set `native_name`"
203 )
204 }
205 MapError::UnexpectedShape { field, expected } => {
206 write!(f, "`{field}` must be {expected}")
207 }
208 }
209 }
210}
211
212impl std::error::Error for MapError {}
213
214impl From<MapError> for CoreError {
215 fn from(err: MapError) -> Self {
216 CoreError::new(err.code(), err.to_string())
217 }
218}
219
220pub trait EntryMapper: Sync {
222 fn to_native(&self, server: &RenderedServer, cx: &WriteCx<'_>)
223 -> Result<NativeValue, MapError>;
224
225 #[allow(clippy::wrong_self_convention)]
227 fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError>;
228
229 fn canonical(&self, value: &NativeValue) -> Canonical;
231
232 fn skipped_by_client(&self, _value: &NativeValue) -> Option<&'static str> {
237 None
238 }
239}
240
241const MODELED_KEYS: [&str; 6] = ["type", "command", "args", "env", "url", "headers"];
243const HEADERS_HELPER: &str = "headersHelper";
244const TYPE: &str = "type";
245const CWD: &str = "cwd";
246const ENABLED: &str = "enabled";
247
248const WINDOWS_SHIMS: [&str; 7] = ["npx", "npm", "pnpm", "pnpx", "yarn", "yarnpkg", "corepack"];
251
252#[derive(Debug)]
259pub struct McpServersJson {
260 pub caps: &'static Caps,
261 pub type_field: bool,
263 pub remote_type: bool,
266 pub cwd: bool,
269 pub http_aliases: &'static [&'static str],
271 pub url_implies_http: bool,
276 pub valid_name: fn(&str) -> bool,
278}
279
280impl McpServersJson {
281 fn headers_helper(&self) -> bool {
282 self.caps.command_ref == Some(CommandRef::HeadersHelper)
283 }
284
285 fn is_modeled(&self, key: &str) -> bool {
286 MODELED_KEYS.contains(&key)
287 || (key == CWD && self.cwd)
288 || (key == HEADERS_HELPER && self.headers_helper())
289 || is_disable_key(self.caps, key)
290 || is_tool_key(self.caps, key)
291 || self.caps.passthrough_allowlist.contains(&key)
292 }
293
294 fn inferred_type(&self, entry: &NativeMap) -> Option<&'static str> {
296 if entry.contains_key("command") {
297 Some("stdio")
298 } else if entry.contains_key("url") && self.url_implies_http {
299 Some("http")
300 } else {
301 None
302 }
303 }
304}
305
306impl EntryMapper for McpServersJson {
307 fn to_native(
308 &self,
309 server: &RenderedServer,
310 cx: &WriteCx<'_>,
311 ) -> Result<NativeValue, MapError> {
312 check_name(self.valid_name, &server.name)?;
313 let transport = check_transport(self.caps, &server.launch)?;
314 let existing = existing_entry(cx);
315 let keep_empty = |key: &str| existing.is_some_and(|entry| entry.contains_key(key));
316 let mut entry = NativeMap::new();
317 match &server.launch {
318 Launch::Stdio(stdio) => {
319 if !stdio.forward_env.is_empty() {
320 return unsupported("env_vars");
321 }
322 if self.type_field {
323 entry.insert(TYPE, "stdio".into());
324 }
325 let (command, args) = if self.caps.windows_shell_shim && cx.os == Os::Windows {
326 shell_shim(&stdio.command, &stdio.args)
327 } else {
328 (stdio.command.clone(), stdio.args.clone())
329 };
330 entry.insert("command", command.into());
331 entry.insert("args", strings(args));
332 if !stdio.env.is_empty() || keep_empty("env") {
333 entry.insert("env", string_map(&stdio.env));
334 }
335 if let Some(cwd) = &stdio.cwd {
336 if !self.cwd {
337 return unsupported(CWD);
338 }
339 entry.insert(CWD, cwd.as_str().into());
340 }
341 }
342 Launch::Http(remote) | Launch::Sse(remote) => {
343 if remote.bearer_env.is_some() {
344 return unsupported("bearer_token_env_var");
345 }
346 if !remote.headers_env.is_empty() {
347 return unsupported("env_http_headers");
348 }
349 if self.remote_type || transport == Transport::Sse {
350 entry.insert(TYPE, transport.as_str().into());
351 }
352 entry.insert("url", remote.url.as_str().into());
353 if !remote.headers.is_empty() || keep_empty("headers") {
354 entry.insert("headers", string_map(&remote.headers));
355 }
356 if let Some(helper) = &remote.headers_helper {
357 if !self.headers_helper() {
358 return unsupported(HEADERS_HELPER);
359 }
360 entry.insert(HEADERS_HELPER, helper.as_str().into());
361 }
362 }
363 }
364 write_enabled(&mut entry, self.caps, server, existing)?;
365 write_tools(&mut entry, self.caps, &server.tools)?;
366 write_passthrough(&mut entry, self.caps, server)?;
367 carry_over(&mut entry, existing, |key| self.is_modeled(key));
368 Ok(NativeValue::Object(entry))
369 }
370
371 fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError> {
372 let entry = value.as_object().ok_or_else(|| MapError::UnexpectedShape {
373 field: key.to_owned(),
374 expected: "an object",
375 })?;
376 let transport = match entry.get(TYPE) {
377 Some(NativeValue::String(kind)) => match kind.as_str() {
378 "stdio" => Transport::Stdio,
379 "http" => Transport::Http,
380 "sse" => Transport::Sse,
381 alias if self.http_aliases.contains(&alias) => Transport::Http,
382 other => {
383 return Err(MapError::UnsupportedTransport {
384 transport: other.to_owned(),
385 });
386 }
387 },
388 Some(_) => return shape(TYPE, "a string"),
389 None if entry.contains_key("command") => Transport::Stdio,
391 None if entry.contains_key("url") => Transport::Http,
392 None => return shape("command", "set (or `url` for a remote server)"),
393 };
394 let mut fields = ServerFields {
395 transport: Some(transport),
396 command: string_field(entry, "command")?,
397 args: string_list(entry, "args")?,
398 cwd: if self.cwd {
399 string_field(entry, CWD)?
400 } else {
401 None
402 },
403 url: string_field(entry, "url")?,
404 headers: string_map_field(entry, "headers")?,
405 env: string_map_field(entry, "env")?,
406 };
407 if self.caps.windows_shell_shim
408 && let (Some(command), Some(args)) = (&fields.command, &fields.args)
409 && let Some((inner, rest)) = shell_unshim(command, args)
410 {
411 fields.command = Some(inner);
412 fields.args = Some(rest);
413 }
414 let mut def = ServerDef {
415 fields,
416 disabled: read_disabled(entry, self.caps)?,
417 tools: read_tools(entry, self.caps)?,
418 ..ServerDef::default()
419 };
420 if self.headers_helper() {
421 def.headers_helper = string_field(entry, HEADERS_HELPER)?;
422 }
423 split_rest(&mut def, entry, self.caps, |key| self.is_modeled(key));
424 Ok(def)
425 }
426
427 fn canonical(&self, value: &NativeValue) -> Canonical {
428 let Some(entry) = value.as_object() else {
429 return Canonical::of(value);
430 };
431 let mut entry = entry.clone();
432 if let Some(kind) = entry.get(TYPE).and_then(NativeValue::as_str) {
433 let kind = if self.http_aliases.contains(&kind) {
434 "http"
435 } else {
436 kind
437 };
438 if Some(kind) == self.inferred_type(&entry) {
439 entry.remove(TYPE);
440 } else {
441 entry.insert(TYPE, kind.into());
442 }
443 }
444 drop_empty(&mut entry, &["args", "env", "headers"]);
445 drop_default_enabled(&mut entry, self.caps);
446 Canonical::of(&NativeValue::Object(entry))
447 }
448
449 fn skipped_by_client(&self, value: &NativeValue) -> Option<&'static str> {
450 let entry = value.as_object()?;
451 (entry.contains_key("url")
453 && !entry.contains_key(TYPE)
454 && self.inferred_type(entry).is_none())
455 .then_some("has a `url` but no `type`, so the client skips it")
456 }
457}
458
459pub fn word_name(name: &str) -> bool {
464 !name.is_empty()
465 && name
466 .bytes()
467 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
468}
469
470pub fn dotted_word_name(name: &str) -> bool {
473 !name.is_empty()
474 && name.bytes().all(|byte| {
475 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' || byte == b'.'
476 })
477}
478
479pub(crate) fn existing_entry<'a>(cx: &WriteCx<'a>) -> Option<&'a NativeMap> {
481 cx.existing.and_then(NativeValue::as_object)
482}
483
484pub(crate) fn check_name(valid: fn(&str) -> bool, name: &str) -> Result<(), MapError> {
485 if valid(name) {
486 Ok(())
487 } else {
488 Err(MapError::InvalidName {
489 name: name.to_owned(),
490 })
491 }
492}
493
494pub(crate) fn check_transport(caps: &Caps, launch: &Launch) -> Result<Transport, MapError> {
495 let transport = launch.transport();
496 if caps.transports.contains(transport) {
497 Ok(transport)
498 } else {
499 Err(MapError::UnsupportedTransport {
500 transport: transport.as_str().to_owned(),
501 })
502 }
503}
504
505fn disable_flag(caps: &Caps) -> Option<(&'static str, bool)> {
509 match caps.native_disable {
510 Some(DisableMech::EnabledFalse) => Some((ENABLED, false)),
511 Some(DisableMech::DisabledTrue) => Some(("disabled", true)),
512 Some(DisableMech::ListMember(_)) | None => None,
513 }
514}
515
516pub(crate) fn is_disable_key(caps: &Caps, key: &str) -> bool {
518 disable_flag(caps).is_some_and(|(flag, _)| flag == key)
519}
520
521pub(crate) fn write_enabled(
525 entry: &mut NativeMap,
526 caps: &Caps,
527 server: &RenderedServer,
528 existing: Option<&NativeMap>,
529) -> Result<(), MapError> {
530 let Some((flag, disabled)) = disable_flag(caps) else {
531 return if server.enabled {
532 Ok(())
533 } else {
534 unsupported(ENABLED)
535 };
536 };
537 if !server.enabled {
538 entry.insert(flag, NativeValue::Bool(disabled));
539 } else if existing.is_some_and(|entry| entry.contains_key(flag)) {
540 entry.insert(flag, NativeValue::Bool(!disabled));
541 }
542 Ok(())
543}
544
545pub(crate) fn read_disabled(entry: &NativeMap, caps: &Caps) -> Result<bool, MapError> {
546 let Some((flag, disabled)) = disable_flag(caps) else {
547 return Ok(false);
548 };
549 match entry.get(flag) {
550 None => Ok(false),
551 Some(NativeValue::Bool(value)) => Ok(*value == disabled),
552 Some(_) => shape(flag, "a boolean"),
553 }
554}
555
556pub(crate) fn drop_default_enabled(entry: &mut NativeMap, caps: &Caps) {
559 if let Some((flag, disabled)) = disable_flag(caps)
560 && entry.get(flag) == Some(&NativeValue::Bool(!disabled))
561 {
562 entry.remove(flag);
563 }
564}
565
566pub(crate) fn is_tool_key(caps: &Caps, key: &str) -> bool {
568 match caps.tool_filter {
569 Some(ToolFilterMech::AllowDeny { allow, deny }) => key == allow || key == deny,
570 Some(ToolFilterMech::Allow(allow)) => key == allow,
571 None => false,
572 }
573}
574
575pub(crate) fn write_tools(
576 entry: &mut NativeMap,
577 caps: &Caps,
578 tools: &ToolLists,
579) -> Result<(), MapError> {
580 let (allow_key, deny_key) = match caps.tool_filter {
581 _ if tools.is_empty() => return Ok(()),
582 Some(ToolFilterMech::AllowDeny { allow, deny }) => (allow, Some(deny)),
583 Some(ToolFilterMech::Allow(allow)) => (allow, None),
584 None => return unsupported("tools"),
585 };
586 if let Some(allow) = &tools.allow {
587 entry.insert(allow_key, strings(allow.clone()));
588 }
589 if let Some(deny) = &tools.deny {
590 let Some(deny_key) = deny_key else {
591 return unsupported("tools.deny");
592 };
593 entry.insert(deny_key, strings(deny.clone()));
594 }
595 Ok(())
596}
597
598pub(crate) fn read_tools(entry: &NativeMap, caps: &Caps) -> Result<ToolLists, MapError> {
599 Ok(match caps.tool_filter {
600 Some(ToolFilterMech::AllowDeny { allow, deny }) => ToolLists {
601 allow: string_list(entry, allow)?,
602 deny: string_list(entry, deny)?,
603 },
604 Some(ToolFilterMech::Allow(allow)) => ToolLists {
605 allow: string_list(entry, allow)?,
606 deny: None,
607 },
608 None => ToolLists::default(),
609 })
610}
611
612pub(crate) fn write_passthrough(
615 entry: &mut NativeMap,
616 caps: &Caps,
617 server: &RenderedServer,
618) -> Result<(), MapError> {
619 for (key, value) in server.passthrough.iter() {
620 if !caps.passthrough_allowlist.contains(&key) {
621 return unsupported(key);
622 }
623 if let Some(timeout) = caps.timeouts.iter().find(|timeout| timeout.key == key)
624 && timeout.duration(value).is_none()
625 {
626 return shape(key, timeout.expected());
627 }
628 entry.insert(key, value.clone());
629 }
630 Ok(())
631}
632
633pub(crate) fn carry_over(
635 entry: &mut NativeMap,
636 existing: Option<&NativeMap>,
637 is_modeled: impl Fn(&str) -> bool,
638) {
639 for (key, value) in existing.into_iter().flat_map(NativeMap::iter) {
640 if !is_modeled(key) {
641 entry.insert(key, value.clone());
642 }
643 }
644}
645
646pub(crate) fn split_rest(
648 def: &mut ServerDef,
649 entry: &NativeMap,
650 caps: &Caps,
651 is_modeled: impl Fn(&str) -> bool,
652) {
653 for (key, value) in entry.iter() {
654 if caps.passthrough_allowlist.contains(&key) {
655 def.passthrough.insert(key, value.clone());
656 } else if !is_modeled(key) {
657 def.unmapped.insert(key, value.clone());
658 }
659 }
660}
661
662pub(crate) fn drop_empty(entry: &mut NativeMap, keys: &[&str]) {
664 for key in keys {
665 let empty = match entry.get(key) {
666 Some(NativeValue::Array(items)) => items.is_empty(),
667 Some(NativeValue::Object(map)) => map.is_empty(),
668 _ => false,
669 };
670 if empty {
671 entry.remove(key);
672 }
673 }
674}
675
676pub(crate) fn unsupported<T>(field: &str) -> Result<T, MapError> {
677 Err(MapError::UnsupportedField {
678 field: field.to_owned(),
679 })
680}
681
682pub(crate) fn shape<T>(field: &str, expected: &'static str) -> Result<T, MapError> {
683 Err(MapError::UnexpectedShape {
684 field: field.to_owned(),
685 expected,
686 })
687}
688
689pub(crate) fn strings(items: Vec<String>) -> NativeValue {
690 NativeValue::Array(items.into_iter().map(NativeValue::String).collect())
691}
692
693pub(crate) fn string_map(map: &BTreeMap<String, String>) -> NativeValue {
694 NativeValue::Object(
695 map.iter()
696 .map(|(key, value)| (key.as_str(), NativeValue::from(value.as_str())))
697 .collect(),
698 )
699}
700
701pub(crate) fn string_field(entry: &NativeMap, key: &str) -> Result<Option<String>, MapError> {
702 match entry.get(key) {
703 None => Ok(None),
704 Some(NativeValue::String(value)) => Ok(Some(value.clone())),
705 Some(_) => shape(key, "a string"),
706 }
707}
708
709pub(crate) fn string_list(entry: &NativeMap, key: &str) -> Result<Option<Vec<String>>, MapError> {
710 let Some(value) = entry.get(key) else {
711 return Ok(None);
712 };
713 value
714 .as_array()
715 .and_then(|items| {
716 items
717 .iter()
718 .map(|item| item.as_str().map(str::to_owned))
719 .collect::<Option<Vec<_>>>()
720 })
721 .map(Some)
722 .ok_or_else(|| MapError::UnexpectedShape {
723 field: key.to_owned(),
724 expected: "an array of strings",
725 })
726}
727
728pub(crate) fn string_map_field(
729 entry: &NativeMap,
730 key: &str,
731) -> Result<Option<BTreeMap<String, String>>, MapError> {
732 let Some(value) = entry.get(key) else {
733 return Ok(None);
734 };
735 value
736 .as_object()
737 .and_then(|map| {
738 map.iter()
739 .map(|(name, value)| {
740 value
741 .as_str()
742 .map(|value| (name.to_owned(), value.to_owned()))
743 })
744 .collect::<Option<BTreeMap<_, _>>>()
745 })
746 .map(Some)
747 .ok_or_else(|| MapError::UnexpectedShape {
748 field: key.to_owned(),
749 expected: "an object of strings",
750 })
751}
752
753fn is_windows_shim(command: &str) -> bool {
756 let name = command
757 .rsplit(['/', '\\'])
758 .next()
759 .unwrap_or(command)
760 .to_ascii_lowercase();
761 name.ends_with(".cmd") || name.ends_with(".bat") || WINDOWS_SHIMS.contains(&name.as_str())
762}
763
764fn shell_shim(command: &str, args: &[String]) -> (String, Vec<String>) {
767 if !is_windows_shim(command) {
768 return (command.to_owned(), args.to_vec());
769 }
770 let mut shimmed = Vec::with_capacity(args.len() + 2);
771 shimmed.push("/c".to_owned());
772 shimmed.push(command.to_owned());
773 shimmed.extend_from_slice(args);
774 ("cmd".to_owned(), shimmed)
775}
776
777fn shell_unshim(command: &str, args: &[String]) -> Option<(String, Vec<String>)> {
781 let is_cmd = command.eq_ignore_ascii_case("cmd") || command.eq_ignore_ascii_case("cmd.exe");
782 match args {
783 [flag, inner, rest @ ..]
784 if is_cmd && flag.eq_ignore_ascii_case("/c") && is_windows_shim(inner) =>
785 {
786 Some((inner.clone(), rest.to_vec()))
787 }
788 _ => None,
789 }
790}
791
792fn write_canonical(value: &NativeValue, out: &mut String) {
793 match value {
794 NativeValue::Null => out.push_str("null"),
795 NativeValue::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
796 NativeValue::Integer(value) => out.push_str(&value.to_string()),
797 NativeValue::Float(value) => out.push_str(&format!("{value:?}")),
798 NativeValue::String(value) => push_string(value, out),
799 NativeValue::Datetime(value) => {
800 out.push_str("datetime(");
801 push_string(value, out);
802 out.push(')');
803 }
804 NativeValue::Array(items) => {
805 out.push('[');
806 for (index, item) in items.iter().enumerate() {
807 if index > 0 {
808 out.push(',');
809 }
810 write_canonical(item, out);
811 }
812 out.push(']');
813 }
814 NativeValue::Object(map) => {
815 let mut members: Vec<(&str, &NativeValue)> = map.iter().collect();
816 members.sort_by(|a, b| a.0.cmp(b.0));
817 out.push('{');
818 for (index, (key, item)) in members.into_iter().enumerate() {
819 if index > 0 {
820 out.push(',');
821 }
822 push_string(key, out);
823 out.push(':');
824 write_canonical(item, out);
825 }
826 out.push('}');
827 }
828 }
829}
830
831fn push_string(value: &str, out: &mut String) {
832 out.push_str(&serde_json::to_string(value).expect("a string serializes"));
833}