scryer-mcp 0.3.0

Model Context Protocol (MCP) server for Scryer code intelligence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::{HashSet, VecDeque};
use std::path::Path;

use rmcp::model::Tool;
use scryer_db::{CodeGraphEdge, SourceFile, Symbol};
use scryer_engine::EngineService;

use super::admin::{make_tool, read_only};
use super::dependency::{SymbolCandidate, lookup_symbol_candidates, narrow_by_file};
use super::navigation::{count_references, matches_symbol_query};
use crate::context::ProjectContextResolver;

/// Most candidates listed when a traced name is ambiguous.
const MAX_CANDIDATES: usize = 10;

// --- Shared Graph Helpers ---

/// Which end of a `code_graph_edge` to follow from a symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EdgeDirection {
    /// Edges pointing at the symbol (its callers).
    Inbound,
    /// Edges leaving the symbol (its callees).
    Outbound,
}

impl EdgeDirection {
    /// The symbol on the far side of `edge`.
    pub(crate) fn neighbour(self, edge: &CodeGraphEdge) -> u64 {
        match self {
            Self::Inbound => edge.source_symbol_id,
            Self::Outbound => edge.target_symbol_id,
        }
    }
}

/// The 1-hop `code_graph_edge` rows of `symbol_id` in `direction`, optionally restricted to
/// `edge_types` (e.g. `["calls"]`).
pub(crate) async fn one_hop_edges(
    db: &mut toasty::Db,
    project_id: u64,
    symbol_id: u64,
    direction: EdgeDirection,
    edge_types: Option<&[&str]>,
) -> anyhow::Result<Vec<CodeGraphEdge>> {
    let by_symbol = match direction {
        EdgeDirection::Inbound => CodeGraphEdge::fields().target_symbol_id().eq(symbol_id),
        EdgeDirection::Outbound => CodeGraphEdge::fields().source_symbol_id().eq(symbol_id),
    };
    let mut edges = CodeGraphEdge::filter(
        CodeGraphEdge::fields()
            .project_id()
            .eq(project_id)
            .and(by_symbol),
    )
    .exec(db)
    .await?;
    if let Some(types) = edge_types {
        edges.retain(|e| types.contains(&e.edge_type.as_str()));
    }
    Ok(edges)
}

/// Project-relative path of a source file, if it still exists.
pub(crate) async fn source_file_path(
    db: &mut toasty::Db,
    project_id: u64,
    file_id: u64,
) -> anyhow::Result<Option<String>> {
    let file = SourceFile::filter(
        SourceFile::fields()
            .project_id()
            .eq(project_id)
            .and(SourceFile::fields().id().eq(file_id)),
    )
    .first()
    .exec(db)
    .await?;
    Ok(file.map(|f| f.path))
}

