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;
}
};
let Some(id) = req.id else {
continue;
};
let resp = handle_request(
id,
&req.method,
req.params,
®istry,
&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!({}), ®istry, &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!({}), ®istry, &config, &mut cache).await;
let arr = tools.result.unwrap()["tools"].as_array().unwrap().clone();
assert_eq!(arr.len(), 8);
}
}