scryer-mcp 0.2.1

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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
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(&params.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) = &params.file_path
                && !file_path.ends_with(scope_fp)
                && file_path != *scope_fp
            {
                continue;
            }

            if let Some(ff) = &params.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) = &params.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(&params.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(&params.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) = &params.kinds
            && !kinds.iter().any(|k| kind_matches(k, &s.kind))
        {
            continue;
        }

        // Query filter (matches name or qualified_name)
        if let Some(q) = &params.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) = &params.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, &params.type_name)
                .await?
                .into_iter()
                .filter(|c| TYPE_KINDS.contains(&c.symbol.kind.as_str()))
                .collect();
        if let Some(fp) = &params.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(&params.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(),
        ),
    ]
}