use serde::Deserialize;
use serde_json::{Value, json};
use crate::jsonrpc::{ConnectionContext, Router, RpcError};
use super::ListDirError;
#[derive(Deserialize)]
struct ListDirParams {
#[serde(default)]
path: Option<String>,
#[serde(default)]
include_hidden: Option<bool>,
}
pub fn register(router: &mut Router) {
router.register("fs.list_dir", list_dir);
router.register("fs.list_projects", list_projects);
}
fn to_rpc_error(err: ListDirError) -> RpcError {
let message = err.to_string();
match err {
ListDirError::NotFound(_) => RpcError::not_found(message),
ListDirError::PermissionDenied(_) => RpcError::permission_denied(message),
ListDirError::NotADirectory(_) | ListDirError::NoHome(_) => {
RpcError::invalid_argument(message)
}
ListDirError::Io { .. } => RpcError::internal(message),
}
}
async fn list_dir(params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
let params = if params.is_null() { json!({}) } else { params };
let p: ListDirParams = serde_json::from_value(params)
.map_err(|e| RpcError::invalid_params(format!("fs.list_dir: {e}")))?;
let path = p.path.as_deref().unwrap_or("~");
let listing = super::list_dir(path, p.include_hidden.unwrap_or(false)).map_err(to_rpc_error)?;
serde_json::to_value(listing)
.map_err(|e| RpcError::internal(format!("fs.list_dir: serializing listing: {e}")))
}
async fn list_projects(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
let roster = super::mpm_registry::merged_roster().await;
serde_json::to_value(roster)
.map_err(|e| RpcError::internal(format!("fs.list_projects: serializing roster: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
#[tokio::test]
async fn lists_a_directory() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::create_dir(tmp.path().join("alpha")).expect("mkdir");
let result = list_dir(
json!({"path": tmp.path().display().to_string()}),
test_ctx(),
)
.await
.expect("list_dir must succeed");
assert_eq!(result["entries"][0]["name"], "alpha");
assert_eq!(result["entries"][0]["is_dir"], true);
}
#[tokio::test]
async fn omitted_path_defaults_to_home() {
let Some(home) = dirs::home_dir() else {
return; };
let result = list_dir(json!({}), test_ctx())
.await
.expect("default list_dir must succeed");
let expected = std::fs::canonicalize(&home).unwrap_or(home);
assert_eq!(result["path"], expected.display().to_string());
assert_eq!(result["display_path"], "~");
}
#[tokio::test]
async fn null_params_are_treated_as_empty_object() {
if dirs::home_dir().is_none() {
return;
}
let result = list_dir(Value::Null, test_ctx())
.await
.expect("null params must succeed");
assert_eq!(result["display_path"], "~");
}
#[tokio::test]
async fn response_shape_supports_7a_rendering() {
let tmp = tempfile::tempdir().expect("tempdir");
let repo = tmp.path().join("acme-api");
std::fs::create_dir(&repo).expect("mkdir");
std::fs::create_dir(repo.join(".git")).expect("mkdir .git");
std::fs::create_dir(tmp.path().join("scratch")).expect("mkdir");
let result = list_dir(
json!({"path": tmp.path().display().to_string()}),
test_ctx(),
)
.await
.expect("list_dir must succeed");
assert!(result["display_path"].is_string());
assert!(result["parent"].is_string());
let entries = result["entries"].as_array().expect("entries array");
let acme = entries
.iter()
.find(|e| e["name"] == "acme-api")
.expect("acme-api row");
let scratch = entries
.iter()
.find(|e| e["name"] == "scratch")
.expect("scratch row");
assert_eq!(acme["is_git_repo"], true);
assert_eq!(scratch["is_git_repo"], false);
assert!(acme["path"].is_string());
assert_eq!(acme["is_dir"], true);
}
#[tokio::test]
async fn nonexistent_path_maps_to_not_found() {
let tmp = tempfile::tempdir().expect("tempdir");
let missing = tmp.path().join("no-such-dir");
let err = list_dir(json!({"path": missing.display().to_string()}), test_ctx())
.await
.expect_err("must fail");
assert_eq!(err.code, -32002);
assert_eq!(err.data, Some(json!({"error_type": "not_found"})));
}
#[tokio::test]
async fn file_path_maps_to_invalid_argument() {
let tmp = tempfile::tempdir().expect("tempdir");
let file = tmp.path().join("a.txt");
std::fs::write(&file, "x").expect("write");
let err = list_dir(json!({"path": file.display().to_string()}), test_ctx())
.await
.expect_err("must fail");
assert_eq!(err.code, -32003);
assert_eq!(err.data, Some(json!({"error_type": "invalid_argument"})));
}
#[test]
fn errors_are_distinguishable_by_code() {
let not_found = to_rpc_error(ListDirError::NotFound("/x".into()));
let not_dir = to_rpc_error(ListDirError::NotADirectory("/x".into()));
let denied = to_rpc_error(ListDirError::PermissionDenied("/x".into()));
let io = to_rpc_error(ListDirError::Io {
path: "/x".into(),
source: std::io::Error::other("boom"),
});
assert_eq!(not_found.code, -32002);
assert_eq!(not_dir.code, -32003);
assert_eq!(denied.code, -32001);
assert_eq!(io.code, -32603);
let codes = [not_found.code, not_dir.code, denied.code, io.code];
let mut unique = codes.to_vec();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), codes.len(), "every cause needs its own code");
}
#[tokio::test]
async fn wrong_typed_params_are_rejected() {
let err = list_dir(json!({"path": 42}), test_ctx())
.await
.expect_err("must fail");
assert_eq!(err.code, -32602);
}
#[tokio::test]
async fn register_wires_fs_list_dir() {
use trusty_mcp::Request;
let mut router = Router::new();
register(&mut router);
let tmp = tempfile::tempdir().expect("tempdir");
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "fs.list_dir".to_string(),
params: Some(json!({"path": tmp.path().display().to_string()})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"fs.list_dir must be registered, got {:?}",
resp.error
);
}
#[tokio::test]
async fn list_projects_returns_entries_array() {
let result = list_projects(Value::Null, test_ctx())
.await
.expect("fs.list_projects must not error");
assert!(result["entries"].is_array());
}
#[tokio::test]
async fn register_wires_fs_list_projects() {
use trusty_mcp::Request;
let mut router = Router::new();
register(&mut router);
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "fs.list_projects".to_string(),
params: None,
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"fs.list_projects must be registered, got {:?}",
resp.error
);
}
}