// --- Input & Output Types ---

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct TraceCallHierarchyParams {
    /// Function or method, bare or qualified.
    pub symbol: String,
    /// Picks one definition when several share the name.
    pub file_path: Option<String>,
    /// outbound = callees (default), inbound = callers.
    pub direction: Option<super::enums::CallDirection>,
    /// Default 2, max 5.
    pub max_depth: Option<usize>,
    /// Maximum nodes.
    pub limit: Option<usize>,
    /// Pagination offset.
    pub offset: Option<usize>,
    /// Path substring filter.
    pub file_filter: Option<String>,
    /// json (default) or text: a header line, then one line per item.
    pub format: Option<crate::session::ResponseFormat>,
    /// 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 CallHierarchyNode {
    pub symbol_name: String,
    pub qualified_name: String,
    pub signature: String,
    pub file_path: String,
    pub depth: usize,
    pub edge_type: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct TraceCallHierarchyResult {
    /// Set when the list was cut to fit the budget: how to get the rest.
    #[serde(flatten, default)]
    pub next: crate::tools::budget::Continuation,
    pub symbol: String,
    /// Qualified name of the definition the trace started from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qualified_name: Option<String>,
    pub direction: String,
    pub depth: usize,
    pub total_nodes: usize,
    pub returned_nodes: usize,
    /// Offset of the first node shown.
    #[serde(default, skip_serializing_if = "crate::tools::budget::is_zero")]
    pub offset: usize,
    pub has_more: bool,
    pub nodes: Vec<CallHierarchyNode>,
    /// Set when several definitions share the name; pass `file_path` or a qualified name.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub ambiguous: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<SymbolCandidate>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
}

#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
pub struct CalculateBlastRadiusParams {
    /// Symbol, bare or qualified. This or file_path.
    pub symbol: Option<String>,
    /// File whose dependents to list. This or symbol.
    pub file_path: Option<String>,
    /// Maximum files and symbols.
    pub limit: Option<usize>,
    /// Include the affected symbols (default true).
    pub include_symbols: Option<bool>,
    /// 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 BlastRadiusResult {
    pub target: String,
    pub affected_symbols_count: usize,
    pub affected_files_count: usize,
    pub downstream_files: Vec<String>,
    pub affected_symbols: Vec<String>,
    pub truncated: bool,
    /// Set when several used definitions share the name: the answer is the list of
    /// definitions, not their dependents merged.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub ambiguous: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<SymbolCandidate>,
    /// Why the result is empty, when the target matched nothing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
}

// --- Handlers ---

pub async fn handle_trace_call_hierarchy(
    context: &ProjectContextResolver,
    engine: &EngineService,
    params: TraceCallHierarchyParams,
) -> anyhow::Result<TraceCallHierarchyResult> {
    let file_arg = params.file_path.as_deref().map(Path::new);
    let (project, rel_hint) = context
        .resolve_project(file_arg, params.project.as_deref())
        .await?;
    let direction = params
        .direction
        .unwrap_or(super::enums::CallDirection::Outbound)
        .as_str()
        .to_string();
    let max_depth = params.max_depth.unwrap_or(2).clamp(1, 5);

    let mut guard = engine.db().lock().await;
    let mut out = TraceCallHierarchyResult {
        symbol: params.symbol.clone(),
        direction: direction.clone(),
        ..Default::default()
    };

    // 1. Locate the starting definition. The shared lookup skips `use` stubs, which share
    // the name but carry no call edges.
    let mut candidates = lookup_symbol_candidates(&mut guard, &project, &params.symbol).await?;
    let only_external = !candidates.is_empty() && candidates.iter().all(|c| c.is_external());
    candidates.retain(|c| !c.is_external());
    if let Some(fp) = &params.file_path {
        let hint = rel_hint
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| fp.clone());
        match narrow_by_file(&candidates, &[&hint, fp]) {
            Some(hinted) => candidates = hinted,
            None => out.notes.push(format!(
                "file_path '{fp}' matched no definition of '{}'; ignoring it",
                params.symbol
            )),
        }
    }
    if candidates.is_empty() {
        out.notes.push(if only_external {
            format!(
                "'{}' is a dependency symbol; the call graph covers workspace code only",
                params.symbol
            )
        } else {
            format!(
                "no definition named '{}'; try search_symbols",
                params.symbol
            )
        });
        return Ok(out);
    }
    if candidates.len() > 1 {
        out.ambiguous = true;
        // Largest first, with the usages that tell the caller which one it meant.
        let mut ranked = Vec::new();
        for c in &candidates {
            let mut candidate = c.candidate();
            candidate.usages = Some(count_references(&mut guard, &c.symbol).await?);
            ranked.push(candidate);
        }
        ranked.sort_by(|a, b| {
            b.usages
                .cmp(&a.usages)
                .then_with(|| a.location.cmp(&b.location))
        });
        ranked.truncate(MAX_CANDIDATES);
        out.candidates = ranked;
        out.notes.push(format!(
            "{} definitions share this name; pass file_path or a qualified name",
            candidates.len()
        ));
        return Ok(out);
    }
    let root = candidates.remove(0).symbol;
    out.qualified_name = Some(root.qualified_name.clone());

    let symbols = Symbol::filter(Symbol::fields().project_id().eq(project.id))
        .exec(&mut *guard)
        .await?;

    // 2. BFS traversal
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    let mut result_nodes = Vec::new();

    visited.insert(root.id);
    queue.push_back((root.id, 0usize));

    while let Some((curr_id, curr_depth)) = queue.pop_front() {
        if curr_depth >= max_depth {
            continue;
        }

        let edge_direction = if direction == "inbound" {
            EdgeDirection::Inbound
        } else {
            EdgeDirection::Outbound
        };
        let edges = one_hop_edges(&mut guard, project.id, curr_id, edge_direction, None).await?;

        for edge in edges {
            let next_id = edge_direction.neighbour(&edge);

            if visited.contains(&next_id) {
                continue;
            }
            visited.insert(next_id);

            let next_sym = symbols.iter().find(|s| s.id == next_id);
            if let Some(sym) = next_sym {
                let file_path = source_file_path(&mut guard, project.id, sym.file_id)
                    .await?
                    .unwrap_or_else(|| "unknown".to_string());

                if let Some(ff) = &params.file_filter
                    && !file_path.to_lowercase().contains(&ff.to_lowercase())
                {
                    continue;
                }

                result_nodes.push(CallHierarchyNode {
                    symbol_name: sym.name.clone(),
                    qualified_name: sym.qualified_name.clone(),
                    signature: sym.signature.clone(),
                    file_path,
                    depth: curr_depth + 1,
                    edge_type: edge.edge_type.clone(),
                });

                queue.push_back((next_id, curr_depth + 1));
            }
        }
    }

    let total_nodes = result_nodes.len();
    let offset = params.offset.unwrap_or(0);
    let mut result_nodes: Vec<_> = result_nodes.into_iter().skip(offset).collect();
    let has_more = params.limit.is_some_and(|limit| result_nodes.len() > limit);
    if let Some(limit) = params.limit {
        result_nodes.truncate(limit);
    }
    let paginated_nodes = result_nodes;

    let returned_nodes = paginated_nodes.len();

    out.depth = max_depth;
    out.total_nodes = total_nodes;
    out.returned_nodes = returned_nodes;
    out.offset = offset;
    out.has_more = has_more;
    out.nodes = paginated_nodes;
    Ok(out)
}

