1use std::collections::BTreeMap;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::env::Os;
9use crate::error::ErrorCode;
10use crate::model::clients::{ClientSelection, NATIVE_NAME_KEY, known_client};
11use crate::model::ids::IdKind;
12use crate::model::validate::{Diagnostics, at, join};
13use crate::model::{SCHEMA_VERSION, StoreModel};
14
15pub const OS_NAMES: [&str; 3] = [Os::Windows.as_str(), Os::Linux.as_str(), Os::MacOs.as_str()];
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
19#[serde(rename_all = "lowercase")]
20pub enum Transport {
21 Stdio,
22 Http,
23 Sse,
24}
25
26impl Transport {
27 pub const fn as_str(self) -> &'static str {
28 match self {
29 Transport::Stdio => "stdio",
30 Transport::Http => "http",
31 Transport::Sse => "sse",
32 }
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
38#[serde(rename_all = "lowercase")]
39pub enum DeliveryMode {
40 Auto,
41 Env,
42 Launch,
43 Command,
44 Inline,
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
49#[schemars(title = "Surjection MCP server (store/servers/<id>.toml)")]
50pub struct Server {
51 #[schemars(extend("const" = 1))]
53 pub schema: i64,
54 #[schemars(extend("pattern" = crate::model::ids::SLUG_PATTERN))]
56 pub id: String,
57 #[serde(flatten)]
58 pub body: ServerBody,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub enable: Option<Enable>,
62 #[serde(flatten)]
63 #[schemars(skip)]
64 pub extra: toml::Table,
65}
66
67impl StoreModel for Server {
68 const SCHEMA_NAME: &'static str = "server";
69}
70
71#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
74pub struct ServerBody {
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub display_name: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub description: Option<String>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub tags: Option<Vec<String>>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub transport: Option<Transport>,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub command: Option<String>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub args: Option<Vec<String>>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub cwd: Option<String>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub url: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub headers: Option<BTreeMap<String, String>>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub env: Option<BTreeMap<String, String>>,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub delivery: Option<Delivery>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub tools: Option<ToolFilter>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub os: Option<BTreeMap<String, ServerOverride>>,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
113 #[schemars(with = "Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>")]
114 pub client: Option<BTreeMap<String, toml::Table>>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub meta: Option<Meta>,
117}
118
119#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
122pub struct ServerFields {
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub transport: Option<Transport>,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub command: Option<String>,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub args: Option<Vec<String>>,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub cwd: Option<String>,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub url: Option<String>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub headers: Option<BTreeMap<String, String>>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub env: Option<BTreeMap<String, String>>,
137}
138
139#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
141pub struct ServerOverride {
142 #[serde(flatten)]
143 pub fields: ServerFields,
144 #[serde(flatten)]
145 #[schemars(skip)]
146 pub extra: toml::Table,
147}
148
149#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
150pub struct Enable {
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub clients: Option<ClientSelection>,
154 #[serde(flatten)]
155 #[schemars(skip)]
156 pub extra: toml::Table,
157}
158
159#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
160pub struct Delivery {
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub mode: Option<DeliveryMode>,
163 #[serde(flatten)]
164 #[schemars(skip)]
165 pub extra: toml::Table,
166}
167
168#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
169pub struct ToolFilter {
170 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub allow: Option<Vec<String>>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub deny: Option<Vec<String>>,
176 #[serde(flatten)]
177 #[schemars(skip)]
178 pub extra: toml::Table,
179}
180
181#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
182pub struct Meta {
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub homepage: Option<String>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub origin: Option<String>,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub source: Option<ServerSource>,
193 #[serde(flatten)]
194 #[schemars(skip)]
195 pub extra: toml::Table,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
200#[serde(rename_all = "lowercase")]
201pub enum ServerSourceKind {
202 Git,
203 Local,
204 Registry,
206}
207
208impl ServerSourceKind {
209 pub const fn as_str(self) -> &'static str {
210 match self {
211 ServerSourceKind::Git => "git",
212 ServerSourceKind::Local => "local",
213 ServerSourceKind::Registry => "registry",
214 }
215 }
216}
217
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
221pub struct ServerSource {
222 pub kind: ServerSourceKind,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub url: Option<String>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub folder: Option<String>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub path: Option<String>,
234 #[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
236 pub git_ref: Option<String>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 #[schemars(extend("pattern" = "^[0-9a-f]{40}$"))]
240 pub commit: Option<String>,
241 pub file: String,
243 pub converter: String,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub entry: Option<String>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub checkout: Option<bool>,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub machine: Option<String>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub catalog: Option<String>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub version: Option<String>,
263 #[serde(flatten)]
264 #[schemars(skip)]
265 pub extra: toml::Table,
266}
267
268impl ServerSource {
269 pub fn uses_checkout(&self) -> bool {
270 self.checkout == Some(true)
271 }
272
273 fn validate_into(&self, path: &str, d: &mut Diagnostics) {
274 match self.kind {
275 ServerSourceKind::Git if self.url.as_deref().is_none_or(str::is_empty) => d.error(
276 ErrorCode::MissingField,
277 join(path, "url"),
278 "a git source needs its url",
279 ),
280 ServerSourceKind::Local if self.folder.as_deref().is_none_or(str::is_empty) => d.error(
281 ErrorCode::MissingField,
282 join(path, "folder"),
283 "a local source needs its folder",
284 ),
285 ServerSourceKind::Registry if self.url.as_deref().is_none_or(str::is_empty) => d.error(
286 ErrorCode::MissingField,
287 join(path, "url"),
288 "a registry source needs the registry's url",
289 ),
290 ServerSourceKind::Registry if self.catalog.as_deref().is_none_or(str::is_empty) => d
291 .error(
292 ErrorCode::MissingField,
293 join(path, "catalog"),
294 "a registry source needs its catalog entry",
295 ),
296 ServerSourceKind::Registry if self.version.as_deref().is_none_or(str::is_empty) => d
297 .error(
298 ErrorCode::MissingField,
299 join(path, "version"),
300 "a registry source needs its version",
301 ),
302 _ => {}
303 }
304 if self.kind == ServerSourceKind::Registry
305 && let Some(problem) = self
306 .url
307 .as_deref()
308 .filter(|url| !url.is_empty())
309 .and_then(crate::model::catalogs::registry_url_problem)
310 {
311 d.error(ErrorCode::InvalidValue, join(path, "url"), problem);
312 }
313 if self.commit.is_some() && self.kind == ServerSourceKind::Registry {
314 d.error(
315 ErrorCode::InvalidValue,
316 join(path, "commit"),
317 "a registry source has a version, not a commit",
318 );
319 }
320 if self.version.is_some() && self.kind != ServerSourceKind::Registry {
321 d.error(
322 ErrorCode::InvalidValue,
323 join(path, "version"),
324 "only a registry source has a version",
325 );
326 }
327 if let Some(commit) = &self.commit
328 && !crate::model::ids::is_commit_id(commit)
329 {
330 d.error(
331 ErrorCode::InvalidValue,
332 join(path, "commit"),
333 format!("{commit:?} is not a commit id (40 hex characters)"),
334 );
335 }
336 if self.machine.is_some() && self.kind != ServerSourceKind::Local {
337 d.error(
338 ErrorCode::InvalidValue,
339 join(path, "machine"),
340 "only a local folder source is bound to a machine",
341 );
342 }
343 if self.uses_checkout() && self.kind != ServerSourceKind::Git {
344 d.error(
345 ErrorCode::InvalidValue,
346 join(path, "checkout"),
347 "only a git source runs from a checkout",
348 );
349 }
350 if self.file.is_empty() || self.converter.is_empty() {
351 d.error(
352 ErrorCode::MissingField,
353 path.to_owned(),
354 "a source needs its file and converter",
355 );
356 }
357 }
358}
359
360impl Server {
361 pub fn new(id: impl Into<String>) -> Self {
363 Self {
364 schema: SCHEMA_VERSION,
365 id: id.into(),
366 body: ServerBody::default(),
367 enable: None,
368 extra: toml::Table::new(),
369 }
370 }
371
372 pub fn validate(&self, file_id: Option<&str>) -> Diagnostics {
374 let mut d = Diagnostics::new();
375 d.check_named_id(IdKind::Server, &self.id, "id", file_id);
376 self.body.validate_into("", true, &mut d);
377 if let Some(clients) = self.enable.as_ref().and_then(|e| e.clients.as_ref()) {
378 d.check_client_selection(clients, "enable.clients");
379 }
380 d
381 }
382
383 pub fn set_clients(&mut self, clients: Option<ClientSelection>) {
386 self.enable = match (self.enable.take(), clients) {
387 (Some(mut enable), clients) => {
388 enable.clients = clients;
389 (enable.clients.is_some() || !enable.extra.is_empty()).then_some(enable)
390 }
391 (None, Some(clients)) => Some(Enable {
392 clients: Some(clients),
393 ..Enable::default()
394 }),
395 (None, None) => None,
396 };
397 }
398}
399
400impl ServerBody {
401 pub fn fields(&self) -> ServerFields {
403 ServerFields {
404 transport: self.transport,
405 command: self.command.clone(),
406 args: self.args.clone(),
407 cwd: self.cwd.clone(),
408 url: self.url.clone(),
409 headers: self.headers.clone(),
410 env: self.env.clone(),
411 }
412 }
413
414 pub(crate) fn validate_into(&self, prefix: &str, complete: bool, d: &mut Diagnostics) {
417 let base = self.fields();
418 base.check_templates(prefix, d);
419 let overrides = self.os.as_ref();
420 for (os, over) in overrides.into_iter().flatten() {
421 let path = join(&join(prefix, "os"), os);
422 if !OS_NAMES.contains(&os.as_str()) {
423 d.warning(
424 ErrorCode::UnknownOs,
425 &path,
426 format!("unknown OS {os:?}; expected one of {OS_NAMES:?}; kept as written"),
427 );
428 }
429 over.fields.check_templates(&path, d);
430 }
431 if complete {
432 check_transport(&base, overrides, prefix, d);
433 }
434 for (client_id, table) in self.client.iter().flatten() {
435 let path = join(&join(prefix, "client"), client_id);
436 check_passthrough(client_id, table, &path, d);
437 }
438 let meta_path = join(prefix, "meta");
439 if let Some(origin) = self.meta.as_ref().and_then(|meta| meta.origin.as_ref())
440 && !is_valid_origin(origin)
441 {
442 d.error(
443 ErrorCode::InvalidValue,
444 join(&meta_path, "origin"),
445 format!(
446 "invalid origin {origin:?}; expected manual, imported:<client>, \
447 migrated:skilldock, catalog:<source>, source:git or source:local"
448 ),
449 );
450 }
451 if let Some(source) = self.meta.as_ref().and_then(|meta| meta.source.as_ref()) {
452 source.validate_into(&join(&meta_path, "source"), d);
453 }
454 }
455}
456
457impl ServerFields {
458 pub fn merged(&self, over: &ServerFields) -> ServerFields {
461 let merge_map = |base: &Option<BTreeMap<String, String>>,
462 over: &Option<BTreeMap<String, String>>| {
463 match (base, over) {
464 (Some(base), Some(over)) => {
465 let mut merged = base.clone();
466 merged.extend(over.iter().map(|(k, v)| (k.clone(), v.clone())));
467 Some(merged)
468 }
469 (base, None) => base.clone(),
470 (None, over) => over.clone(),
471 }
472 };
473 ServerFields {
474 transport: over.transport.or(self.transport),
475 command: over.command.clone().or_else(|| self.command.clone()),
476 args: over.args.clone().or_else(|| self.args.clone()),
477 cwd: over.cwd.clone().or_else(|| self.cwd.clone()),
478 url: over.url.clone().or_else(|| self.url.clone()),
479 headers: merge_map(&self.headers, &over.headers),
480 env: merge_map(&self.env, &over.env),
481 }
482 }
483
484 fn has(&self, field: &str) -> bool {
485 match field {
486 "transport" => self.transport.is_some(),
487 "command" => self.command.is_some(),
488 "args" => self.args.is_some(),
489 "cwd" => self.cwd.is_some(),
490 "url" => self.url.is_some(),
491 "headers" => self.headers.is_some(),
492 "env" => self.env.is_some(),
493 _ => false,
494 }
495 }
496
497 pub(crate) fn check_templates(&self, prefix: &str, d: &mut Diagnostics) {
499 for (field, value) in [
500 ("command", &self.command),
501 ("cwd", &self.cwd),
502 ("url", &self.url),
503 ] {
504 if let Some(value) = value {
505 d.check_template(value, &join(prefix, field));
506 }
507 }
508 for (index, arg) in self.args.iter().flatten().enumerate() {
509 d.check_template(arg, &at(&join(prefix, "args"), index));
510 }
511 for (field, map) in [("headers", &self.headers), ("env", &self.env)] {
512 for (key, value) in map.iter().flatten() {
513 d.check_template(value, &join(&join(prefix, field), key));
514 }
515 }
516 }
517}
518
519fn check_transport(
524 base: &ServerFields,
525 overrides: Option<&BTreeMap<String, ServerOverride>>,
526 prefix: &str,
527 d: &mut Diagnostics,
528) {
529 let has_os_override = overrides
530 .is_some_and(|overrides| overrides.keys().any(|os| OS_NAMES.contains(&os.as_str())));
531 let views: Vec<(Option<&str>, ServerFields)> = if has_os_override {
532 OS_NAMES
533 .iter()
534 .map(|os| {
535 let over = overrides.and_then(|overrides| overrides.get(*os));
536 let view = over.map_or_else(|| base.clone(), |over| base.merged(&over.fields));
537 (Some(*os), view)
538 })
539 .collect()
540 } else {
541 vec![(None, base.clone())]
542 };
543
544 let mut problems: Vec<(ErrorCode, String, String, Vec<&'static str>)> = Vec::new();
546 let mut report = |code: ErrorCode, field: &str, os: Option<&'static str>, message: String| {
547 let path = match os {
548 Some(os) if !base.has(field) && code == ErrorCode::FieldNotAllowed => {
549 join(&join(&join(prefix, "os"), os), field)
550 }
551 _ => join(prefix, field),
552 };
553 match problems
554 .iter_mut()
555 .find(|(c, p, m, _)| *c == code && *p == path && *m == message)
556 {
557 Some((.., oses)) => oses.extend(os),
558 None => problems.push((code, path, message, os.into_iter().collect())),
559 }
560 };
561 for (os, view) in &views {
562 let Some(transport) = view.transport else {
563 report(
564 ErrorCode::MissingField,
565 "transport",
566 *os,
567 "`transport` is required: stdio, http or sse".to_owned(),
568 );
569 continue;
570 };
571 let (required, forbidden): (&str, &[&str]) = match transport {
572 Transport::Stdio => ("command", &["url", "headers"]),
573 Transport::Http | Transport::Sse => ("url", &["command", "args", "env"]),
574 };
575 let name = transport.as_str();
576 if !view.has(required) {
577 report(
578 ErrorCode::MissingField,
579 required,
580 *os,
581 format!("{name} servers need `{required}`"),
582 );
583 }
584 for field in forbidden {
585 if view.has(field) {
586 report(
587 ErrorCode::FieldNotAllowed,
588 field,
589 *os,
590 format!("{name} servers must not set `{field}`"),
591 );
592 }
593 }
594 }
595 for (code, path, message, oses) in problems {
596 let message = if oses.is_empty() || oses.len() == views.len() {
597 message
598 } else {
599 format!("{message} (on {})", oses.join(", "))
600 };
601 d.error(code, path, message);
602 }
603}
604
605fn check_passthrough(client_id: &str, table: &toml::Table, path: &str, d: &mut Diagnostics) {
606 let known = known_client(client_id);
607 if known.is_none() {
608 d.warning(
609 ErrorCode::UnknownClient,
610 path,
611 format!("unknown client {client_id:?}; kept as written"),
612 );
613 }
614 for (key, value) in table {
615 let key_path = join(path, key);
616 if key == NATIVE_NAME_KEY {
617 if !value.as_str().is_some_and(|name| !name.trim().is_empty()) {
618 d.error(
619 ErrorCode::InvalidValue,
620 key_path,
621 "`native_name` must be a non-empty string",
622 );
623 }
624 continue;
625 }
626 if let Some(known) = known
627 && !known.passthrough.contains(&key.as_str())
628 {
629 let allowed = if known.passthrough.is_empty() {
630 format!("{client_id} accepts only `{NATIVE_NAME_KEY}`")
631 } else {
632 format!(
633 "{client_id} accepts `{NATIVE_NAME_KEY}`, `{}`",
634 known.passthrough.join("`, `")
635 )
636 };
637 d.error(
638 ErrorCode::PassthroughNotAllowed,
639 &key_path,
640 format!("`{key}` is not a passthrough field: {allowed}"),
641 );
642 continue;
643 }
644 check_value_templates(value, &key_path, d);
645 }
646}
647
648fn check_value_templates(value: &toml::Value, path: &str, d: &mut Diagnostics) {
649 match value {
650 toml::Value::String(text) => d.check_template(text, path),
651 toml::Value::Array(items) => {
652 for (index, item) in items.iter().enumerate() {
653 check_value_templates(item, &at(path, index), d);
654 }
655 }
656 toml::Value::Table(table) => {
657 for (key, item) in table {
658 check_value_templates(item, &join(path, key), d);
659 }
660 }
661 _ => {}
662 }
663}
664
665fn is_valid_origin(origin: &str) -> bool {
666 match origin.split_once(':') {
667 None => origin == "manual",
668 Some(("imported", client)) => !client.is_empty(),
669 Some(("migrated", source)) => source == "skilldock",
670 Some(("catalog", source)) => !source.is_empty(),
671 Some(("source", kind)) => matches!(kind, "git" | "local"),
672 Some(_) => false,
673 }
674}