gamecode-mcp2 0.7.0

Minimal, auditable Model Context Protocol server for safe LLM-to-system interaction
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Tool execution is the critical security boundary.
// Every tool must be explicitly configured - no implicit capabilities.

use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::process::Command;
use tracing::{debug, info};

use crate::protocol::Tool;
use crate::validation;

// Tools config - what tools exist is controlled by YAML, not code
#[derive(Debug, Deserialize)]
pub struct ToolsConfig {
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub tools: Vec<ToolDefinition>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ToolDefinition {
    pub name: String,
    pub description: String,
    #[serde(default)]
    pub command: String,
    #[serde(default)]
    pub args: Vec<ArgDefinition>,
    #[serde(default)]
    pub static_flags: Vec<String>,
    pub internal_handler: Option<String>,
    #[allow(dead_code)]
    pub example_output: Option<Value>,
    #[serde(default)]
    pub validation: ValidationConfig,
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct ValidationConfig {
    #[serde(default)]
    pub validate_paths: bool,
    #[serde(default)]
    pub allow_absolute_paths: bool,
    #[serde(default)]  
    pub validate_args: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ArgDefinition {
    pub name: String,
    pub description: String,
    pub required: bool,
    #[serde(rename = "type")]
    pub arg_type: String,
    pub cli_flag: Option<String>,
    #[allow(dead_code)]
    pub default: Option<String>,
    #[serde(default)]
    pub is_path: bool,  // Mark arguments that are file paths
}

#[derive(Default)]
pub struct ToolManager {
    tools: HashMap<String, ToolDefinition>,
}

impl ToolManager {
    pub fn new() -> Self {
        Self::default()
    }

    // Explicit tool loading - admin controls what tools are available
    pub async fn load_from_file(&mut self, path: &Path) -> Result<()> {
        info!("Loading tools from: {}", path.display());

        let content = tokio::fs::read_to_string(path)
            .await
            .context("Failed to read tools file")?;

        // YAML parsing is the only text processing we can't avoid
        let config: ToolsConfig = serde_yaml::from_str(&content).context("Failed to parse YAML")?;

        // Process includes first
        for include in &config.include {
            let include_path = self.resolve_include_path(path, include)?;
            info!("Including tools from: {}", include_path.display());

            // Recursively load included files
            Box::pin(self.load_from_file(&include_path)).await?;
        }

        // Then load tools from this file
        for tool in config.tools {
            info!("Loaded tool: {}", tool.name);
            self.tools.insert(tool.name.clone(), tool);
        }

        Ok(())
    }

    fn resolve_include_path(&self, base_path: &Path, include: &str) -> Result<PathBuf> {
        let base_dir = base_path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("Cannot determine parent directory"))?;

        // Support both relative and absolute paths
        let include_path = if include.starts_with('/') {
            PathBuf::from(include)
        } else {
            match include.starts_with("~/") {
                true => {
                    if let Some(home) = directories::UserDirs::new() {
                        home.home_dir().join(&include[2..])
                    } else {
                        return Err(anyhow::anyhow!("Cannot resolve home directory"));
                    }
                }
                false => {
                    // Relative path
                    base_dir.join(include)
                }
            }
        };

        if !include_path.exists() {
            return Err(anyhow::anyhow!(
                "Include file not found: {}",
                include_path.display()
            ));
        }

        Ok(include_path)
    }


    pub async fn load_with_precedence(&mut self, cli_override: Option<String>) -> Result<()> {
        // Clear precedence order:
        // 1. Command-line flag (--tools-file)
        if let Some(tools_file) = cli_override {
            info!("Loading tools from command-line override: {}", tools_file);
            return self.load_from_file(Path::new(&tools_file)).await;
        }
        
        // 2. Environment variable
        if let Ok(tools_file) = std::env::var("GAMECODE_TOOLS_FILE") {
            info!("Loading tools from GAMECODE_TOOLS_FILE: {}", tools_file);
            return self.load_from_file(Path::new(&tools_file)).await;
        }
        
        // 3. Local tools.yaml in current directory
        let local_tools = PathBuf::from("./tools.yaml");
        if local_tools.exists() {
            info!("Loading tools from local tools.yaml");
            return self.load_from_file(&local_tools).await;
        }
        
        // 4. Auto-detection (only if no local tools.yaml)
        if let Ok(mode) = self.detect_project_type() {
            info!("Auto-detected {} project", mode);
            if self.load_auto_detected_tools(&mode).await.is_ok() {
                return Ok(());
            }
        }
        
        // 5. Config directory fallback
        if let Some(home) = directories::UserDirs::new() {
            let config_tools = home.home_dir()
                .join(".config/gamecode-mcp/tools.yaml");
            if config_tools.exists() {
                info!("Loading tools from config directory");
                return self.load_from_file(&config_tools).await;
            }
        }
        
        Err(anyhow::anyhow!("No tools configuration found. Create tools.yaml or use --tools-file"))
    }
    
    fn detect_project_type(&self) -> Result<String> {
        let detections = vec![
            ("Cargo.toml", "rust"),
            ("package.json", "javascript"),
            ("requirements.txt", "python"),
            ("go.mod", "go"),
            ("pom.xml", "java"),
            ("build.gradle", "java"),
            ("Gemfile", "ruby"),
        ];
        
        for (file, mode) in detections {
            if PathBuf::from(file).exists() {
                return Ok(mode.to_string());
            }
        }
        
        Err(anyhow::anyhow!("No project type detected"))
    }
    
    async fn load_auto_detected_tools(&mut self, mode: &str) -> Result<()> {
        // Try to load language-specific tools
        let lang_file = format!("tools/languages/{}.yaml", mode);
        if PathBuf::from(&lang_file).exists() {
            self.load_from_file(Path::new(&lang_file)).await?;
        }
        
        // Always load core tools as well
        if PathBuf::from("tools/core.yaml").exists() {
            self.load_from_file(Path::new("tools/core.yaml")).await?;
        }
        
        // Load git tools if .git exists
        if PathBuf::from(".git").exists() && PathBuf::from("tools/git.yaml").exists() {
            self.load_from_file(Path::new("tools/git.yaml")).await?;
        }
        
        Ok(())
    }

    // Convert to MCP schema - LLM sees exactly this, nothing hidden
    pub fn get_mcp_tools(&self) -> Vec<Tool> {
        self.tools
            .values()
            .map(|def| {
                let mut properties = serde_json::Map::new();
                let mut required = Vec::new();

                // Build JSON schema from arg definitions
                for arg in &def.args {
                    let arg_schema = match arg.arg_type.as_str() {
                        "string" => json!({
                            "type": "string",
                            "description": arg.description
                        }),
                        "number" => json!({
                            "type": "number",
                            "description": arg.description
                        }),
                        "boolean" => json!({
                            "type": "boolean",
                            "description": arg.description
                        }),
                        "array" => json!({
                            "type": "array",
                            "description": arg.description
                        }),
                        _ => json!({
                            "type": "string",
                            "description": arg.description
                        }),
                    };

                    properties.insert(arg.name.clone(), arg_schema);

                    if arg.required {
                        required.push(json!(arg.name));
                    }
                }

                let schema = json!({
                    "type": "object",
                    "properties": properties,
                    "required": required
                });

                Tool {
                    name: def.name.clone(),
                    description: def.description.clone(),
                    input_schema: schema,
                }
            })
            .collect()
    }

    // Tool execution - the critical security boundary
    pub async fn execute_tool(&self, name: &str, args: Value, injected_values: &HashMap<String, String>) -> Result<Value> {
        let tool = self
            .tools
            .get(name)
            .ok_or_else(|| anyhow::anyhow!("Tool '{}' not found", name))?;

        // Internal handlers are hardcoded - no dynamic code execution
        if let Some(handler) = &tool.internal_handler {
            return self.execute_internal_handler(handler, &args, injected_values).await;
        }

        // External commands - only what's explicitly configured
        if tool.command.is_empty() || tool.command == "internal" {
            return Err(anyhow::anyhow!("Tool '{}' has no command", name));
        }

        let mut cmd = Command::new(&tool.command);
        
        // Set injected values as environment variables for the command
        for (key, value) in injected_values {
            cmd.env(format!("GAMECODE_{}", key.to_uppercase()), value);
        }

        // Add static flags
        for flag in &tool.static_flags {
            cmd.arg(flag);
        }

        // Argument construction - no shell interpretation, direct args only
        if let Some(obj) = args.as_object() {
            for arg_def in &tool.args {
                if let Some(value) = obj.get(&arg_def.name) {
                    // Optional validation
                    if tool.validation.validate_args {
                        validation::validate_typed_value(value, &arg_def.arg_type)?;
                    }
                    
                    // Path validation if marked as path
                    if arg_def.is_path && tool.validation.validate_paths {
                        if let Some(path_str) = value.as_str() {
                            validation::validate_path(path_str, tool.validation.allow_absolute_paths)?;
                        }
                    }
                    
                    let arg_value = value.to_string().trim_matches('"').to_string();
                    
                    if let Some(cli_flag) = &arg_def.cli_flag {
                        cmd.arg(cli_flag);
                        cmd.arg(&arg_value);
                    } else {
                        // Positional argument
                        cmd.arg(&arg_value);
                    }
                }
            }
        }

        debug!("Executing command: {:?}", cmd);

        let output = cmd
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await
            .context("Failed to execute command")?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Try to parse as JSON first
            if let Ok(json_value) = serde_json::from_str::<Value>(&stdout) {
                Ok(json_value)
            } else {
                Ok(json!({
                    "output": stdout.trim(),
                    "status": "success"
                }))
            }
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(anyhow::anyhow!("Command failed: {}", stderr))
        }
    }

    // Internal handlers - hardcoded, no dynamic evaluation
    async fn execute_internal_handler(&self, handler: &str, args: &Value, _injected_values: &HashMap<String, String>) -> Result<Value> {
        match handler {
            "add" => {
                let a = args
                    .get("a")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'a'"))?;
                let b = args
                    .get("b")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'b'"))?;
                Ok(json!({
                    "result": a + b,
                    "operation": "addition"
                }))
            }
            "multiply" => {
                let a = args
                    .get("a")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'a'"))?;
                let b = args
                    .get("b")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'b'"))?;
                Ok(json!({
                    "result": a * b,
                    "operation": "multiplication"
                }))
            }
            "list_files" => {
                let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

                let mut files = Vec::new();
                let mut entries = tokio::fs::read_dir(path).await?;

                while let Some(entry) = entries.next_entry().await? {
                    let metadata = entry.metadata().await?;
                    files.push(json!({
                        "name": entry.file_name().to_string_lossy(),
                        "is_dir": metadata.is_dir(),
                        "size": metadata.len()
                    }));
                }

                Ok(json!({
                    "path": path,
                    "files": files
                }))
            }
            "write_file" => {
                let path = args
                    .get("path")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'path'"))?;
                let content = args
                    .get("content")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'content'"))?;

                tokio::fs::write(path, content).await?;

                Ok(json!({
                    "status": "success",
                    "path": path,
                    "bytes_written": content.len()
                }))
            }
            "create_graphviz_diagram" => {
                let filename = args
                    .get("filename")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'filename'"))?;
                let format = args
                    .get("format")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'format'"))?;
                let content = args
                    .get("content")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'content'"))?;

                // Save DOT source file
                let dot_file = format!("{}.dot", filename);
                tokio::fs::write(&dot_file, content).await?;

                // Generate diagram using GraphViz
                let output_file = format!("{}.{}", filename, format);
                let output = tokio::process::Command::new("dot")
                    .arg(format!("-T{}", format))
                    .arg(&dot_file)
                    .arg("-o")
                    .arg(&output_file)
                    .output()
                    .await?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    return Err(anyhow::anyhow!("GraphViz error: {}", stderr));
                }

                Ok(json!({
                    "status": "success",
                    "source_file": dot_file,
                    "output_file": output_file,
                    "format": format
                }))
            }
            "create_plantuml_diagram" => {
                let filename = args
                    .get("filename")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'filename'"))?;
                let format = args
                    .get("format")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'format'"))?;
                let content = args
                    .get("content")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing parameter 'content'"))?;

                // Save PlantUML source file
                let puml_file = format!("{}.puml", filename);
                tokio::fs::write(&puml_file, content).await?;

                // Generate diagram using PlantUML
                let output = tokio::process::Command::new("plantuml")
                    .arg(format!("-t{}", format))
                    .arg(&puml_file)
                    .output()
                    .await?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    return Err(anyhow::anyhow!("PlantUML error: {}", stderr));
                }

                // PlantUML generates output with same base name
                let output_file = format!("{}.{}", filename, format);

                Ok(json!({
                    "status": "success",
                    "source_file": puml_file,
                    "output_file": output_file,
                    "format": format
                }))
            }
            _ => Err(anyhow::anyhow!("Unknown internal handler: {}", handler)),
        }
    }
}