blazy 0.2.0

Unified, AI-safe meta-package manager for 22 OS and language package managers
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
use crate::config::BlazyConfig;
use crate::model::{ActionKind, ProviderId};
use crate::providers::ProviderRegistry;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::str::FromStr;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

#[derive(Deserialize)]
struct JsonRpcRequest {
    #[allow(dead_code)]
    jsonrpc: Option<String>,
    id: Option<Value>,
    method: String,
    #[serde(default)]
    params: Value,
}

#[derive(Serialize)]
struct JsonRpcResponse {
    jsonrpc: &'static str,
    id: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<JsonRpcError>,
}

#[derive(Serialize)]
struct JsonRpcError {
    code: i64,
    message: String,
}

pub async fn run_stdio_server(
    registry: ProviderRegistry,
    config: BlazyConfig,
) -> Result<(), String> {
    let stdin = tokio::io::stdin();
    let mut stdout = tokio::io::stdout();
    let mut lines = BufReader::new(stdin).lines();
    let mut cached_providers: Option<Vec<crate::model::ProviderStatus>> = None;

    while let Some(line) = lines
        .next_line()
        .await
        .map_err(|e| format!("failed reading stdin: {e}"))?
    {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let req: JsonRpcRequest = match serde_json::from_str(trimmed) {
            Ok(r) => r,
            Err(err) => {
                let resp = JsonRpcResponse {
                    jsonrpc: "2.0",
                    id: Value::Null,
                    result: None,
                    error: Some(JsonRpcError {
                        code: -32700,
                        message: format!("Parse error: {err}"),
                    }),
                };
                write_response(&mut stdout, &resp).await?;
                continue;
            }
        };

        // Notifications have no `id` and expect no response.
        let Some(id) = req.id else {
            continue;
        };

        let resp = handle_request(
            id,
            &req.method,
            req.params,
            &registry,
            &config,
            &mut cached_providers,
        )
        .await;
        write_response(&mut stdout, &resp).await?;
    }

    Ok(())
}

async fn write_response(
    stdout: &mut tokio::io::Stdout,
    resp: &JsonRpcResponse,
) -> Result<(), String> {
    let encoded = serde_json::to_string(resp).map_err(|e| e.to_string())?;
    stdout
        .write_all(encoded.as_bytes())
        .await
        .map_err(|e| e.to_string())?;
    stdout.write_all(b"\n").await.map_err(|e| e.to_string())?;
    stdout.flush().await.map_err(|e| e.to_string())?;
    Ok(())
}

async fn handle_request(
    id: Value,
    method: &str,
    params: Value,
    registry: &ProviderRegistry,
    config: &BlazyConfig,
    cached_providers: &mut Option<Vec<crate::model::ProviderStatus>>,
) -> JsonRpcResponse {
    match method {
        "initialize" => JsonRpcResponse {
            jsonrpc: "2.0",
            id,
            result: Some(json!({
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {}
                },
                "serverInfo": {
                    "name": "blazy",
                    "version": env!("CARGO_PKG_VERSION")
                }
            })),
            error: None,
        },
        "ping" => JsonRpcResponse {
            jsonrpc: "2.0",
            id,
            result: Some(json!({})),
            error: None,
        },
        "tools/list" => JsonRpcResponse {
            jsonrpc: "2.0",
            id,
            result: Some(json!({ "tools": tool_definitions() })),
            error: None,
        },
        "tools/call" => {
            let name = params
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let args = params
                .get("arguments")
                .cloned()
                .unwrap_or_else(|| json!({}));
            let result = call_tool(name, args, registry, config, cached_providers).await;
            JsonRpcResponse {
                jsonrpc: "2.0",
                id,
                result: Some(result),
                error: None,
            }
        }
        other => JsonRpcResponse {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(JsonRpcError {
                code: -32601,
                message: format!("Method not found: {other}"),
            }),
        },
    }
}