pub async fn handle_calculate_blast_radius(
    context: &ProjectContextResolver,
    engine: &EngineService,
    params: CalculateBlastRadiusParams,
) -> anyhow::Result<BlastRadiusResult> {
    anyhow::ensure!(
        params.symbol.is_some() || params.file_path.is_some(),
        "Pass `symbol` (a symbol name) or `file_path` (a source file) to assess"
    );
    let file_path = params.file_path.as_deref().map(Path::new);
    let (project, rel_path) = context
        .resolve_project(file_path, params.project.as_deref())
        .await?;
    // A relative path to a file the filesystem doesn't know (yet) is still project-relative.
    let rel_path = rel_path.or_else(|| {
        file_path
            .filter(|p| {
                p.is_relative()
                    && !p
                        .components()
                        .any(|c| matches!(c, std::path::Component::ParentDir))
            })
            .map(Path::to_path_buf)
    });

    let mut guard = engine.db().lock().await;
    let symbols = Symbol::filter(Symbol::fields().project_id().eq(project.id))
        .exec(&mut *guard)
        .await?;

    let mut seed_symbol_ids = Vec::new();
    let mut notes = Vec::new();
    let target_label = if let Some(sym_name) = &params.symbol {
        let mut seeds: Vec<&Symbol> = symbols
            .iter()
            .filter(|s| matches_symbol_query(s, sym_name))
            .collect();
        // `file_path` picks one definition when several share the name.
        if let Some(fp) = &params.file_path
            && seeds.len() > 1
        {
            let hint = fp.trim_start_matches("./");
            let mut in_file = Vec::new();
            for s in &seeds {
                let file = SourceFile::filter(
                    SourceFile::fields()
                        .project_id()
                        .eq(project.id)
                        .and(SourceFile::fields().id().eq(s.file_id)),
                )
                .first()
                .exec(&mut *guard)
                .await?;
                if file.is_some_and(|f| {
                    f.path == hint
                        || hint.ends_with(&format!("/{}", f.path))
                        || f.path.ends_with(&format!("/{hint}"))
                }) {
                    in_file.push(*s);
                }
            }
            if in_file.is_empty() {
                notes.push(format!(
                    "file_path '{fp}' matched no definition of '{sym_name}'; ignoring it"
                ));
            } else {
                seeds = in_file;
            }
        }
        // Several definitions that are used: say which, rather than merge their dependents.
        let mut used = Vec::new();
        for s in seeds.iter().filter(|s| s.kind != "reexport") {
            let usages = count_references(&mut guard, s).await?;
            if usages > 0 {
                used.push((*s, usages));
            }
        }
        if used.len() > 1 {
            let mut candidates = Vec::new();
            for (s, usages) in &used {
                let file = SourceFile::filter(
                    SourceFile::fields()
                        .project_id()
                        .eq(project.id)
                        .and(SourceFile::fields().id().eq(s.file_id)),
                )
                .first()
                .exec(&mut *guard)
                .await?;
                candidates.push(SymbolCandidate {
                    qualified_name: s.qualified_name.clone(),
                    kind: s.kind.clone(),
                    location: format!(
                        "{}:{}",
                        file.map_or_else(|| "unknown".to_string(), |f| f.path),
                        s.start_line
                    ),
                    usages: Some(*usages),
                });
            }
            candidates.sort_by(|a, b| {
                b.usages
                    .cmp(&a.usages)
                    .then_with(|| a.location.cmp(&b.location))
            });
            let definition_count = candidates.len();
            candidates.truncate(MAX_CANDIDATES);
            notes.push(format!(
                "{definition_count} definitions named '{sym_name}' are used; pass file_path (the definition's file) or a qualified name to assess one"
            ));
            return Ok(BlastRadiusResult {
                target: sym_name.clone(),
                affected_symbols_count: 0,
                affected_files_count: 0,
                downstream_files: Vec::new(),
                affected_symbols: Vec::new(),
                truncated: false,
                ambiguous: true,
                candidates,
                notes,
            });
        }
        seed_symbol_ids.extend(seeds.iter().map(|s| s.id));
        if seed_symbol_ids.is_empty() {
            notes.push(format!(
                "no symbol named '{sym_name}' in this project; try search_symbols(query: \"{sym_name}\") or check the project"
            ));
        }
        sym_name.clone()
    } else if let Some(rel) = rel_path {
        let rel_str = rel.to_string_lossy().to_string();
        let file = SourceFile::filter(
            SourceFile::fields()
                .project_id()
                .eq(project.id)
                .and(SourceFile::fields().path().eq(&rel_str)),
        )
        .first()
        .exec(&mut *guard)
        .await?;

        if let Some(file) = file {
            for s in &symbols {
                if s.file_id == file.id {
                    seed_symbol_ids.push(s.id);
                }
            }
        } else {
            notes.push(format!(
                "'{rel_str}' is not in the index; check the path, or run index_workspace if the file is new"
            ));
        }
        rel_str
    } else {
        // `file_path` lies outside every project's root.
        notes.push("file_path is outside the resolved project".to_string());
        params.file_path.clone().unwrap_or_default()
    };

    // Follow inbound/reverse calls to find all affected callers and dependents
    let mut visited_symbols = HashSet::new();
    let mut queue = VecDeque::new();

    for id in seed_symbol_ids {
        visited_symbols.insert(id);
        queue.push_back(id);
    }

    while let Some(curr_id) = queue.pop_front() {
        // Reverse edges: where target_symbol_id == curr_id
        let reverse_edges = one_hop_edges(
            &mut guard,
            project.id,
            curr_id,
            EdgeDirection::Inbound,
            None,
        )
        .await?;

        for edge in reverse_edges {
            if !visited_symbols.contains(&edge.source_symbol_id) {
                visited_symbols.insert(edge.source_symbol_id);
                queue.push_back(edge.source_symbol_id);
            }
        }
    }

    let mut affected_files = HashSet::new();
    let mut affected_symbol_names = Vec::new();

    for id in &visited_symbols {
        if let Some(s) = symbols.iter().find(|sym| sym.id == *id) {
            affected_symbol_names.push(s.qualified_name.clone());
            if let Some(path) = source_file_path(&mut guard, project.id, s.file_id).await? {
                affected_files.insert(path);
            }
        }
    }

    let mut downstream_files: Vec<String> = affected_files.into_iter().collect();
    downstream_files.sort();
    affected_symbol_names.sort();

    let total_affected_symbols = visited_symbols.len();
    let total_affected_files = downstream_files.len();

    let include_symbols = params.include_symbols.unwrap_or(true);
    let mut affected_symbols = if include_symbols {
        affected_symbol_names
    } else {
        Vec::new()
    };

    let mut truncated = false;
    if let Some(limit) = params.limit {
        if downstream_files.len() > limit {
            downstream_files.truncate(limit);
            truncated = true;
        }
        if affected_symbols.len() > limit {
            affected_symbols.truncate(limit);
            truncated = true;
        }
    }

    Ok(BlastRadiusResult {
        target: target_label,
        affected_symbols_count: total_affected_symbols,
        affected_files_count: total_affected_files,
        downstream_files,
        affected_symbols,
        truncated,
        ambiguous: false,
        candidates: Vec::new(),
        notes,
    })
}

