dynamic-mcp 1.5.0

MCP proxy server that reduces LLM context overhead with on-demand tool loading from multiple upstream servers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use crate::cli::tool_detector::{ConfigFormat, Tool};
use crate::config::schema::IntermediateServerConfig;
use anyhow::{anyhow, Context, Result};
use std::collections::HashMap;

pub struct ConfigParser {
    tool: Tool,
}

impl ConfigParser {
    pub fn new(tool: Tool) -> Self {
        Self { tool }
    }

    pub fn parse(&self, content: &str) -> Result<HashMap<String, IntermediateServerConfig>> {
        match self.tool.config_format() {
            ConfigFormat::Json => self.parse_json(content),
            ConfigFormat::Jsonc => self.parse_jsonc(content),
            ConfigFormat::JsonOrJsonc => self
                .parse_jsonc(content)
                .or_else(|_| self.parse_json(content)),
            ConfigFormat::Toml => self.parse_toml(content),
        }
    }

    fn parse_json(&self, content: &str) -> Result<HashMap<String, IntermediateServerConfig>> {
        let value: serde_json::Value =
            serde_json::from_str(content).context("Failed to parse JSON config")?;

        self.extract_servers(&value)
    }

    fn parse_jsonc(&self, content: &str) -> Result<HashMap<String, IntermediateServerConfig>> {
        let content_without_comments = Self::strip_line_comments(content);
        let stripped = json_comments::StripComments::new(content_without_comments.as_bytes());
        let value: serde_json::Value = serde_json::from_reader(stripped)
            .context("Failed to parse JSONC config (JSON with comments)")?;

        self.extract_servers(&value)
    }