fn tool_definitions() -> Value {
    json!([
        {
            "name": "detect_providers",
            "description": "Detect installed package managers (scoop, winget, choco, npm, pnpm, uv, pip, cargo), their versions, and capabilities.",
            "inputSchema": {
                "type": "object",
                "properties": {},
                "additionalProperties": false
            }
        },
        {
            "name": "search_packages",
            "description": "Search for packages across available package managers.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": { "type": "string", "description": "Package name or search term" },
                    "providers": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Optional list of provider IDs to restrict search to"
                    }
                },
                "required": ["query"],
                "additionalProperties": false
            }
        },
        {
            "name": "list_installed",
            "description": "List installed packages across available package managers.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "providers": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Optional list of provider IDs"
                    }
                },
                "additionalProperties": false
            }
        },
        {
            "name": "plan_action",
            "description": "Create a deterministic dry-run execution plan for add/remove/update without modifying the system.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": { "type": "string", "enum": ["add", "remove", "update"] },
                    "target": { "type": "string", "description": "Package target, e.g. ripgrep, scoop:ripgrep, uv:ruff@0.9.0" },
                    "provider": { "type": "string", "description": "Optional forced provider ID" }
                },
                "required": ["action", "target"],
                "additionalProperties": false
            }
        },
        {
            "name": "apply_plan",
            "description": "Plan and execute a package manager action (add, remove, or update). Defaults to dry_run=true for safety; pass dry_run=false to execute.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": { "type": "string", "enum": ["add", "remove", "update"] },
                    "target": { "type": "string", "description": "Package target, e.g. ripgrep or scoop:ripgrep" },
                    "provider": { "type": "string", "description": "Optional forced provider ID" },
                    "dry_run": { "type": "boolean", "default": true, "description": "Preview the execution plan without mutating (defaults to true)" },
                    "allow_elevation": { "type": "boolean", "description": "Allow actions that may trigger admin elevation" }
                },
                "required": ["action", "target"],
                "additionalProperties": false
            }
        },
        {
            "name": "which_command",
            "description": "Locate a command on PATH, detect shadowed binaries, and identify the likely owning package manager.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "command": { "type": "string", "description": "Binary or command name (e.g. rg, node, uv)" }
                },
                "required": ["command"],
                "additionalProperties": false
            }
        },
        {
            "name": "audit_duplicates",
            "description": "Audit installed packages across all providers to find duplicate or conflicting installations.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "providers": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Optional list of provider IDs"
                    }
                },
                "additionalProperties": false
            }
        },
        {
            "name": "check_outdated",
            "description": "Check which installed packages have updates available across providers.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "providers": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Optional list of provider IDs"
                    }
                },
                "additionalProperties": false
            }
        }
    ])
}