// --- Tool Definitions ---

pub fn tool_definitions() -> Vec<Tool> {
    vec![
        make_tool::<TraceCallHierarchyParams>(
            "trace_call_hierarchy",
            "Use to follow callers (who calls this) or callees beyond one hop: direction 'inbound' or 'outbound' (default), max_depth default 2, max 5. Starts from the definition, never a `use` import; several same-name definitions return candidates, so pass file_path or a qualified name.",
            read_only(),
        ),
        make_tool::<CalculateBlastRadiusParams>(
            "calculate_blast_radius",
            "Use before changing or deleting a symbol or file to see which indexed workspace code depends on it. Pass `symbol` or `file_path` (at least one). Returns the reverse dependency graph, affected symbol count and downstream files.",
            read_only(),
        ),
    ]
}

impl crate::tools::budget::Paged for TraceCallHierarchyResult {
    const TOOL: &'static str = "trace_call_hierarchy";
    fn item_count(&self) -> usize {
        self.nodes.len()
    }
    fn page_offset(&self) -> usize {
        self.offset
    }
    fn keep_first(&mut self, kept: usize) {
        self.nodes.truncate(kept);
        self.returned_nodes = kept;
        self.has_more = true;
    }
    fn continuation_mut(&mut self) -> &mut crate::tools::budget::Continuation {
        &mut self.next
    }
    fn render_text(&self) -> String {
        crate::tools::render::trace_call_hierarchy(self)
    }
}