use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use rmcp::model::Tool;
use scryer_db::{DependencyPackage, Scope, SourceFile, Symbol, SymbolReference};
use scryer_engine::{
EngineService, ResolvedDefinition, find_symbol_for_target, reference_target_at,
};
use super::admin::{make_tool, read_only};
use super::dependency::{
TYPE_KINDS, crate_root, follow_import, import_path, imports_symbol, last_segment,
lookup_symbol_candidates, narrow_by_file,
};
use super::inspect::cut_docstring;
use crate::context::ProjectContextResolver;
// --- Input & Output Types ---
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct ResolveDefinitionParams {
/// Relative or absolute path of the file containing the reference.
pub file_path: String,
/// 1-based line number.
pub line: u32,
/// 0-based column index.
pub col: u32,
/// Custom token budget for this response.
pub max_tokens: Option<usize>,
/// If true, bypasses token budget truncation.
pub no_truncate: Option<bool>,
/// Optional project slug or ID override.
pub project: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ResolvedDefinitionResult {
pub found: bool,
pub symbol_name: Option<String>,
pub file_path: Option<String>,
pub start_line: Option<u32>,
pub end_line: Option<u32>,
pub signature: Option<String>,
/// First 3 lines (400 chars) unless `max_tokens` or `no_truncate` is set.
pub docstring: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub docstring_truncated: bool,
pub is_external: Option<bool>,
pub crate_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notice: Option<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct FindReferencesParams {
/// Symbol name or qualified identifier to locate.
pub symbol: String,
/// Optional file path to scope the reference lookup.
pub file_path: Option<String>,
/// Substring filter for referenced file paths.
pub file_filter: Option<String>,
/// Keep only references of this kind: call, type_annotation, import, reexport, read or write.
pub role: Option<super::enums::ReferenceRole>,
/// Where to look: project (default), workspace_all, file (needs file_path) or dependencies (workspace usages of external crate symbols and their re-exports).
pub scope_level: Option<super::enums::ScopeLevel>,
/// Zero-based offset for paginating references.
pub offset: Option<usize>,
/// Maximum number of references to return. Defaults to returning all within token budget.
pub limit: Option<usize>,
/// Custom token budget for this response.
pub max_tokens: Option<usize>,
/// If true, bypasses the token budget cap and returns full results.
pub no_truncate: Option<bool>,
/// Optional project slug or ID override.
pub project: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ReferenceItem {
pub file_path: String,
pub line_number: u32,
pub role: String,
pub start_byte: usize,
pub end_byte: usize,
/// Qualified name of the function, method or type that contains this reference, so a
/// caller list needs no follow-up lookup per site.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enclosing_symbol: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FindReferencesResult {
pub symbol: String,
pub total_references: usize,
pub returned_references: usize,
pub offset: usize,
pub limit: Option<usize>,
pub has_more: bool,
pub references: Vec<ReferenceItem>,
/// Why the result is empty, when it is.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct GetEnclosingScopeParams {
/// Relative or absolute path of the source file.
pub file_path: String,
/// 1-based line number to inspect.
pub line: u32,
/// Custom token budget for this response.
pub max_tokens: Option<usize>,
/// If true, bypasses token budget truncation.
pub no_truncate: Option<bool>,
/// Optional project slug or ID override.
pub project: Option<String>,
}
/// The innermost lexical scope (block, closure, function body, ...) at a line.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LexicalScope {
pub scope_kind: String,
pub start_line: u32,
pub end_line: u32,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct EnclosingScopeResult {
pub found: bool,
pub file_path: String,
/// Name of the smallest named symbol (function, method, type, module, ...) containing the line.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub qualified_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
/// Line span of the enclosing named symbol.
#[serde(skip_serializing_if = "Option::is_none")]
pub start_line: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_line: Option<u32>,
/// The innermost lexical scope at the line, which may be an unnamed block or closure
/// inside the named symbol.
#[serde(skip_serializing_if = "Option::is_none")]
pub innermost_scope: Option<LexicalScope>,
/// Why nothing was found, when nothing was.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct GetFileOutlineParams {
/// Source file path to generate outline for.
pub file_path: String,
/// Optional search query to filter symbols by name or qualified name (case-insensitive substring).
pub query: Option<String>,
/// Optional symbol kinds to keep. Indexed kinds: "fn", "struct", "enum", "trait", "type", "mod", "const", "reexport" (Rust); "class", "method", "interface" (Python/TypeScript). Common names are accepted as aliases ("function"/"method" → fn, "class" ↔ struct, "interface" ↔ trait, "module" → mod, "import"/"use" → reexport).
pub kinds: Option<Vec<String>>,
/// Optional start line to scope symbols within a file region.
pub start_line: Option<u32>,
/// Optional end line to scope symbols within a file region.
pub end_line: Option<u32>,
/// Zero-based offset for paginating symbols.
pub offset: Option<usize>,
/// Maximum number of symbols to return. Defaults to returning all within token budget.
pub limit: Option<usize>,
/// If true, omits docstrings to minimize token usage.
pub compact: Option<bool>,
/// Custom token budget for this response.
pub max_tokens: Option<usize>,
/// If true, bypasses the token budget cap and returns full outline.
pub no_truncate: Option<bool>,
/// Optional project slug or ID override.
pub project: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OutlineSymbol {
pub name: String,
pub qualified_name: String,
pub kind: String,
pub visibility: String,
pub signature: String,
pub start_line: u32,
pub end_line: u32,
pub docstring: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FileOutlineResult {
pub file_path: String,
pub total_symbols: usize,
pub returned_symbols: usize,
pub offset: usize,
pub limit: Option<usize>,
pub has_more: bool,
pub symbols: Vec<OutlineSymbol>,
/// Hints when filters matched nothing (e.g. the kinds present in the file).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct GetTypeContractParams {
/// Name of the struct, enum, trait, or type alias.
pub type_name: String,
/// Optional file path hint.
pub file_path: Option<String>,
/// Optional substring to filter struct fields, enum variants, or methods.
pub member_query: Option<String>,
/// Custom token budget for this response.
pub max_tokens: Option<usize>,
/// If true, bypasses token budget truncation.
pub no_truncate: Option<bool>,
/// Optional project slug or ID override.
pub project: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TypeContractResult {
pub found: bool,
pub type_name: String,
pub kind: Option<String>,
pub signature: Option<String>,
pub file_path: Option<String>,
/// Listed before the docstring so a long docstring can't push members past the budget.
pub members: Vec<String>,
/// First 3 lines (400 chars) unless `max_tokens` or `no_truncate` is set.
pub docstring: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub docstring_truncated: bool,
/// Why nothing was found, when nothing was.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
// --- Handlers ---
pub async fn handle_resolve_definition(
context: &ProjectContextResolver,
engine: &EngineService,
params: ResolveDefinitionParams,
) -> anyhow::Result<ResolvedDefinitionResult> {
let full_doc = params.max_tokens.is_some() || params.no_truncate.unwrap_or(false);
let mut res = resolve_definition_full(context, engine, params).await?;
(res.docstring, res.docstring_truncated) = response_docstring(res.docstring, full_doc);
Ok(res)
}
/// Docstring for a response: dependency docstrings can run to ~1,000 tokens on one line,
/// which the line-based budget would cut together with every field after it, so keep the
/// first 3 lines unless the caller lifted the budget (`full`).
fn response_docstring(doc: Option<String>, full: bool) -> (Option<String>, bool) {
match doc {
Some(doc) if !full => {
let (cut, truncated) = cut_docstring(&doc);
(Some(cut), truncated)
}
other => (other, false),
}
}
async fn resolve_definition_full(
context: &ProjectContextResolver,
engine: &EngineService,
params: ResolveDefinitionParams,
) -> anyhow::Result<ResolvedDefinitionResult> {
anyhow::ensure!(
params.line >= 1,
"`line` is 1-based (the first line is 1); `col` is 0-based"
);
let path = PathBuf::from(¶ms.file_path);
let (project, rel_path) = context
.resolve_project(Some(&path), params.project.as_deref())
.await?;
// A path no project contains is only usable if it is relative to the project root and
// stays inside it; never read an arbitrary absolute or `..` path.
let rel = match rel_path {
Some(rel) => rel,
None => {
if path.is_absolute()
|| path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
anyhow::bail!(
"file_path '{}' is outside project '{}'",
params.file_path,
project.slug
);
}
path
}
};
let root = Path::new(&project.root_path);
// Name the symbol under the cursor; nothing to resolve if it isn't an identifier.
let content = std::fs::read_to_string(root.join(&rel)).unwrap_or_default();
let Some(target) = reference_target_at(&rel, &content, params.line, params.col) else {
let reason = if content.is_empty() {
format!(
"could not read '{}' in project '{}'; check file_path",
rel.display(),
project.slug
)
} else {
format!(
"no identifier at line {}, col {} (line is 1-based, col is 0-based); point at the name of the reference, e.g. use get_file_outline or find_references to locate it",
params.line, params.col
)
};
return Ok(ResolvedDefinitionResult::not_found_because(reason));
};
// 1. Try engine stack-graph resolution for bare identifiers. Its rules only bind
// names globally, so path-qualified references go straight to the index lookup.
if !target.contains("::")
&& let Ok(Some(resolved)) = engine
.resolve_definition(project.id, root, &rel, params.line, params.col)
.await
{
let file_path = resolved.file_path.to_string_lossy().to_string();
let target_project_id = if resolved.is_external { 0 } else { project.id };
let indexed = {
let mut guard = engine.db().lock().await;
symbol_at(&mut guard, target_project_id, &file_path, &resolved).await?
};
let notice = if resolved.is_external && !Path::new(&file_path).exists() {
Some("Source file not found on disk; signature returned from index.".to_string())
} else {
None
};
return Ok(ResolvedDefinitionResult {
found: true,
symbol_name: Some(resolved.symbol_name),
file_path: Some(file_path),
start_line: Some(
indexed
.as_ref()
.map_or(resolved.start_line, |s| s.start_line),
),
end_line: Some(indexed.as_ref().map_or(resolved.end_line, |s| s.end_line)),
signature: indexed
.as_ref()
.map(|s| s.signature.clone())
.or(resolved.syntax_type),
docstring: indexed.and_then(|s| s.docstring),
docstring_truncated: false,
is_external: Some(resolved.is_external),
crate_name: resolved.crate_name,
notice,
});
}
// 2. Fall back to the index: match the target name against project symbols,
// preferring definitions in the current file.
let mut guard = engine.db().lock().await;
let rel_str = rel.to_string_lossy().to_string();
let current_file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(project.id)
.and(SourceFile::fields().path().eq(rel_str)),
)
.first()
.exec(&mut *guard)
.await?;
let symbol =
find_symbol_for_target(&mut *guard, project.id, &target, current_file.map(|f| f.id))
.await?;
let Some(mut sym) = symbol else {
return Ok(ResolvedDefinitionResult::not_found_because(format!(
"'{target}' is an identifier but matches no indexed definition; try search_symbols(query: \"{target}\"), or index_workspace if the code is new"
)));
};
// A file's `use` stub shares the imported item's name and wins the name lookup; jump
// through it to the definition it imports.
if sym.kind == "reexport"
&& let Some(def) = follow_import(&mut guard, &project, &sym).await?
{
sym = def;
}
let file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(sym.project_id)
.and(SourceFile::fields().id().eq(sym.file_id)),
)
.first()
.exec(&mut *guard)
.await?;
let is_external = sym.project_id == 0;
// Dependency files are stored relative to their package root, so report the absolute
// path into the Cargo cache and the package's crate name.
let package = match sym.dependency_package_id {
Some(pkg_id) if is_external => {
DependencyPackage::filter(DependencyPackage::fields().id().eq(pkg_id))
.first()
.exec(&mut *guard)
.await?
}
_ => None,
};
let crate_name = package.as_ref().map(|p| p.name.clone());
let res_file_path = file.map(|f| match &package {
Some(pkg) => Path::new(&pkg.root_path)
.join(&f.path)
.to_string_lossy()
.into_owned(),
None => f.path,
});
let notice = if is_external
&& res_file_path
.as_ref()
.map(|p| !Path::new(p).exists())
.unwrap_or(true)
{
Some("Source file not found on disk; signature returned from index.".to_string())
} else {
None
};
Ok(ResolvedDefinitionResult {
found: true,
symbol_name: Some(sym.name),
file_path: res_file_path,
start_line: Some(sym.start_line),
end_line: Some(sym.end_line),
signature: Some(sym.signature),
docstring: sym.docstring,
docstring_truncated: false,
is_external: Some(is_external),
crate_name,
notice,
})
}
impl ResolvedDefinitionResult {
fn not_found_because(reason: String) -> Self {
Self {
notice: Some(reason),
..Self::not_found()
}
}
fn not_found() -> Self {
Self {
found: false,
symbol_name: None,
file_path: None,
start_line: None,
end_line: None,
signature: None,
docstring: None,
docstring_truncated: false,
is_external: None,
crate_name: None,
notice: None,
}
}
}
/// The indexed symbol declared at a stack-graph definition site, if any.
async fn symbol_at(
db: &mut toasty::Db,
project_id: u64,
file_path: &str,
def: &ResolvedDefinition,
) -> anyhow::Result<Option<Symbol>> {
let mut file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(project_id)
.and(SourceFile::fields().path().eq(file_path)),
)
.first()
.exec(&mut *db)
.await?;
if file.is_none() && (project_id == 0 || def.is_external) {
let p = Path::new(file_path);
let files = SourceFile::filter(SourceFile::fields().project_id().eq(0))
.exec(&mut *db)
.await?;
file = files.into_iter().find(|f| p.ends_with(&f.path));
}
let Some(file) = file else {
return Ok(None);
};
let symbols = Symbol::filter(
Symbol::fields()
.project_id()
.eq(file.project_id)
.and(Symbol::fields().file_id().eq(file.id))
.and(Symbol::fields().name().eq(&def.symbol_name)),
)
.exec(&mut *db)
.await?;
Ok(symbols
.into_iter()
.find(|s| s.start_line <= def.start_line && def.start_line <= s.end_line))
}
pub async fn handle_find_references(
context: &ProjectContextResolver,
engine: &EngineService,
params: FindReferencesParams,
) -> anyhow::Result<FindReferencesResult> {
use super::enums::ScopeLevel;
let is_workspace_all = params.scope_level == Some(ScopeLevel::WorkspaceAll);
let is_dependencies = params.scope_level == Some(ScopeLevel::Dependencies);
let is_file_scope = params.scope_level == Some(ScopeLevel::File);
anyhow::ensure!(
!is_file_scope || params.file_path.is_some(),
"scope_level 'file' needs `file_path` (the file whose references to list)"
);
// Validate an explicit `project` even for scopes that don't otherwise resolve one.
if params.project.is_some() {
context
.resolve_project(None, params.project.as_deref())
.await?;
}
let mut guard = engine.db().lock().await;
// Resolve matching symbols
let symbols = if is_dependencies {
let external_symbols = Symbol::filter(Symbol::fields().project_id().eq(0))
.exec(&mut *guard)
.await?;
let ws_reexports = Symbol::filter(Symbol::fields().kind().eq("reexport"))
.exec(&mut *guard)
.await?;
let query = params.symbol.as_str();
let matches_query = |s: &Symbol| {
s.name == query
|| s.qualified_name == query
|| s.qualified_name.ends_with(&format!("::{query}"))
};
let mut definitions: Vec<Symbol> = external_symbols
.iter()
.filter(|s| matches_query(s))
.cloned()
.collect();
// Public paths often differ from definition paths (`tokio::sync::Mutex` is defined at
// `tokio::sync::mutex::Mutex`), so within a named crate fall back to the bare name.
if definitions.is_empty() && query.contains("::") {
let name = last_segment(query);
definitions = external_symbols
.iter()
.filter(|s| {
s.kind != "reexport"
&& s.name == name
&& crate_root(&s.qualified_name) == crate_root(query)
})
.cloned()
.collect();
}
// Workspace code references the `use` stubs that import a dependency item, not the
// item itself, so include the stubs that import a matched definition.
let mut matched = definitions.clone();
matched.extend(ws_reexports.into_iter().filter(|s| {
matches_query(s)
|| import_path(s).is_some_and(|p| p == query || p.ends_with(&format!("::{query}")))
|| definitions
.iter()
.any(|d| d.kind != "reexport" && imports_symbol(s, d))
}));
let mut seen = HashSet::new();
matched.retain(|s| seen.insert(s.id));
matched
} else if is_workspace_all {
let all = Symbol::all().exec(&mut *guard).await?;
all.into_iter()
.filter(|s| s.name == params.symbol || s.qualified_name == params.symbol)
.collect::<Vec<_>>()
} else {
let file_path = params.file_path.as_deref().map(Path::new);
let (project, _) = context
.resolve_project(file_path, params.project.as_deref())
.await?;
let proj_symbols = Symbol::filter(Symbol::fields().project_id().eq(project.id))
.exec(&mut *guard)
.await?;
proj_symbols
.into_iter()
.filter(|s| s.name == params.symbol || s.qualified_name == params.symbol)
.collect::<Vec<_>>()
};
let mut references = Vec::new();
// (project_id, file_id) of each reference, parallel to `references`.
let mut origins: Vec<(u64, u64)> = Vec::new();
let symbol_found = !symbols.is_empty();
for sym in symbols {
let refs = if is_dependencies || is_workspace_all {
SymbolReference::filter(SymbolReference::fields().symbol_id().eq(sym.id))
.exec(&mut *guard)
.await?
} else {
SymbolReference::filter(
SymbolReference::fields()
.project_id()
.eq(sym.project_id)
.and(SymbolReference::fields().symbol_id().eq(sym.id)),
)
.exec(&mut *guard)
.await?
};
for r in refs {
let file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(r.project_id)
.and(SourceFile::fields().id().eq(r.file_id)),
)
.first()
.exec(&mut *guard)
.await?;
let file_path = file
.map(|f| f.path)
.unwrap_or_else(|| "unknown".to_string());
if is_file_scope
&& let Some(scope_fp) = ¶ms.file_path
&& !file_path.ends_with(scope_fp)
&& file_path != *scope_fp
{
continue;
}
if let Some(ff) = ¶ms.file_filter
&& !file_path.to_lowercase().contains(&ff.to_lowercase())
{
continue;
}
if let Some(rf) = params.role
&& !r.role.eq_ignore_ascii_case(rf.as_str())
{
continue;
}
references.push(ReferenceItem {
file_path,
line_number: r.line_number,
role: r.role,
start_byte: r.start_byte,
end_byte: r.end_byte,
enclosing_symbol: None,
});
origins.push((r.project_id, r.file_id));
}
if is_dependencies {
let reexport_edges = scryer_db::CodeGraphEdge::filter(
scryer_db::CodeGraphEdge::fields()
.target_symbol_id()
.eq(sym.id)
.and(
scryer_db::CodeGraphEdge::fields()
.edge_type()
.eq("reexports"),
),
)
.exec(&mut *guard)
.await?;
for edge in reexport_edges {
let source_sym = Symbol::filter(Symbol::fields().id().eq(edge.source_symbol_id))
.first()
.exec(&mut *guard)
.await?;
if let Some(src_s) = source_sym {
let src_file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(src_s.project_id)
.and(SourceFile::fields().id().eq(src_s.file_id)),
)
.first()
.exec(&mut *guard)
.await?;
let file_path = src_file
.map(|f| f.path)
.unwrap_or_else(|| "unknown".to_string());
if let Some(ff) = ¶ms.file_filter
&& !file_path.to_lowercase().contains(&ff.to_lowercase())
{
continue;
}
if let Some(rf) = params.role
&& rf != super::enums::ReferenceRole::Reexport
{
continue;
}
references.push(ReferenceItem {
file_path,
line_number: src_s.start_line,
role: "reexport".to_string(),
start_byte: src_s.start_byte,
end_byte: src_s.end_byte,
enclosing_symbol: None,
});
origins.push((src_s.project_id, src_s.file_id));
}
}
}
}
let total_references = references.len();
let offset = params.offset.unwrap_or(0);
let mut paginated_references = if offset >= total_references {
Vec::new()
} else {
let remaining = &references[offset..];
if let Some(limit) = params.limit {
remaining.iter().take(limit).cloned().collect()
} else {
remaining.to_vec()
}
};
let returned_references = paginated_references.len();
let has_more = offset + returned_references < total_references;
// Name the function each returned reference sits in (only for the page being returned).
let mut file_symbols: std::collections::HashMap<(u64, u64), Vec<Symbol>> =
std::collections::HashMap::new();
for (i, item) in paginated_references.iter_mut().enumerate() {
if item.role == "reexport" {
continue;
}
let key = origins[offset + i];
if let std::collections::hash_map::Entry::Vacant(slot) = file_symbols.entry(key) {
let syms = Symbol::filter(
Symbol::fields()
.project_id()
.eq(key.0)
.and(Symbol::fields().file_id().eq(key.1)),
)
.exec(&mut *guard)
.await?;
slot.insert(syms);
}
item.enclosing_symbol = file_symbols[&key]
.iter()
.filter(|s| {
s.kind != "reexport"
&& s.start_byte <= item.start_byte
&& item.end_byte <= s.end_byte
})
.min_by_key(|s| s.end_byte - s.start_byte)
.map(|s| s.qualified_name.clone());
}
let mut notes = Vec::new();
if !symbol_found {
notes.push(format!(
"no indexed symbol named '{0}'; this is not the same as \"no usages\". Try search_symbols(query: \"{0}\"), or index_workspace if the code is new",
params.symbol
));
} else if total_references == 0 {
notes.push(match params.role {
Some(role) => format!(
"'{}' is indexed but has no references with role '{}'; drop `role` to see every kind",
params.symbol,
role.as_str()
),
None => format!("'{}' is indexed but has no recorded references", params.symbol),
});
}
Ok(FindReferencesResult {
symbol: params.symbol,
total_references,
returned_references,
offset,
limit: params.limit,
has_more,
references: paginated_references,
notes,
})
}
/// Number of references to one symbol definition, without materialising reference items.
///
/// Workspace symbols count references inside their own project. Dependency symbols
/// (project 0) count references from every project, workspace re-exports, and references to
/// the workspace `use` stubs that import them, matching `find_references` with
/// `scope_level: "dependencies"`.
pub(crate) async fn count_references(db: &mut toasty::Db, sym: &Symbol) -> anyhow::Result<usize> {
if sym.project_id != 0 {
let refs = SymbolReference::filter(
SymbolReference::fields()
.project_id()
.eq(sym.project_id)
.and(SymbolReference::fields().symbol_id().eq(sym.id)),
)
.exec(&mut *db)
.await?;
return Ok(refs.len());
}
let refs = SymbolReference::filter(SymbolReference::fields().symbol_id().eq(sym.id))
.exec(&mut *db)
.await?;
let reexports = scryer_db::CodeGraphEdge::filter(
scryer_db::CodeGraphEdge::fields()
.target_symbol_id()
.eq(sym.id)
.and(
scryer_db::CodeGraphEdge::fields()
.edge_type()
.eq("reexports"),
),
)
.exec(&mut *db)
.await?;
let stubs = Symbol::filter(
Symbol::fields()
.kind()
.eq("reexport")
.and(Symbol::fields().name().eq(&sym.name)),
)
.exec(&mut *db)
.await?;
let mut stub_refs = 0;
for stub in stubs
.iter()
.filter(|s| s.project_id != 0 && imports_symbol(s, sym))
{
stub_refs += SymbolReference::filter(SymbolReference::fields().symbol_id().eq(stub.id))
.exec(&mut *db)
.await?
.len();
}
Ok(refs.len() + reexports.len() + stub_refs)
}
pub async fn handle_get_enclosing_scope(
context: &ProjectContextResolver,
engine: &EngineService,
params: GetEnclosingScopeParams,
) -> anyhow::Result<EnclosingScopeResult> {
anyhow::ensure!(params.line >= 1, "`line` is 1-based (the first line is 1)");
let path = PathBuf::from(¶ms.file_path);
let (project, rel_path) = context
.resolve_project(Some(&path), params.project.as_deref())
.await?;
let rel = rel_path.unwrap_or(path);
let rel_str = rel.to_string_lossy().to_string();
let mut guard = engine.db().lock().await;
let file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(project.id)
.and(SourceFile::fields().path().eq(&rel_str)),
)
.first()
.exec(&mut *guard)
.await?;
let Some(file) = file else {
return Ok(EnclosingScopeResult {
notes: vec![format!(
"'{rel_str}' is not in the index; check the path, or run index_workspace if the file is new"
)],
file_path: rel_str,
..Default::default()
});
};
let mut out = EnclosingScopeResult {
file_path: rel_str,
..Default::default()
};
// Smallest named symbol spanning the line; `use` stubs aren't scopes.
let symbols = Symbol::filter(
Symbol::fields()
.project_id()
.eq(project.id)
.and(Symbol::fields().file_id().eq(file.id)),
)
.exec(&mut *guard)
.await?;
if let Some(sym) = symbols
.into_iter()
.filter(|s| {
s.kind != "reexport" && s.start_line <= params.line && s.end_line >= params.line
})
.min_by_key(|s| (s.end_line - s.start_line, std::cmp::Reverse(s.start_line)))
{
out.found = true;
out.name = Some(sym.name);
out.qualified_name = Some(sym.qualified_name);
out.kind = Some(sym.kind);
out.signature = Some(sym.signature);
out.start_line = Some(sym.start_line);
out.end_line = Some(sym.end_line);
}
let scopes = Scope::filter(
Scope::fields()
.project_id()
.eq(project.id)
.and(Scope::fields().file_id().eq(file.id)),
)
.exec(&mut *guard)
.await?;
if let Some(scope) = scopes
.into_iter()
.filter(|s| s.start_line <= params.line && s.end_line >= params.line)
.min_by_key(|s| s.end_line - s.start_line)
{
out.found = true;
out.innermost_scope = Some(LexicalScope {
scope_kind: scope.scope_kind,
start_line: scope.start_line,
end_line: scope.end_line,
});
}
if !out.found {
out.notes.push(format!(
"no symbol or scope contains line {} of '{}'; the line may be past the end of the file or the index may be stale (run index_workspace)",
params.line, out.file_path
));
}
Ok(out)
}
pub async fn handle_get_file_outline(
context: &ProjectContextResolver,
engine: &EngineService,
params: GetFileOutlineParams,
) -> anyhow::Result<FileOutlineResult> {
let path = PathBuf::from(¶ms.file_path);
let (project, rel_path) = context
.resolve_project(Some(&path), params.project.as_deref())
.await?;
let rel = rel_path.unwrap_or(path);
let rel_str = rel.to_string_lossy().to_string();
let mut guard = engine.db().lock().await;
let file = SourceFile::filter(
SourceFile::fields()
.project_id()
.eq(project.id)
.and(SourceFile::fields().path().eq(&rel_str)),
)
.first()
.exec(&mut *guard)
.await?;
let Some(file) = file else {
return Ok(FileOutlineResult {
notes: vec![format!(
"'{rel_str}' is not in the index; check the path, or run index_workspace if the file is new"
)],
file_path: rel_str,
total_symbols: 0,
returned_symbols: 0,
offset: 0,
limit: params.limit,
has_more: false,
symbols: Vec::new(),
});
};
let symbols = Symbol::filter(
Symbol::fields()
.project_id()
.eq(project.id)
.and(Symbol::fields().file_id().eq(file.id)),
)
.exec(&mut *guard)
.await?;
let compact = params.compact.unwrap_or(false);
let mut kinds_in_file: Vec<String> = symbols.iter().map(|s| s.kind.clone()).collect();
kinds_in_file.sort();
kinds_in_file.dedup();
let mut outline_symbols = Vec::new();
for s in symbols {
// Line range filter
if let Some(start) = params.start_line
&& s.end_line < start
{
continue;
}
if let Some(end) = params.end_line
&& s.start_line > end
{
continue;
}
// Kinds filter
if let Some(kinds) = ¶ms.kinds
&& !kinds.iter().any(|k| kind_matches(k, &s.kind))
{
continue;
}
// Query filter (matches name or qualified_name)
if let Some(q) = ¶ms.query {
let q_lower = q.to_lowercase();
if !s.name.to_lowercase().contains(&q_lower)
&& !s.qualified_name.to_lowercase().contains(&q_lower)
{
continue;
}
}
outline_symbols.push(OutlineSymbol {
name: s.name,
qualified_name: s.qualified_name,
kind: s.kind,
visibility: s.visibility,
signature: s.signature,
start_line: s.start_line,
end_line: s.end_line,
docstring: if compact { None } else { s.docstring },
});
}
// Sort by line number
outline_symbols.sort_by_key(|s| s.start_line);
let total_symbols = outline_symbols.len();
let offset = params.offset.unwrap_or(0);
let paginated_symbols = if offset >= total_symbols {
Vec::new()
} else {
let remaining = &outline_symbols[offset..];
if let Some(limit) = params.limit {
remaining.iter().take(limit).cloned().collect()
} else {
remaining.to_vec()
}
};
let returned_symbols = paginated_symbols.len();
let has_more = offset + returned_symbols < total_symbols;
let mut notes = Vec::new();
if let Some(kinds) = ¶ms.kinds
&& total_symbols == 0
&& !kinds_in_file.is_empty()
{
notes.push(format!(
"no symbols of kind {kinds:?}; kinds in this file: {}",
kinds_in_file.join(", ")
));
}
Ok(FileOutlineResult {
file_path: rel_str,
total_symbols,
returned_symbols,
offset,
limit: params.limit,
has_more,
symbols: paginated_symbols,
notes,
})
}
/// Whether a requested outline `kind` selects symbols of indexed kind `actual`. Accepts the
/// indexed names plus common aliases, so `function` finds Rust `fn`s and Python `method`s.
fn kind_matches(kind: &str, actual: &str) -> bool {
let aliases: &[&str] = match kind.to_ascii_lowercase().as_str() {
"fn" | "function" | "func" | "def" | "method" => &["fn", "method"],
"struct" | "class" => &["struct", "class"],
"trait" | "interface" | "protocol" => &["trait", "interface"],
"mod" | "module" | "namespace" => &["mod"],
"const" | "constant" | "static" => &["const"],
"type" | "typealias" | "type_alias" | "alias" => &["type"],
"use" | "import" | "reexport" => &["reexport"],
_ => &[],
};
kind.eq_ignore_ascii_case(actual) || aliases.contains(&actual)
}
pub async fn handle_get_type_contract(
context: &ProjectContextResolver,
engine: &EngineService,
params: GetTypeContractParams,
) -> anyhow::Result<TypeContractResult> {
let file_path = params.file_path.as_deref().map(Path::new);
let (project, rel_hint) = context
.resolve_project(file_path, params.project.as_deref())
.await?;
// The engine matches exact names only. Resolve through the shared lookup first so
// qualified names, public dependency paths (`tokio::sync::Mutex`) and the `file_path`
// hint all pick the right definition, then hand the engine its exact qualified name.
let resolved = {
let mut guard = engine.db().lock().await;
let mut candidates: Vec<_> =
lookup_symbol_candidates(&mut guard, &project, ¶ms.type_name)
.await?
.into_iter()
.filter(|c| TYPE_KINDS.contains(&c.symbol.kind.as_str()))
.collect();
if let Some(fp) = ¶ms.file_path {
let hint = rel_hint
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| fp.clone());
if let Some(hinted) = narrow_by_file(&candidates, &[&hint, fp]) {
candidates = hinted;
}
}
candidates
.into_iter()
.next()
.map(|c| c.symbol.qualified_name)
};
let root = Path::new(&project.root_path);
let contract = engine
.get_type_contract(
project.id,
root,
resolved.as_deref().unwrap_or(¶ms.type_name),
params.file_path.as_deref(),
params.member_query.as_deref(),
)
.await?;
let full_doc = params.max_tokens.is_some() || params.no_truncate.unwrap_or(false);
let (docstring, docstring_truncated) = response_docstring(contract.docstring, full_doc);
let notes = if contract.found {
Vec::new()
} else {
vec![format!(
"no struct, enum, trait or type alias named '{0}'; try search_symbols(query: \"{0}\", kinds: [\"struct\", \"enum\", \"trait\"]) or inspect_symbol",
params.type_name
)]
};
Ok(TypeContractResult {
found: contract.found,
type_name: contract.type_name,
kind: contract.kind,
signature: contract.signature,
file_path: contract.file_path,
members: contract.members,
docstring,
docstring_truncated,
notes,
})
}
// --- Tool Definitions ---
pub fn tool_definitions() -> Vec<Tool> {
vec![
make_tool::<ResolveDefinitionParams>(
"resolve_definition",
"Use when you have a file, line and column of a reference and need its definition. Follows the reference across files to the exact symbol instead of grepping for every same-named identifier; returns path, line span and signature. `line` is 1-based and `col` 0-based, and must fall on the identifier; when found is false, `notice` says why.",
read_only(),
),
make_tool::<FindReferencesParams>(
"find_references",
"Use to list where a symbol is used, e.g. before renaming or changing a signature. References come from parsed code, so unlike grep it doesn't match comments or string literals, and each one names the function or type that contains it (`enclosing_symbol`), so a caller list needs no follow-up lookup per site; paginate with offset/limit and narrow with file_filter or role. `role` keeps one kind of use; scope_level 'file' needs file_path. An unknown symbol is reported in `notes`, not as an empty list. Set scope_level 'dependencies' to find workspace usages of external crate symbols: public paths like `tokio::sync::Mutex` work, and usages through `use` imports are included.",
read_only(),
),
make_tool::<GetEnclosingScopeParams>(
"get_enclosing_scope",
"Use when you know a file and a 1-based line (e.g. from a stack trace, diff or compiler error) and need the function, method or type containing it. Returns that symbol's name, kind, signature and line span, plus the innermost block or closure at the line.",
read_only(),
),
make_tool::<GetFileOutlineParams>(
"get_file_outline",
"Use instead of reading a whole file to see what it declares: returns functions, types, traits and their signatures with exact line spans, without bodies. Then read only the lines you need. Filter with kinds (fn, struct, enum, trait, type, mod, const; aliases like function, method, class work).",
read_only(),
),
make_tool::<GetTypeContractParams>(
"get_type_contract",
"Use when you need a type's full shape (fields, variants, methods) before changing or constructing it, without reading its implementation. Filter with member_query; works for workspace types and Cargo dependency types, including public paths like `tokio::sync::Mutex`, and file_path picks one of several same-named types.",
read_only(),
),
]
}