poly-mcp 0.3.1

A comprehensive MCP server with filesystem, diagnostics, scripting, time, network, context, git, input, clipboard, and transform tools
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
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::io::{self, BufRead, Write};
use std::path::Path;
use std::sync::Arc;
use anyhow::Result;
use clap::Parser;
use is_terminal::IsTerminal;
use tokio::sync::Mutex;
use axum::{
    extract::State,
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use tower_http::cors::CorsLayer;

use poly_mcp::config::{all_module_info, is_module_compiled};
use poly_mcp::{PolyMcp, ToolConfig};

/// Poly MCP - A comprehensive Model Context Protocol server
///
/// Provides powerful modules for AI assistants, with fine-grained control
/// over which modules and tools are available.
///
/// Modules can be controlled at two levels:
///   Compile-time: Cargo feature flags (e.g., --features "filesystem,git")
///   Runtime: CLI flags or a JSON config file
#[derive(Parser, Debug)]
#[command(name = "poly-mcp")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "A comprehensive MCP server with configurable modules", long_about = None)]
struct Cli {
    /// List all available modules and their tools
    #[arg(short, long)]
    list_modules: bool,

    /// Show verbose startup information
    #[arg(short, long)]
    verbose: bool,

    /// Run as HTTP server instead of stdio mode
    #[arg(short, long)]
    server: bool,

    /// Port to bind HTTP server to (default: 3000)
    #[arg(short, long, default_value = "3000")]
    port: u16,

    /// Host to bind HTTP server to (default: 127.0.0.1)
    #[arg(long, default_value = "127.0.0.1")]
    host: String,

    /// Enable ONLY these modules (comma-separated, disables all others).
    /// Aliases: fs, diag, net, ctx, clip.
    /// Example: --modules fs,git,transform
    #[arg(short, long, value_name = "MODULES")]
    modules: Option<String>,

    /// Disable these specific modules (comma-separated).
    /// Example: --disable-modules silent,input
    #[arg(long, value_name = "MODULES")]
    disable_modules: Option<String>,

    /// Disable specific tools (comma-separated).
    /// Example: --disable-tools fs_delete,silent_script
    #[arg(long, value_name = "TOOLS")]
    disable_tools: Option<String>,

    /// Path to JSON config file for module/tool filtering.
    /// Auto-loads ./poly-mcp.config.json if present.
    #[arg(short, long, value_name = "PATH")]
    config: Option<String>,

    /// Print a default config file to stdout and exit
    #[arg(long)]
    generate_config: bool,
}

// ── JSON-RPC types ──────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcRequest {
    jsonrpc: String,
    id: Option<Value>,
    method: String,
    params: Option<Value>,
}

#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcResponse {
    jsonrpc: String,
    id: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<JsonRpcError>,
}

#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcError {
    code: i32,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<Value>,
}

// ── Request handling ────────────────────────────────────────────────

async fn handle_mcp_request(server: &mut PolyMcp, request: JsonRpcRequest) -> JsonRpcResponse {
    let id = request.id.clone();

    match request.method.as_str() {
        "initialize" => JsonRpcResponse {
            jsonrpc: "2.0".to_string(),
            id,
            result: Some(server.get_server_info()),
            error: None,
        },
        "tools/list" => JsonRpcResponse {
            jsonrpc: "2.0".to_string(),
            id,
            result: Some(server.list_tools()),
            error: None,
        },
        "tools/call" => {
            let params = request.params.unwrap_or(json!({}));
            let name = params["name"].as_str().unwrap_or("");
            let arguments = params.get("arguments").cloned();

            match server.call_tool(name, arguments).await {
                Ok(result) => JsonRpcResponse {
                    jsonrpc: "2.0".to_string(),
                    id,
                    result: Some(json!({
                        "content": [{
                            "type": "text",
                            "text": result.to_string()
                        }]
                    })),
                    error: None,
                },
                Err(e) => JsonRpcResponse {
                    jsonrpc: "2.0".to_string(),
                    id,
                    result: None,
                    error: Some(JsonRpcError {
                        code: -32000,
                        message: e.to_string(),
                        data: None,
                    }),
                },
            }
        }
        _ => JsonRpcResponse {
            jsonrpc: "2.0".to_string(),
            id,
            result: None,
            error: Some(JsonRpcError {
                code: -32601,
                message: format!("Method not found: {}", request.method),
                data: None,
            }),
        },
    }
}