    fn strip_line_comments(content: &str) -> String {
        content
            .lines()
            .map(|line| {
                if let Some(pos) = line.find("//") {
                    let before_comment = &line[..pos];
                    let in_string = before_comment.matches('"').count() % 2 != 0;
                    if in_string {
                        line.to_string()
                    } else {
                        before_comment.to_string()
                    }
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn parse_toml(&self, content: &str) -> Result<HashMap<String, IntermediateServerConfig>> {
        let value: toml::Value = toml::from_str(content).context("Failed to parse TOML config")?;

        let mcp_table = value
            .get("mcp")
            .and_then(|v| v.as_table())
            .ok_or_else(|| anyhow!("TOML config missing 'mcp' table"))?;

        let mut servers = HashMap::new();

        for (name, server_value) in mcp_table {
            let server_table = server_value
                .as_table()
                .ok_or_else(|| anyhow!("Server '{}' is not a table", name))?;

            let command = server_table
                .get("command")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let args = server_table
                .get("args")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                });

            let env = server_table
                .get("env")
                .and_then(|v| v.as_table())
                .map(|table| {
                    table
                        .iter()
                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                });

            let url = server_table
                .get("url")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let server_type = server_table
                .get("type")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let enabled = server_table.get("enabled").and_then(|v| v.as_bool());

            let intermediate = IntermediateServerConfig {
                command,
                args,
                env: env.map(|e| self.normalize_env_vars(e)),
                url,
                headers: None,
                server_type,
                enabled,
            };

            servers.insert(name.clone(), intermediate);
        }

        Ok(servers)
    }

    fn extract_servers(
        &self,
        value: &serde_json::Value,
    ) -> Result<HashMap<String, IntermediateServerConfig>> {
        let servers_key = match self.tool {
            Tool::OpenCode => "mcp",
            Tool::VSCode => "servers",
            _ => "mcpServers",
        };

        let servers_obj = value
            .get(servers_key)
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                anyhow!(
                    "Config missing '{}' object. Expected format:\n{{\n  \"{}\": {{\n    \"server-name\": {{ ... }}\n  }}\n}}",
                    servers_key,
                    servers_key
                )
            })?;

        let mut result = HashMap::new();

        for (name, server_value) in servers_obj {
            let server_obj = server_value.as_object().ok_or_else(|| {
                anyhow!(
                    "Server '{}' is not an object. Each server must be a JSON object.",
                    name
                )
            })?;

            let command = match self.tool {
                Tool::OpenCode => server_obj
                    .get("command")
                    .and_then(|v| v.as_array())
                    .and_then(|arr| arr.first())
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                _ => server_obj
                    .get("command")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
            };

            let args = match self.tool {
                Tool::OpenCode => server_obj
                    .get("command")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .skip(1)
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    }),
                _ => server_obj
                    .get("args")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    }),
            };

            let env = server_obj
                .get("env")
                .and_then(|v| v.as_object())
                .map(|obj| {
                    obj.iter()
                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                });

            let url = server_obj
                .get("url")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let headers = server_obj
                .get("headers")
                .and_then(|v| v.as_object())
                .map(|obj| {
                    obj.iter()
                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                });

            let server_type = server_obj
                .get("type")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let enabled = server_obj.get("enabled").and_then(|v| v.as_bool());

            let intermediate = IntermediateServerConfig {
                command,
                args,
                env: env.map(|e| self.normalize_env_vars(e)),
                url,
                headers: headers.map(|h| self.normalize_env_vars(h)),
                server_type,
                enabled,
            };

            result.insert(name.clone(), intermediate);
        }

        Ok(result)
    }

    fn normalize_env_vars(&self, map: HashMap<String, String>) -> HashMap<String, String> {
        let pattern = self.tool.env_var_pattern();
        map.into_iter()
            .map(|(k, v)| (k, pattern.normalize(&v)))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_cursor_json() {
        let config = r#"{
            "mcpServers": {
                "test": {
                    "command": "npx",
                    "args": ["-y", "package"],
                    "env": {
                        "TOKEN": "${env:GITHUB_TOKEN}"
                    }
                }
            }
        }"#;

        let parser = ConfigParser::new(Tool::Cursor);
        let result = parser.parse(config).unwrap();

        assert_eq!(result.len(), 1);
        let server = result.get("test").unwrap();
        assert_eq!(server.command, Some("npx".to_string()));
        assert_eq!(
            server.args,
            Some(vec!["-y".to_string(), "package".to_string()])
        );

        let env = server.env.as_ref().unwrap();
        assert_eq!(env.get("TOKEN").unwrap(), "${GITHUB_TOKEN}");
    }

    #[test]
    fn test_parse_opencode_jsonc() {
        let config = r#"{
            // Comment
            "mcp": {
                "test": {
                    "command": ["npx", "-y", "package"],
                    "enabled": true
                }
            }
        }"#;

        let parser = ConfigParser::new(Tool::OpenCode);
        let result = parser.parse(config).unwrap();

        assert_eq!(result.len(), 1);
        let server = result.get("test").unwrap();
        assert_eq!(server.command, Some("npx".to_string()));
        assert_eq!(
            server.args,
            Some(vec!["-y".to_string(), "package".to_string()])
        );
        assert_eq!(server.enabled, Some(true));
    }

    #[test]
    fn test_parse_claude_desktop_json() {
        let config = r#"{
            "mcpServers": {
                "test": {
                    "command": "docker",
                    "args": ["run", "-i", "image"],
                    "env": {
                        "TOKEN": "${GITHUB_TOKEN}"
                    }
                }
            }
        }"#;

        let parser = ConfigParser::new(Tool::ClaudeDesktop);
        let result = parser.parse(config).unwrap();

        let server = result.get("test").unwrap();
        let env = server.env.as_ref().unwrap();
        assert_eq!(env.get("TOKEN").unwrap(), "${GITHUB_TOKEN}");
    }

    #[test]
    fn test_parse_vscode_json_with_url() {
        let config = r#"{
            "servers": {
                "api": {
                    "type": "http",
                    "url": "https://api.example.com",
                    "headers": {
                        "API_Key": "${env:API_KEY}"
                    }
                }
            }
        }"#;

        let parser = ConfigParser::new(Tool::VSCode);
        let result = parser.parse(config).unwrap();

        let server = result.get("api").unwrap();
        assert_eq!(server.url, Some("https://api.example.com".to_string()));
        assert_eq!(server.server_type, Some("http".to_string()));

        let headers = server.headers.as_ref().unwrap();
        assert_eq!(headers.get("API_Key").unwrap(), "${API_KEY}");
    }

    #[test]
    fn test_parse_codex_toml() {
        let config = r#"
[mcp.test]
command = "npx"
args = ["-y", "package"]

[mcp.test.env]
TOKEN = "${GITHUB_TOKEN}"
        "#;

        let parser = ConfigParser::new(Tool::Codex);
        let result = parser.parse(config).unwrap();

        assert_eq!(result.len(), 1);
        let server = result.get("test").unwrap();
        assert_eq!(server.command, Some("npx".to_string()));
        assert_eq!(
            server.args,
            Some(vec!["-y".to_string(), "package".to_string()])
        );

        let env = server.env.as_ref().unwrap();
        assert_eq!(env.get("TOKEN").unwrap(), "${GITHUB_TOKEN}");
    }

    #[test]
    fn test_parse_missing_mcpservers() {
        let config = r#"{"other": {}}"#;
        let parser = ConfigParser::new(Tool::Cursor);
        let result = parser.parse(config);

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("missing 'mcpServers'"));
    }

    #[test]
    fn test_parse_invalid_server_format() {
        let config = r#"{"mcpServers": {"test": "not-an-object"}}"#;
        let parser = ConfigParser::new(Tool::Cursor);
        let result = parser.parse(config);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not an object"));
    }

    #[test]
    fn test_parse_enabled_field() {
        let config = r#"{
            "mcpServers": {
                "enabled-server": {
                    "command": "npx",
                    "args": ["-y", "package"],
                    "enabled": true
                },
                "disabled-server": {
                    "command": "npx",
                    "args": ["-y", "other-package"],
                    "enabled": false
                },
                "default-server": {
                    "command": "npx",
                    "args": ["-y", "default-package"]
                }
            }
        }"#;

        let parser = ConfigParser::new(Tool::Cursor);
        let result = parser.parse(config).unwrap();

        assert_eq!(result.len(), 3);

        let enabled = result.get("enabled-server").unwrap();
        assert_eq!(enabled.enabled, Some(true));

        let disabled = result.get("disabled-server").unwrap();
        assert_eq!(disabled.enabled, Some(false));

        let default = result.get("default-server").unwrap();
        assert_eq!(default.enabled, None);
    }
}