use std::{
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
#[expect(deprecated)]
use rmcp::model::Root;
#[derive(Clone, Debug, Default)]
pub(crate) struct McpRoots {
roots: Arc<RwLock<Vec<McpRoot>>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct McpRoot {
path: PathBuf,
name: String,
}
impl McpRoots {
pub(crate) fn for_workspace(workspace: &Path) -> Self {
let roots = match root_name(workspace) {
Some(name) => vec![McpRoot {
path: workspace.to_path_buf(),
name,
}],
None => Vec::new(),
};
Self {
roots: Arc::new(RwLock::new(roots)),
}
}
#[expect(deprecated)]
pub(crate) fn to_protocol(&self) -> Vec<Root> {
self.read()
.iter()
.filter_map(|root| {
let uri = file_uri(&root.path)?;
Some(Root::new(uri).with_name(root.name.clone()))
})
.collect()
}
pub(crate) fn is_empty(&self) -> bool {
self.read().is_empty()
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, Vec<McpRoot>> {
self.roots.read().unwrap_or_else(|error| error.into_inner())
}
}
fn root_name(path: &Path) -> Option<String> {
file_uri(path)?;
Some(
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("workspace")
.to_string(),
)
}
fn file_uri(path: &Path) -> Option<String> {
url::Url::from_directory_path(path)
.ok()
.map(|url| url.to_string())
}
#[cfg(test)]
#[path = "roots_tests.rs"]
mod tests;