From dbf6de6d24d863181cdec3e09df3016145dca3ee Mon Sep 17 00:00:00 2001 From: GuoYu Date: Tue, 17 Nov 2026 00:41:16 +0800 Subject: [PATCH] feat(mcp): limit the query tools to a directory with scope (#3735) The query tools take an optional scope: a directory of the project or of one of its content roots (attached projects included). Results are limited to the files in it; paths narrows within it. search_text, search_regex and search_file walk only that directory; search_symbol, find_references, get_project_problems and get_all_open_file_paths keep results inside it; git_status uses the repository holding it; get_run_configurations and list_runs keep those whose working directory is inside it. Searching a directory of a content root walked it from the project root, so the project's exclusions met paths through the attachment's folder (an excluded '.*' hid every file of a worktree under .wt/). Such a directory is now searched from its content root, and the project-relative masks follow the root they search, so paths also reaches files of an attached project. This applies to Find in Files on a directory too. Co-authored-by: guoyucode <29471644+guoyucode@users.noreply.github.com> --- crates/ide-host/src/mcp/editors.rs | 12 ++- crates/ide-host/src/mcp/mod.rs | 1 + crates/ide-host/src/mcp/run/agent_tools.rs | 4 + crates/ide-host/src/mcp/run/configs.rs | 6 ++ crates/ide-host/src/mcp/scope.rs | 51 +++++++++++++ crates/ide-host/src/mcp/search.rs | 53 +++++++++---- crates/ide-host/src/mcp/symbols.rs | 9 ++- crates/ide-host/src/mcp/vcs.rs | 18 +++-- crates/ide-host/src/ops/search.rs | 74 +++++++++++++++--- crates/ide-host/tests/mcp.rs | 89 ++++++++++++++++++++++ docs/en/guide/mcp.mdx | 1 + docs/zh/guide/mcp.mdx | 1 + 12 files changed, 285 insertions(+), 34 deletions(-) create mode 100644 crates/ide-host/src/mcp/scope.rs diff --git a/crates/ide-host/src/mcp/editors.rs b/crates/ide-host/src/mcp/editors.rs index 7c2b4e635..5c811076d 100644 --- a/crates/ide-host/src/mcp/editors.rs +++ b/crates/ide-host/src/mcp/editors.rs @@ -1,4 +1,5 @@ use super::page::{OFFSET, Page}; +use super::scope::{self, Scope}; use super::tool::{Call, Output, Param, ParamType, Tool}; use ide_core::{Diagnostic, IdeResult, Severity}; use serde_json::{Map, Value, json}; @@ -14,7 +15,8 @@ pub fn tools() -> Vec { Use this tool to explore current open editors.", open_editors, - ), + ) + .param(scope::param()), Tool::new( "get_current_file", "Returns the focused editor's file and selection reported by the IDE. @@ -43,18 +45,20 @@ Lines and UTF-16 columns are 1-based.", project_problems, ) .param(Param::optional("errorsOnly", ParamType::Boolean, "Only errors (default) or warnings too")) + .param(scope::param()) .param(Param::optional("limit", ParamType::Integer, "Problems to return at most (default 100)")) .param(Param::optional("offset", ParamType::Integer, OFFSET)), ] } async fn open_editors(call: Call) -> IdeResult { + let dir = Scope::of(&call)?; let windows = call.host.mcp_windows(call.root()); let open = call.host.mcp_reports.editors(&windows); - let active = call.host.mcp_reports.focused(call.window()); + let active = call.host.mcp_reports.focused(call.window()).filter(|e| dir.contains(&e.path.0)); Output::json(json!({ "activeFilePath": active.map(|e| call.display(&e.path.0)), - "openFiles": open.iter().map(|p| call.display(p)).collect::>(), + "openFiles": open.iter().filter(|p| dir.contains(p)).map(|p| call.display(p)).collect::>(), })) } @@ -99,9 +103,11 @@ async fn file_problems(call: Call) -> IdeResult { async fn project_problems(call: Call) -> IdeResult { let page = Page::of(&call, PROBLEMS_LIMIT)?; let errors_only = call.flag("errorsOnly", true)?; + let dir = Scope::of(&call)?; let files = call.host.mcp_reports.problems(&call.host.mcp_windows(call.root())); let problems: Vec<(String, Value)> = files .into_iter() + .filter(|f| dir.contains(&f.path.0)) .flat_map(|f| { let path = call.display(&f.path.0); let wanted = f.items.into_iter().filter(|d| !errors_only || d.severity == Severity::Error); diff --git a/crates/ide-host/src/mcp/mod.rs b/crates/ide-host/src/mcp/mod.rs index c4254af79..9bde57677 100644 --- a/crates/ide-host/src/mcp/mod.rs +++ b/crates/ide-host/src/mcp/mod.rs @@ -10,6 +10,7 @@ mod files; mod http; mod page; mod reports; +mod scope; mod search; mod symbols; mod tool; diff --git a/crates/ide-host/src/mcp/run/agent_tools.rs b/crates/ide-host/src/mcp/run/agent_tools.rs index bad153bc7..25e136dd7 100644 --- a/crates/ide-host/src/mcp/run/agent_tools.rs +++ b/crates/ide-host/src/mcp/run/agent_tools.rs @@ -305,6 +305,7 @@ pub fn list_runs() -> Tool { start of the command, exit code and times. `get_run_status` gives a tab's whole status.", |call| async move { let page = Page::of(&call, LIST_LIMIT)?; + let dir = crate::mcp::scope::Scope::of(&call)?; let wanted = call.opt_str("state")?.filter(|s| s != "all"); let states = match wanted.as_deref() { None => None, @@ -325,6 +326,8 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole .iter() .rev() .map(|r| r.status()) + // A tab belongs where its command runs. + .filter(|s| dir.contains_shown(call.root(), s["workingDirectory"].as_str().unwrap_or_default())) .filter(|s| { states.as_ref().is_none_or(|states| s["state"].as_str().is_some_and(|v| states.contains(&v))) }) @@ -341,6 +344,7 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole ParamType::String, "all (default), running, idle (not running), error (failed, crashed, startFailed), or one state", )) + .param(crate::mcp::scope::param()) .param(Param::optional("limit", ParamType::Integer, "Tabs to return at most (default 10)")) .param(Param::optional("offset", ParamType::Integer, OFFSET)) } diff --git a/crates/ide-host/src/mcp/run/configs.rs b/crates/ide-host/src/mcp/run/configs.rs index c81693f0f..c4fcc6cbf 100644 --- a/crates/ide-host/src/mcp/run/configs.rs +++ b/crates/ide-host/src/mcp/run/configs.rs @@ -139,8 +139,13 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a } let page = Page::of(&call, CONFIGURATIONS_LIMIT)?; let query = call.opt_str("query")?.map(|q| q.to_lowercase()); + let dir = crate::mcp::scope::Scope::of(&call)?; let list: Vec = configs .iter() + // A configuration belongs where it runs. + .filter(|c| { + dir.contains(&c.cwd.as_deref().map_or_else(|| call.root().to_path_buf(), |d| call.root().join(d))) + }) .filter(|c| { query.as_ref().is_none_or(|q| { [c.name.as_str(), c.kind.as_str(), command_line(c).as_str()] @@ -164,6 +169,7 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a in the file instead of project-wide run configurations.", )) .param(Param::optional("query", ParamType::String, "Only configurations whose name, type or command contains it")) + .param(crate::mcp::scope::param()) .param(Param::optional("limit", ParamType::Integer, "Configurations to return at most (default 100)")) .param(Param::optional("offset", ParamType::Integer, OFFSET)) } diff --git a/crates/ide-host/src/mcp/scope.rs b/crates/ide-host/src/mcp/scope.rs new file mode 100644 index 000000000..9a6bee5a5 --- /dev/null +++ b/crates/ide-host/src/mcp/scope.rs @@ -0,0 +1,51 @@ +//! The `scope` argument of the query tools: the directory their results are limited to, a +//! folder of the project or a project attached to it. + +use crate::mcp::tool::{Call, Param, ParamType}; +use ide_core::{IdeError, IdeResult}; +use std::path::{Path, PathBuf}; + +pub fn param() -> Param { + Param::optional( + "scope", + ParamType::String, + "Directory to limit results to: relative to the project root, or absolute", + ) +} + +/// No `scope`: everything. +pub struct Scope(Option); + +impl Scope { + pub fn of(call: &Call) -> IdeResult { + let Some(raw) = call.opt_str("scope")?.filter(|s| !s.trim().is_empty()) else { return Ok(Self(None)) }; + let given = Path::new(raw.trim()); + let path = crate::mcp::tool::normalize(&if given.is_absolute() { + given.to_path_buf() + } else { + call.root().join(given) + }); + let path = dunce::canonicalize(&path).unwrap_or(path); + if !path.is_dir() { + return Err(IdeError::not_found(format!("scope {raw} is not a directory"))); + } + let roots = std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots()); + if !roots.into_iter().any(|root| path.starts_with(root)) { + return Err(IdeError::invalid(format!("scope {raw} is outside the project"))); + } + Ok(Self(Some(path))) + } + + pub fn dir(&self) -> Option<&Path> { + self.0.as_deref() + } + + pub fn contains(&self, path: &Path) -> bool { + self.0.as_ref().is_none_or(|dir| path.starts_with(dir)) + } + + /// For a path the tools return: project-relative with `/`, or absolute. + pub fn contains_shown(&self, root: &Path, path: &str) -> bool { + self.0.is_none() || self.contains(&root.join(path)) + } +} diff --git a/crates/ide-host/src/mcp/search.rs b/crates/ide-host/src/mcp/search.rs index 61b4575b6..9d585b26c 100644 --- a/crates/ide-host/src/mcp/search.rs +++ b/crates/ide-host/src/mcp/search.rs @@ -6,6 +6,7 @@ //! the editor (one per character except emoji and other astral characters). use crate::mcp::page::{OFFSET, Page}; +use crate::mcp::scope::{self, Scope}; use crate::mcp::tool::{Call, Output, Param, ParamType, Tool}; use crate::mcp::util::{INDEXING_PARTIAL_RESULT_REASON, MEDIUM_TIMEOUT}; use crate::ops::search::SearchEvent; @@ -67,6 +68,7 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].", |call| async move { text_search(call, false).await }, ) .param(Param::required("q", ParamType::String, "Text to search for")) + .param(scope::param()) .param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION)) .param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION)) .param(Param::optional("offset", ParamType::Integer, OFFSET)) @@ -89,6 +91,7 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].", |call| async move { text_search(call, true).await }, ) .param(Param::required("q", ParamType::String, "Regex pattern to search for")) + .param(scope::param()) .param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION)) .param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION)) .param(Param::optional("offset", ParamType::Integer, OFFSET)) @@ -110,6 +113,7 @@ If you don't find a suitable result, try again with include_external=true to sea |call| async move { symbol_search(call).await }, ) .param(Param::required("q", ParamType::String, "Symbol query text")) + .param(scope::param()) .param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION)) .param(Param::optional( "include_external", @@ -136,6 +140,7 @@ Paths are optional additional glob filters relative to the project root.", |call| async move { file_search(call).await }, ) .param(Param::required("q", ParamType::String, "Glob pattern to search for")) + .param(scope::param()) .param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION)) .param(Param::optional( "includeExcluded", @@ -539,6 +544,7 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult { let pattern = query(&call, if is_regex { "Regex pattern is empty" } else { "Search text is empty" })?; let (page, limit) = page(&call, DEFAULT_LIMIT)?; let around = context(&call)?; + let dir = Scope::of(&call)?; let scope = PathScope::new(call.root(), &call.str_list("paths")?)?; // Globs Find in Files cannot take are applied afterwards, so the engine must not // stop at `limit` matches the filter may drop. @@ -559,7 +565,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult { whole_word: false, include, exclude, - scope: SearchScope::Project, + // Only `scope` is walked. + scope: dir.dir().map_or(SearchScope::Project, |d| SearchScope::Directory { path: d.to_path_buf().into() }), max_matches, context: Default::default(), }; @@ -568,8 +575,12 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult { } let (files, summary, timed_out) = run_search(&call, query.clone()).await?; // Content roots outside the project are reported by absolute path. - let mut files: Vec<(String, FileMatches)> = - files.into_iter().map(|f| (call.display(&f.path.0), f)).filter(|(path, _)| scope.matches(path)).collect(); + let mut files: Vec<(String, FileMatches)> = files + .into_iter() + .filter(|f| dir.contains(&f.path.0)) + .map(|f| (call.display(&f.path.0), f)) + .filter(|(path, _)| scope.matches(path)) + .collect(); files.sort_by(|a, b| a.0.cmp(&b.0)); // Only these can match a line break. let may_span = is_regex || pattern.contains('\n'); @@ -739,6 +750,7 @@ async fn run_search(call: &Call, query: SearchQuery) -> IdeResult<(Vec IdeResult { let q = query(&call, "Glob pattern is empty")?; let (page, limit) = page(&call, DEFAULT_LIMIT)?; + let dir = Scope::of(&call)?; let scope = PathScope::new(call.root(), &call.str_list("paths")?)?; let include_excluded = call.flag("includeExcluded", false)?; let glob = GlobSetBuilder::new() @@ -748,16 +760,19 @@ async fn file_search(call: Call) -> IdeResult { // Ignored names and "Exclude files" patterns, which `read_dir` does not flag. let excludes = if include_excluded { None } else { Some(FileMask::new(&[], &call.project().search_excludes())?) }; let root = call.root().to_path_buf(); - // The project folder and the content roots its walk does not cover: those outside it and - // those inside it that it skips as ignored. - let roots: Vec = std::iter::once(root.clone()) - .chain( - call.project() - .content_roots() - .into_iter() - .filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r)), - ) - .collect(); + // `scope`, or the project folder and the content roots its walk does not cover: those + // outside it and those inside it that it skips as ignored. + let roots: Vec = match dir.dir() { + Some(dir) => vec![dir.to_path_buf()], + None => std::iter::once(root.clone()) + .chain( + call.project() + .content_roots() + .into_iter() + .filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r)), + ) + .collect(), + }; let host = call.host(); let walk = Walk { host: host.clone(), @@ -862,12 +877,17 @@ async fn symbol_search(call: Call) -> IdeResult { let q = query(&call, "Search query is empty")?; let (page, limit) = page(&call, SYMBOL_SEARCH_DEFAULT_LIMIT)?; let around = context(&call)?; + let dir = Scope::of(&call)?; let scope = PathScope::new(call.root(), &call.str_list("paths")?)?; let external = call.flag("include_external", false)?; let host = call.host(); let project = call.project().clone(); let indexing_before = project.index.status().indexing; - let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) }; + let pool = if scope.is_all() && dir.dir().is_none() { + limit + 1 + } else { + ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) + }; let found = { let (project, q) = (project.clone(), q.clone()); host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await? @@ -876,6 +896,7 @@ async fn symbol_search(call: Call) -> IdeResult { .into_iter() // By the path the other tools give: the index shows a root outside the project by its // folder name, which is no path to read. + .filter(|s| dir.contains(&s.path.0)) .map(|s| (call.display(&s.path.0), s)) .filter(|(path, _)| scope.matches(path)) .map(|(path, s)| SearchItem { @@ -891,9 +912,9 @@ async fn symbol_search(call: Call) -> IdeResult { timed_out = out_of_time; for (name, container, location) in symbols { let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path)); - // Project files obey `paths`; library symbols are what was asked for. + // Project files obey `scope` and `paths`; library symbols are what was asked for. let inside = location.uri.is_none() && !Path::new(&path).is_absolute(); - if inside && !scope.matches(&path) { + if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) { continue; } let item = SearchItem { diff --git a/crates/ide-host/src/mcp/symbols.rs b/crates/ide-host/src/mcp/symbols.rs index 156d082d8..98bf22f78 100644 --- a/crates/ide-host/src/mcp/symbols.rs +++ b/crates/ide-host/src/mcp/symbols.rs @@ -211,6 +211,7 @@ pub fn find_references() -> Tool { Tool::new("find_references", "Find references using the language service and the IDE's project index. Positions are 1-based UTF-16. Reports incomplete results when analysis is still running.", |call| async move { let path = call.resolve_readable(&call.str("filePath")?).await?; let page = super::page::Page::of(&call, REFERENCES_LIMIT)?; + let dir = super::scope::Scope::of(&call)?; let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?; let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?; let project = call.project.clone(); @@ -248,7 +249,12 @@ pub fn find_references() -> Tool { // `classified`, when there, goes with `locations` one to one. if let serde_json::Value::Object(map) = &mut value { let mut list = |key: &str| match map.remove(key) { Some(serde_json::Value::Array(items)) => items, _ => Vec::new() }; - let (locations, classified) = (list("locations"), list("classified")); + let (mut locations, mut classified) = (list("locations"), list("classified")); + if dir.dir().is_some() { + let inside = |l: &serde_json::Value| l["path"].as_str().is_some_and(|p| dir.contains(std::path::Path::new(p))); + locations.retain(inside); + classified.retain(|c| inside(&c["location"])); + } let classified = page.take(classified, &mut serde_json::Map::new()); let locations = page.take(locations, map); map.insert("locations".into(), locations.into()); @@ -260,6 +266,7 @@ pub fn find_references() -> Tool { .param(Param::required("line", ParamType::Integer, "1-based line")) .param(Param::required("column", ParamType::Integer, "1-based UTF-16 column")) .param(Param::optional("includeDeclaration", ParamType::Boolean, "Include declarations (default true)")) + .param(super::scope::param()) .param(Param::optional("limit", ParamType::Integer, "References to return at most (default 100)")) .param(Param::optional("offset", ParamType::Integer, super::page::OFFSET)) } diff --git a/crates/ide-host/src/mcp/vcs.rs b/crates/ide-host/src/mcp/vcs.rs index dceb8b7ab..328590ee6 100644 --- a/crates/ide-host/src/mcp/vcs.rs +++ b/crates/ide-host/src/mcp/vcs.rs @@ -266,11 +266,16 @@ By default all Git repositories are returned.", .map(|r| (r.root.into_path_buf(), r.head)) .collect(); let wanted = call.opt_str("repositoryPathRelativeToProject")?; + let scope = super::scope::Scope::of(&call)?; let git = git_executable(&call); - let mut roots: Vec<(PathBuf, Option)> = match &wanted { + // A repository asked for, or the one holding `scope`. + let target = match &wanted { + Some(wanted) => Some(call.resolve_inside(wanted)?), + None => scope.dir().map(Path::to_path_buf), + }; + let mut roots: Vec<(PathBuf, Option)> = match target { None => repos, - Some(wanted) => { - let path = call.resolve_inside(wanted)?; + Some(path) => { // The innermost repository containing the path. match innermost_repo(repos, &path) { Some(repo) => vec![repo], @@ -282,7 +287,8 @@ By default all Git repositories are returned.", vec![(root, branch)] } None => { - return Err(IdeError::not_found(format!("No git repository found for path: {wanted}"))); + let shown = wanted.unwrap_or_else(|| call.display(&path)); + return Err(IdeError::not_found(format!("No git repository found for path: {shown}"))); } }, } @@ -293,12 +299,13 @@ By default all Git repositories are returned.", for (root, branch) in roots { let rel = relative_to_project(&call, &root); let (git, dir) = (git.clone(), root.clone()); - let entries = host + let mut entries = host .blocking(move || read_status(&git, &dir, include_untracked, include_ignored)) .await .map_err(|e| { IdeError::internal(format!("Failed to get git status for repository '{rel}': {}", e.message)) })?; + entries.retain(|e| scope.contains(&root.join(e.path.trim_end_matches('/')))); let count = |f: fn(&StatusEntry) -> bool| entries.iter().filter(|e| f(e)).count(); let listed: Vec = entries .iter() @@ -345,6 +352,7 @@ By default all Git repositories are returned.", )) .param(Param::optional("includeUntracked", ParamType::Boolean, "Whether to include untracked files")) .param(Param::optional("includeIgnored", ParamType::Boolean, "Whether to include ignored files")) + .param(super::scope::param()) .param(Param::optional("limit", ParamType::Integer, "Entries to return per repository at most (default 100)")) .param(Param::optional("offset", ParamType::Integer, OFFSET)) } diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index dea10a998..02a8c58ed 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -62,13 +62,25 @@ pub(crate) fn search_project( _ => None, }; let workspace = ide_workspace::workspace::Workspace::load(root)?.is_some_and(|w| w.is_container(root)); - let include_root = !workspace - || matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. }); + // A directory inside a content root is searched from that root, so that the project's + // exclusions (a `.*` name) meet the paths there as in a whole-project search. + let within = match &query.scope { + ide_search::SearchScope::Directory { path } => { + project.content_roots().into_iter().filter(|r| path.0.starts_with(r)).max_by_key(|r| r.components().count()) + } + _ => None, + }; + let include_root = within.is_none() + && (!workspace + || matches!( + query.scope, + ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. } + )); let content_roots = match query.scope { ide_search::SearchScope::Project | ide_search::SearchScope::FileSet { .. } | ide_search::SearchScope::Pattern { .. } => project.content_roots(), - _ => Vec::new(), + _ => within.into_iter().collect(), }; let filter = |rel: &str| match set { Some(ProjectFileSet::Production) => !roots.is_test(rel), @@ -84,6 +96,19 @@ pub(crate) fn search_project( let mut total = SearchSummary::default(); for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) { let mut remaining = query.clone(); + // A root inside the project (one its walk skips) goes by its path there. + let prefix = (dir != root).then(|| match dir.strip_prefix(root) { + Ok(rel) if !workspace => rel.to_string_lossy().replace('\\', "/"), + _ => dir.file_name().unwrap_or_default().to_string_lossy().into_owned(), + }); + if let Some(prefix) = &prefix { + remaining.include = rebase_masks(&query.include, prefix); + remaining.exclude = rebase_masks(&query.exclude, prefix); + // Only paths elsewhere were asked for. + if remaining.include.is_empty() && !query.include.is_empty() { + continue; + } + } let max = if query.max_matches == 0 { 10_000 } else { query.max_matches }; remaining.max_matches = max.saturating_sub(total.matches).max(1); let summary = ide_search::search_in_context( @@ -94,12 +119,7 @@ pub(crate) fn search_project( ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode }, cancel, &|mut file| { - if dir != root { - // A root inside the project (one its walk skips) goes by its path there. - let prefix = match dir.strip_prefix(root) { - Ok(rel) if include_root => rel.to_string_lossy().replace('\\', "/"), - _ => dir.file_name().unwrap_or_default().to_string_lossy().into_owned(), - }; + if let Some(prefix) = &prefix { file.rel_path = format!("{prefix}/{}", file.rel_path); } emit(file); @@ -117,5 +137,41 @@ pub(crate) fn search_project( Ok(total) } +/// Project-relative `masks` (each a comma-separated list) for a search from the content root +/// shown as `prefix`: paths below it lose the prefix, other paths can match nothing there and +/// are dropped, names and `**/` patterns (`*.rs`, `**/build/**`) stay as they are. +fn rebase_masks(masks: &[String], prefix: &str) -> Vec { + let prefix = format!("{}/", prefix.trim_end_matches('/')); + masks + .iter() + .filter_map(|group| { + let kept: Vec = group + .split(',') + .map(str::trim) + .filter(|m| !m.is_empty()) + .filter_map(|mask| { + let (negated, body) = mask.strip_prefix('!').map_or(("", mask), |b| ("!", b.trim())); + let body = body.trim_start_matches("./").trim_start_matches('/'); + if !body.contains('/') || body.starts_with("**/") { + return Some(mask.to_owned()); + } + body.strip_prefix(&prefix).map(|rest| format!("{negated}{rest}")) + }) + .collect(); + (!kept.is_empty()).then(|| kept.join(",")) + }) + .collect() +} + +#[cfg(test)] +mod tests { + #[test] + fn masks_follow_the_root_they_search() { + let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()]; + assert_eq!(super::rebase_masks(&masks, ".wt/a"), ["src/**", "*.rs", "!out/**", "**/build/**"]); + assert_eq!(super::rebase_masks(&["src/**".into()], ".wt/a"), Vec::::new()); + } +} + mod commands; pub use commands::*; diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/mcp.rs index 0cf75872d..98d68a2c2 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/mcp.rs @@ -441,6 +441,95 @@ async fn git_status_and_diff_on_a_temporary_repository() { assert!(!h.tmp.path().join("executed").exists()); } +#[tokio::test(flavor = "multi_thread")] +async fn scope_limits_the_query_tools_to_a_directory() { + let h = Harness::new(); + std::fs::create_dir_all(h.root.join("lib")).unwrap(); + std::fs::write(h.root.join("lib/c.txt"), "needle\n").unwrap(); + let paths = |v: &Value| -> Vec { + let mut out: Vec = + v["items"].as_array().unwrap().iter().map(|i| i["filePath"].as_str().unwrap().to_owned()).collect(); + out.dedup(); + out + }; + assert_eq!(paths(&h.json("search_text", json!({"q":"needle","scope":"lib"})).await), ["lib/c.txt"]); + assert_eq!(paths(&h.json("search_regex", json!({"q":"need.e","scope":"lib/"})).await), ["lib/c.txt"]); + let absolute = h.root.join("src").to_string_lossy().into_owned(); + assert_eq!(paths(&h.json("search_file", json!({"q":"*.txt","scope":absolute})).await), ["src/a.txt", "src/b.txt"]); + // Within the scope, `paths` narrows further. + assert_eq!( + paths(&h.json("search_text", json!({"q":"needle","scope":"src","paths":["**/b.txt"]})).await), + ["src/b.txt"] + ); + assert!(h.error("search_text", json!({"q":"needle","scope":"missing"})).await.contains("is not a directory")); + assert!(h.error("search_text", json!({"q":"needle","scope":".."})).await.contains("outside the project")); + + let git = |args: &[&str]| { + let output = std::process::Command::new("git").current_dir(&h.root).args(args).output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + }; + git(&["init"]); + git(&["add", "."]); + git(&["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "Initial"]); + std::fs::write(h.root.join("src/a.txt"), "changed\n").unwrap(); + std::fs::write(h.root.join("lib/c.txt"), "changed\n").unwrap(); + let status = h.json("git_status", json!({"scope":"lib"})).await; + assert_eq!(status["repositories"].as_array().unwrap().len(), 1); + assert_eq!( + status["repositories"][0]["entries"], + json!([{"pathRelativeToRepository":"lib/c.txt","indexStatus":" ","workTreeStatus":"M"}]) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn scope_reaches_an_attached_worktree_the_repository_ignores() { + let h = Harness::new(); + h.trust().await; + let git = |dir: &Path, args: &[&str]| { + let output = std::process::Command::new("git").current_dir(dir).args(args).output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + }; + git(&h.root, &["init"]); + git(&h.root, &["add", "."]); + git(&h.root, &["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "Initial"]); + std::fs::write(h.root.join(".git/info/exclude"), "/.wt/\n").unwrap(); + git(&h.root, &["worktree", "add", "-q", ".wt/feature"]); + let worktree = h.root.join(".wt/feature"); + h.host.trust.decide(&worktree, true, false).unwrap(); + ide_host::ops::project::attach_workspace(&h.host, "main", &worktree).unwrap(); + // Hidden folders excluded by name: `.wt` is one, the worktree's own files are not. + ide_host::ops::project::set_settings( + &h.host, + "main", + ide_workspace::settings::SettingsScope::Project, + "projectStructure.excludeFiles", + "\".*\"", + ) + .unwrap(); + let found = |args: Value| { + let h = &h; + async move { + let v = h.json("search_text", args).await; + let mut out: Vec = v["items"] + .as_array() + .cloned() + .unwrap_or_default() + .iter() + .map(|i| i["filePath"].as_str().unwrap().to_owned()) + .collect(); + out.dedup(); + out + } + }; + let everywhere = found(json!({"q":"needle"})).await; + assert!(everywhere.contains(&".wt/feature/src/b.txt".to_owned()), "{everywhere:?}"); + assert_eq!( + found(json!({"q":"needle","scope":".wt/feature/src"})).await, + [".wt/feature/src/a.txt", ".wt/feature/src/b.txt"] + ); + assert_eq!(found(json!({"q":"needle","paths":[".wt/feature/src/b.txt"]})).await, [".wt/feature/src/b.txt"]); +} + #[cfg(unix)] #[tokio::test(flavor = "multi_thread")] async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() { diff --git a/docs/en/guide/mcp.mdx b/docs/en/guide/mcp.mdx index 37863a2ee..a5c3ba4af 100644 --- a/docs/en/guide/mcp.mdx +++ b/docs/en/guide/mcp.mdx @@ -100,6 +100,7 @@ Notes on what they do: - `read_file` also reads sources of dependencies and files inside jar and zip archives. - The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false. +- The query tools (the searches, `find_references`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module. - `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows. - `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis. - `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed. diff --git a/docs/zh/guide/mcp.mdx b/docs/zh/guide/mcp.mdx index 73fb107b1..3a38d48f6 100644 --- a/docs/zh/guide/mcp.mdx +++ b/docs/zh/guide/mcp.mdx @@ -100,6 +100,7 @@ stdio 配置大致如下(路径以你机器上的为准): - `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。 - `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。 - 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。 +- 查询类工具(各搜索工具、`find_references`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。 - `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。 - `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。 - `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。