async fn call_tool(
    name: &str,
    args: Value,
    registry: &ProviderRegistry,
    config: &BlazyConfig,
    cached_providers: &mut Option<Vec<crate::model::ProviderStatus>>,
) -> Value {
    match name {
        "detect_providers" => {
            let refresh = args.get("refresh").and_then(|v| v.as_bool()).unwrap_or(false);
            if refresh || cached_providers.is_none() {
                *cached_providers = Some(registry.detect_all().await);
            }
            let statuses = cached_providers.as_ref().unwrap();
            mcp_ok(json!({ "providers": statuses, "cached": !refresh }))
        }
        "search_packages" => {
            let Some(query) = args.get("query").and_then(|v| v.as_str()) else {
                return mcp_err("missing required parameter 'query'");
            };
            let filter = match parse_provider_list(args.get("providers")) {
                Ok(f) => f,
                Err(e) => return mcp_err(&e),
            };
            let (candidates, warnings) = registry.search_all(query, &filter, config).await;
            mcp_ok(json!({ "candidates": candidates, "warnings": warnings }))
        }
        "list_installed" => {
            let filter = match parse_provider_list(args.get("providers")) {
                Ok(f) => f,
                Err(e) => return mcp_err(&e),
            };
            let (packages, warnings) = registry.list_all(&filter, config).await;
            mcp_ok(json!({ "packages": packages, "warnings": warnings }))
        }
        "plan_action" => {
            let (action, target, forced) = match parse_action_args(&args) {
                Ok(v) => v,
                Err(e) => return mcp_err(&e),
            };
            match registry
                .resolve_and_plan(action, &target, forced, config)
                .await
            {
                Ok((plan, warnings)) => mcp_ok(json!({ "plan": plan, "warnings": warnings })),
                Err(e) => mcp_err(&e),
            }
        }
        "apply_plan" => {
            let (action, target, forced) = match parse_action_args(&args) {
                Ok(v) => v,
                Err(e) => return mcp_err(&e),
            };
            let dry_run = args
                .get("dry_run")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let allow_elevation = args
                .get("allow_elevation")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let (plan, warnings) = match registry
                .resolve_and_plan(action, &target, forced, config)
                .await
            {
                Ok(v) => v,
                Err(e) => return mcp_err(&e),
            };
            if dry_run {
                return mcp_ok(json!({ "dry_run": true, "plan": plan, "warnings": warnings }));
            }
            match registry.execute_plan(plan, config, allow_elevation).await {
                Ok(result) => {
                    let is_err = !result.success;
                    let text = serde_json::to_string_pretty(&json!({
                        "result": result,
                        "warnings": warnings
                    }))
                    .unwrap_or_default();
                    json!({
                        "content": [{ "type": "text", "text": text }],
                        "isError": is_err
                    })
                }
                Err(e) => mcp_err(&e),
            }
        }
        "which_command" => {
            let Some(command) = args.get("command").and_then(|v| v.as_str()) else {
                return mcp_err("missing required parameter 'command'");
            };
            let report = crate::diagnostics::inspect_which(command);
            mcp_ok(json!({ "report": report }))
        }
        "audit_duplicates" => {
            let filter = match parse_provider_list(args.get("providers")) {
                Ok(f) => f,
                Err(e) => return mcp_err(&e),
            };
            let (installed, warnings) = registry.list_all(&filter, config).await;
            let duplicates = crate::diagnostics::find_duplicates(&installed);
            mcp_ok(json!({
                "total_packages": installed.len(),
                "duplicate_count": duplicates.len(),
                "duplicates": duplicates,
                "warnings": warnings
            }))
        }
        "check_outdated" => {
            let filter = match parse_provider_list(args.get("providers")) {
                Ok(f) => f,
                Err(e) => return mcp_err(&e),
            };
            let (outdated, warnings) = registry.outdated_all(&filter, config).await;
            mcp_ok(json!({
                "outdated_count": outdated.len(),
                "outdated": outdated,
                "warnings": warnings
            }))
        }
        other => mcp_err(&format!("unknown tool '{other}'")),
    }
}

fn parse_provider_list(val: Option<&Value>) -> Result<Vec<ProviderId>, String> {
    let Some(arr) = val.and_then(|v| v.as_array()) else {
        return Ok(Vec::new());
    };
    arr.iter()
        .map(|item| {
            let s = item
                .as_str()
                .ok_or_else(|| "provider entry must be a string".to_string())?;
            ProviderId::from_str(s)
        })
        .collect()
}

fn parse_action_args(args: &Value) -> Result<(ActionKind, String, Option<ProviderId>), String> {
    let action_str = args
        .get("action")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "missing required parameter 'action'".to_string())?;
    let action = match action_str {
        "add" => ActionKind::Add,
        "remove" => ActionKind::Remove,
        "update" => ActionKind::Update,
        other => return Err(format!("invalid action '{other}'")),
    };
    let target = args
        .get("target")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "missing required parameter 'target'".to_string())?
        .to_string();
    let forced = match args.get("provider").and_then(|v| v.as_str()) {
        Some(p) => Some(ProviderId::from_str(p)?),
        None => None,
    };
    Ok((action, target, forced))
}

fn mcp_ok(payload: Value) -> Value {
    let text = serde_json::to_string_pretty(&payload).unwrap_or_default();
    json!({
        "content": [{ "type": "text", "text": text }],
        "isError": false
    })
}

fn mcp_err(message: &str) -> Value {
    json!({
        "content": [{ "type": "text", "text": message }],
        "isError": true
    })
}

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

    #[tokio::test]
    async fn mcp_handles_initialize_and_tools_list() {
        let registry = ProviderRegistry::new();
        let config = BlazyConfig::default();
        let mut cache = None;

        let init = handle_request(json!(1), "initialize", json!({}), &registry, &config, &mut cache).await;
        assert!(init.error.is_none());
        assert_eq!(
            init.result.unwrap()["serverInfo"]["name"],
            json!("blazy")
        );

        let tools = handle_request(json!(2), "tools/list", json!({}), &registry, &config, &mut cache).await;
        let arr = tools.result.unwrap()["tools"].as_array().unwrap().clone();
        assert_eq!(arr.len(), 8);
    }
}