// ── Display helpers ─────────────────────────────────────────────────

fn print_banner(server: &PolyMcp, verbose: bool) {
    let active = server.active_module_count();

    eprintln!("\n╭────────────────────────────────────────────────────╮");
    eprintln!("│         🔧 Poly MCP Server v{}              │", env!("CARGO_PKG_VERSION"));
    eprintln!("╰────────────────────────────────────────────────────╯\n");

    eprintln!("📡 Protocol: Model Context Protocol (MCP)");
    eprintln!("🔗 Transport: stdio (stdin/stdout) - no network port");
    eprintln!("📋 Format: JSON-RPC 2.0");
    eprintln!("📦 Modules: {} active module(s) loaded\n", active);

    if verbose {
        print_module_status(server);
    }

    eprintln!("✓ Server ready and listening for JSON-RPC requests...");
    eprintln!("ℹ Use --help for more information\n");
}

fn print_module_status(server: &PolyMcp) {
    eprintln!("Module Status:");
    for info in all_module_info() {
        let compiled = is_module_compiled(info.name);
        let runtime_enabled = server.config().modules.is_enabled(info.name);

        let (icon, status) = if !compiled {
            ("○", "NOT COMPILED")
        } else if !runtime_enabled {
            ("✗", "DISABLED")
        } else {
            ("✓", "ACTIVE")
        };

        eprintln!(
            "  {} {:12} - {:3} tools  [{}]",
            icon, info.name, info.tool_count, status
        );
    }
    eprintln!();

    let cfg = server.config();
    if !cfg.tools.enabled.is_empty() {
        eprintln!(
            "Tool whitelist: {} tool(s) explicitly enabled",
            cfg.tools.enabled.len()
        );
    }
    if !cfg.tools.disabled.is_empty() {
        eprintln!(
            "Tool blacklist: {} tool(s) disabled: {}",
            cfg.tools.disabled.len(),
            cfg.tools.disabled.join(", ")
        );
    }
    if !cfg.tools.enabled.is_empty() || !cfg.tools.disabled.is_empty() {
        eprintln!();
    }
}

fn list_all_modules(server: &PolyMcp) {
    println!("\n╭────────────────────────────────────────────────────╮");
    println!("│         🔧 Poly MCP - Available Modules           │");
    println!("╰────────────────────────────────────────────────────╯\n");

    let mut total_active = 0;
    let mut total_tools = 0;

    for info in all_module_info() {
        let compiled = is_module_compiled(info.name);
        let runtime_enabled = server.config().modules.is_enabled(info.name);

        let (icon, status) = if !compiled {
            ("⬜", "NOT COMPILED")
        } else if !runtime_enabled {
            ("🚫", "DISABLED")
        } else {
            ("📦", "ACTIVE")
        };

        println!("{} {} - {} [{}]", icon, info.name, info.description, status);
        println!("   {} tools: {}", info.tool_count, info.tools.join(", "));
        println!();

        if compiled && runtime_enabled {
            total_active += 1;
            total_tools += info.tool_count;
        }
    }

    println!(
        "Active: {}/{} modules, {} tools\n",
        total_active,
        all_module_info().len(),
        total_tools
    );
}

// ── Config loading ──────────────────────────────────────────────────

fn build_config(cli: &Cli) -> Result<ToolConfig> {
    let mut config = ToolConfig::default();

    // Load config file: explicit --config, or auto-detect ./poly-mcp.config.json
    let config_path = cli.config.as_deref().or_else(|| {
        let auto_path = "poly-mcp.config.json";
        if Path::new(auto_path).exists() {
            Some(auto_path)
        } else {
            None
        }
    });

    if let Some(path) = config_path {
        match ToolConfig::from_file(Path::new(path)) {
            Ok(file_config) => {
                config = file_config;
                eprintln!("📄 Loaded config from: {}", path);
            }
            Err(e) => {
                if cli.config.is_some() {
                    return Err(anyhow::anyhow!("Failed to load config '{}': {}", path, e));
                } else {
                    eprintln!("⚠ Failed to parse poly-mcp.config.json: {}", e);
                }
            }
        }
    }

    // CLI overrides take precedence
    config.apply_cli(
        cli.modules.as_deref(),
        cli.disable_modules.as_deref(),
        cli.disable_tools.as_deref(),
    );

    Ok(config)
}

// ── HTTP server mode ────────────────────────────────────────────────

type SharedState = Arc<Mutex<PolyMcp>>;

async fn handle_jsonrpc(
    State(state): State<SharedState>,
    Json(request): Json<JsonRpcRequest>,
) -> Response {
    let mut server = state.lock().await;
    let response = handle_mcp_request(&mut server, request).await;
    Json(response).into_response()
}

async fn health_check() -> Response {
    Json(json!({
        "status": "healthy",
        "service": "poly-mcp",
        "version": env!("CARGO_PKG_VERSION")
    }))
    .into_response()
}

async fn run_http_mode(cli: &Cli, config: ToolConfig) -> Result<()> {
    let server = PolyMcp::new(config);
    let active = server.active_module_count();
    let state = Arc::new(Mutex::new(server));

    let app = Router::new()
        .route("/", post(handle_jsonrpc))
        .route("/jsonrpc", post(handle_jsonrpc))
        .route("/health", axum::routing::get(health_check))
        .layer(CorsLayer::permissive())
        .with_state(state.clone());

    let addr = format!("{}:{}", cli.host, cli.port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;

    eprintln!("\n╭────────────────────────────────────────────────────╮");
    eprintln!("│         🔧 Poly MCP Server v{}              │", env!("CARGO_PKG_VERSION"));
    eprintln!("╰────────────────────────────────────────────────────╯\n");
    eprintln!("📡 Protocol: Model Context Protocol (MCP)");
    eprintln!("🔗 Transport: HTTP (JSON-RPC 2.0)");
    eprintln!("🌐 Address: http://{}", addr);
    eprintln!("📦 Modules: {} active module(s) loaded", active);
    eprintln!("💚 Health: http://{}/health\n", addr);

    if cli.verbose {
        let server = state.lock().await;
        print_module_status(&server);
    }

    eprintln!("✓ Server ready and listening for HTTP requests...");
    eprintln!("ℹ Press Ctrl+C to stop\n");

    axum::serve(listener, app).await?;
    Ok(())
}

// ── Stdio mode ──────────────────────────────────────────────────────

async fn run_stdio_mode(cli: &Cli, config: ToolConfig) -> Result<()> {
    let mut server = PolyMcp::new(config);

    if io::stdin().is_terminal() {
        print_banner(&server, cli.verbose);
    }

    let stdin = io::stdin();
    let mut stdout = io::stdout();

    for line in stdin.lock().lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }

        match serde_json::from_str::<JsonRpcRequest>(&line) {
            Ok(request) => {
                let response = handle_mcp_request(&mut server, request).await;
                let response_json = serde_json::to_string(&response)?;
                writeln!(stdout, "{}", response_json)?;
                stdout.flush()?;
            }
            Err(e) => {
                let error_response = JsonRpcResponse {
                    jsonrpc: "2.0".to_string(),
                    id: None,
                    result: None,
                    error: Some(JsonRpcError {
                        code: -32700,
                        message: format!("Parse error: {}", e),
                        data: None,
                    }),
                };
                let response_json = serde_json::to_string(&error_response)?;
                writeln!(stdout, "{}", response_json)?;
                stdout.flush()?;
            }
        }
    }

    Ok(())
}

// ── Main ────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    tracing_subscriber::fmt::init();

    if cli.generate_config {
        println!("{}", ToolConfig::generate_default());
        return Ok(());
    }

    let config = build_config(&cli)?;

    if cli.list_modules {
        let server = PolyMcp::new(config);
        list_all_modules(&server);
        return Ok(());
    }

    if cli.server {
        run_http_mode(&cli, config).await
    } else {
        run_stdio_mode(&cli, config).await
    }
}