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
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
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

use rmcp::{
    ErrorData as McpError, Peer, RoleServer, ServerHandler,
    model::{
        CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,
        InitializeRequestParams, InitializeResult, ListToolsResult, PaginatedRequestParams,
        ServerCapabilities, ServerConfig,
    },
    service::{NotificationContext, RequestContext},
};
use scryer_db::{ProjectRegistry, ScryerDb};
use scryer_engine::EngineService;
use serde_json::Value;

use crate::context::ProjectContextResolver;
use crate::index_gate::{self, CallIndex};
use crate::session::ResponseFormat;
use crate::session::{SessionOptions, ToolProfile};
use crate::telemetry::TokenSavingsMiddleware;
use crate::tools::{
    admin, adr, cli_hint, dependency, graph, inspect, navigation, search, tool_definitions_for,
};

/// Shared state accessible across tool routers and session life-cycle.
#[derive(Clone)]
pub struct ScryerServerState {
    pub db: ScryerDb,
    /// What the text header says about each project's index, for a few seconds.
    pub(crate) health: Arc<std::sync::Mutex<std::collections::HashMap<u64, (Instant, IndexFacts)>>>,
    pub engine: EngineService,
    pub context: ProjectContextResolver,
    pub telemetry: TokenSavingsMiddleware,
    pub session_id: String,
}

/// The Scryer Model Context Protocol (MCP) server.
#[derive(Clone)]
pub struct ScryerMcpServer {
    state: ScryerServerState,
    options: SessionOptions,
    /// How long a call waits for a first index to finish before answering `INDEXING`.
    first_query_wait: std::time::Duration,
}

/// Whether a `find_references` answer may say `complete`. Set from the recall run of Plan 19
/// Phase 6 (`harness.py verify <suite> --recall --identifiers 60`, gate 98%): cargo 99.1%
/// (`testing-harness/results/recall-cargo-plan19.json`) and this repository 98.0%
/// (`recall-scryer-plan19.json`). Rust only: Python and TypeScript have no real-repository
/// measurement yet (Plan 21 Phase 5). Set it to false if either run drops below the gate.
const RECALL_GATE_PASSED: bool = true;

/// How long the index facts in a text header are reused.
const HEALTH_TTL: std::time::Duration = std::time::Duration::from_secs(10);

/// What a text header says about a project's index.
#[derive(Debug, Clone)]
pub(crate) struct IndexFacts {
    parse_failures: usize,
    line: String,
}

/// Index facts and completeness for a `find_references` answer. `complete` says the list is
/// exhaustive over the indexed files: it needs the recall gate, a Rust-only answer, a result
/// that is neither cut nor ambiguous, and no file that failed to parse.
fn annotate_references(
    res: &mut navigation::FindReferencesResult,
    facts: Option<&IndexFacts>,
    partial: bool,
) {
    let Some(facts) = facts else { return };
    res.next.index_state = Some(facts.line.clone());
    if facts.parse_failures > 0 {
        res.notes.push(format!(
            "CAVEAT: {} file(s) failed to parse and are not indexed; usages in them are missing",
            facts.parse_failures
        ));
    }
    if RECALL_GATE_PASSED
        && !partial
        && facts.parse_failures == 0
        && res.all_rust
        && res.total_references > 0
        && !res.ambiguous
        && !res.has_more
        && res.next.complete.is_none()
    {
        res.next.complete = Some(true);
    }
}

/// A list result as the session's format wants it: the text, or the JSON object.
///
/// The files the answer names go into `touched`, so the caller can check they are current.
/// (A JSON answer is walked for them afterwards; text has to be collected before it is rendered.)
fn emit<P: crate::tools::budget::Paged>(
    res: P,
    format: ResponseFormat,
    touched: &mut std::collections::BTreeSet<String>,
) -> anyhow::Result<Value> {
    Ok(match format {
        ResponseFormat::Text => {
            index_gate::collect_files(&serde_json::to_value(&res)?, touched);
            Value::String(res.render_text())
        }
        ResponseFormat::Json => serde_json::to_value(res)?,
    })
}

/// The header's index line for a list answer, given the call's index state. The files the
/// answer names are only gathered when a stale index makes them matter.
fn index_line<T: serde::Serialize>(
    call: &CallIndex,
    facts: Option<&IndexFacts>,
    res: &T,
) -> Option<String> {
    let mut touched = std::collections::BTreeSet::new();
    if matches!(call.state, scryer_engine::IndexState::Stale { .. })
        && let Ok(value) = serde_json::to_value(res)
    {
        index_gate::collect_files(&value, &mut touched);
    }
    call.header_line(facts.map(|f| f.line.as_str()), &touched)
}

/// Whether the index makes the answer `res` partial (still building, or a file in it pending).
fn is_partial<T: serde::Serialize>(call: &CallIndex, res: &T) -> bool {
    let mut touched = std::collections::BTreeSet::new();
    if matches!(call.state, scryer_engine::IndexState::Stale { .. })
        && let Ok(value) = serde_json::to_value(res)
    {
        index_gate::collect_files(&value, &mut touched);
    }
    call.caveat(&touched).is_some()
}

/// A single-answer result as the session's format wants it. Text gets a header with the index
/// state, and the files it names go into `touched` (JSON is walked for them afterwards).
fn answer<T: serde::Serialize>(
    res: T,
    format: ResponseFormat,
    call: &CallIndex,
    touched: &mut std::collections::BTreeSet<String>,
    text: impl FnOnce(&T, Option<String>) -> String,
) -> anyhow::Result<Value> {
    Ok(match format {
        ResponseFormat::Text => {
            let value = serde_json::to_value(&res)?;
            index_gate::collect_files(&value, touched);
            let state = call.header_line(None, touched);
            Value::String(text(&res, state))
        }
        ResponseFormat::Json => serde_json::to_value(res)?,
    })
}

/// Tool results go out as compact JSON: pretty-printing costs about 17% more characters and no
/// agent reads the indentation.
pub(crate) fn render_json(value: &Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "{}".to_string())
}

impl ScryerMcpServer {
    /// List results lose whole items from the end, never the middle of one, and say how to
    /// fetch the rest.
    fn fit_list<P: crate::tools::budget::Paged>(
        &self,
        res: &mut P,
        max_tokens: Option<usize>,
        no_truncate: bool,
        format: ResponseFormat,
    ) {
        crate::tools::budget::fit_list_to_budget(res, max_tokens, no_truncate, format, |s| {
            self.state.telemetry.count_tokens(s)
        });
    }

    /// The facts the text header gives about the index of the project a call targets.
    async fn index_facts(&self, project: Option<&str>) -> Option<IndexFacts> {
        let (project, _) = self
            .state
            .context
            .resolve_project(None, project)
            .await
            .ok()?;
        if let Ok(cache) = self.state.health.lock()
            && let Some((at, facts)) = cache.get(&project.id)
            && at.elapsed() < HEALTH_TTL
        {
            return Some(facts.clone());
        }
        let health = scryer_engine::index_health(&self.state.db, project.id)
            .await
            .ok()?;
        let parse_failures = health.stats.as_ref().map_or(0, |s| s.parse_failures.count);
        let indexed = health
            .last_indexed
            .as_deref()
            .unwrap_or("at an unknown time");
        let facts = IndexFacts {
            parse_failures,
            line: format!(
                "index: {} files, {} parse failures, indexed {indexed}",
                health.file_count, parse_failures
            ),
        };
        if let Ok(mut cache) = self.state.health.lock() {
            cache.insert(project.id, (Instant::now(), facts.clone()));
        }
        Some(facts)
    }

    /// Create a new `ScryerMcpServer` instance.
    pub fn new(
        db: ScryerDb,
        engine: EngineService,
        registry: Arc<ProjectRegistry>,
        session_id: Option<String>,
    ) -> anyhow::Result<Self> {
        let telemetry = TokenSavingsMiddleware::new(db.clone())?;
        let context = ProjectContextResolver::new(registry);
        let session_id = session_id.unwrap_or_else(|| {
            format!(
                "scryer-sess-{}",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis()
            )
        });

        Ok(Self {
            state: ScryerServerState {
                db,
                health: Arc::default(),
                engine,
                context,
                telemetry,
                session_id,
            },
            options: SessionOptions::default(),
            first_query_wait: index_gate::first_query_wait(),
        })
    }

    /// Override how long a call waits for a first index (default `SCRYER_FIRST_QUERY_WAIT`,
    /// 20 s).
    pub fn with_first_query_wait(mut self, wait: std::time::Duration) -> Self {
        self.first_query_wait = wait;
        self
    }

    /// Set the options this session was opened with (tool profile, default budget, ...).
    pub fn with_options(mut self, options: SessionOptions) -> Self {
        self.options = options;
        self
    }

    /// Apply the options that need the registry: make `--project` the active project.
    ///
    /// Call after [`Self::set_session_cwd`] so an explicit project wins over the cwd. An
    /// unknown project is an error, so a typo fails the session instead of being ignored.
    pub async fn apply_session_options(&self) -> anyhow::Result<()> {
        if let Some(project) = self.options.project.as_deref() {
            let (project, _) = self
                .state
                .context
                .resolve_project(None, Some(project.trim()))
                .await?;
            self.state.context.set_active_project(project.id).await;
        }
        Ok(())
    }

    /// Access inner server state.
    pub fn state(&self) -> &ScryerServerState {
        &self.state
    }

    /// Bind this session to the client's working directory.
    pub async fn set_session_cwd(&self, cwd: PathBuf) {
        self.state.context.set_session_cwd(cwd).await;
    }

    /// Replace session roots with the client's announced `roots/list`, when supported.
    ///
    /// Roots are deprecated by SEP-2577 but still sent by current clients. The cwd from the
    /// daemon handshake remains the primary source of session context.
    #[allow(deprecated)]
    async fn refresh_session_roots(&self, peer: &Peer<RoleServer>) {
        let supports_roots = peer
            .peer_info()
            .is_some_and(|info| info.capabilities.roots.is_some());
        if !supports_roots {
            return;
        }

        match peer.list_roots().await {
            Ok(result) => {
                let roots: Vec<PathBuf> = result
                    .roots
                    .iter()
                    .filter_map(|root| file_uri_to_path(&root.uri))
                    .collect();
                if !roots.is_empty() {
                    self.state.context.set_session_roots(roots).await;
                }
            }
            Err(e) => tracing::debug!("Client roots/list failed: {e}"),
        }
    }

    /// Execute a tool invocation through the dispatcher with token telemetry interceptor.
    ///
    /// Every tool name is accepted under every [`ToolProfile`]: the profile only decides what
    /// `tools/list` shows, so a client that calls a hidden tool by name still works.
    pub async fn dispatch_tool(
        &self,
        name: &str,
        mut arguments: Value,
    ) -> Result<CallToolResponse, McpError> {
        let start_time = Instant::now();
        let tool_name = name.to_string();
        // Agents send "12" for 12 and null for "absent"; make that mean what they intended.
        crate::tools::schema::coerce_arguments(name, &mut arguments);

        let mut project_id = None;

        // A per-call budget wins over the session default (`scryer serve --max-tokens`).
        let max_tokens = arguments
            .get("max_tokens")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .or(self.options.max_tokens);
        let format = arguments
            .get("format")
            .and_then(|v| serde_json::from_value::<ResponseFormat>(v.clone()).ok())
            .unwrap_or(self.options.format);
        let project_arg = arguments
            .get("project")
            .and_then(Value::as_str)
            .map(str::to_string);
        // A tool without an explicit budget gets the one sized to its answers.
        let asked = arguments
            .get("lines")
            .or_else(|| arguments.get("at"))
            .or_else(|| arguments.get("symbols"))
            .and_then(Value::as_array)
            .map_or(1, Vec::len);
        let max_tokens =
            Some(max_tokens.unwrap_or_else(|| crate::tools::budget::default_budget(name, asked)));
        let no_truncate = arguments
            .get("no_truncate")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // A call that reads the index first waits for a first index to finish, and brings the
        // files it names up to date; after it answers, the files the answer names get the same
        // check, and if any had changed the call answers again from the refreshed index.
        let mut call = if index_gate::needs_index(name) {
            index_gate::prepare_call(
                &self.state.context,
                &self.state.engine,
                &arguments,
                project_arg.as_deref(),
                self.first_query_wait,
            )
            .await
        } else {
            CallIndex::none()
        };
        let mut touched = std::collections::BTreeSet::new();
        let mut next_arguments = Some(arguments);
        let mut answered_again = false;
        let mut dispatch_result: anyhow::Result<Value>;
        loop {
            let arguments = next_arguments
                .take()
                .expect("the arguments are set before every pass");
            let kept_arguments = arguments.clone();
            touched.clear();
            // Execute tool within an async block returning anyhow::Result<Value>
            dispatch_result = async {
                match name {
                    // Administration Router (6 tools)
                    "list_projects" => {
                        let params: admin::ListProjectsParams = serde_json::from_value(arguments)?;
                        let res = admin::handle_list_projects(
                            &self.state.context,
                            &self.state.db,
                            params,
                        )
                        .await?;
                        Ok(serde_json::to_value(res)?)
                    }
                    "switch_active_project" => {
                        let params: admin::SwitchActiveProjectParams =
                            serde_json::from_value(arguments)?;
                        let res = admin::handle_switch_active_project(&self.state.context, params)
                            .await?;
                        project_id = Some(res.active_project_id);
                        Ok(serde_json::to_value(res)?)
                    }
                    "delete_project" => {
                        let params: admin::DeleteProjectParams = serde_json::from_value(arguments)?;
                        let res = admin::handle_delete_project(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        Ok(serde_json::to_value(res)?)
                    }
                    "index_workspace" => {
                        let params: admin::IndexWorkspaceParams =
                            serde_json::from_value(arguments)?;
                        let res = admin::handle_index_workspace(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        if let Ok(mut cache) = self.state.health.lock() {
                            cache.clear();
                        }
                        Ok(serde_json::json!({
                            "scanned_files": res.scanned_files,
                            "added_files": res.added_files,
                            "modified_files": res.modified_files,
                            "unchanged_files": res.unchanged_files,
                            "deleted_files": res.deleted_files,
                            "total_scopes": res.total_scopes,
                            "total_symbols": res.total_symbols,
                            "total_references": res.total_references,
                            "total_edges": res.total_edges,
                        }))
                    }
                    "get_indexing_status" => {
                        let params: admin::GetIndexingStatusParams =
                            serde_json::from_value(arguments)?;
                        let res = admin::handle_get_indexing_status(
                            &self.state.context,
                            &self.state.engine,
                            &self.state.db,
                            params,
                        )
                        .await?;
                        project_id = Some(res.project_id);
                        Ok(serde_json::to_value(res)?)
                    }
                    "get_token_savings_metrics" => {
                        let params: admin::GetTokenSavingsMetricsParams =
                            serde_json::from_value(arguments)?;
                        let res =
                            admin::handle_get_token_savings_metrics(&self.state.telemetry, params)
                                .await?;
                        Ok(serde_json::to_value(res)?)
                    }

                    // Navigation Router (5 tools)
                    "resolve_definition" => {
                        let params: navigation::ResolveDefinitionParams =
                            serde_json::from_value(arguments)?;
                        let res = navigation::handle_resolve_definition(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        Ok(serde_json::to_value(res)?)
                    }
                    "find_references" => {
                        let params: navigation::FindReferencesParams =
                            serde_json::from_value(arguments)?;
                        let res = navigation::handle_find_references(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        let facts = self.index_facts(project_arg.as_deref()).await;
                        let partial = is_partial(&call, &res);
                        annotate_references(&mut res, facts.as_ref(), partial);
                        if let Some(line) = index_line(&call, facts.as_ref(), &res) {
                            res.next.index_state = Some(line);
                        }
                        if partial {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        self.fit_list(&mut res, max_tokens, no_truncate, format);
                        emit(res, format, &mut touched)
                    }
                    "get_enclosing_scope" => {
                        let params: navigation::GetEnclosingScopeParams =
                            serde_json::from_value(arguments)?;
                        let res = navigation::handle_get_enclosing_scope(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        navigation::fit_scope_to_budget(&mut res, max_tokens, no_truncate, |s| {
                            self.state.telemetry.count_tokens(s)
                        });
                        if is_partial(&call, &res) {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        answer(
                            res,
                            format,
                            &call,
                            &mut touched,
                            crate::tools::render::enclosing_scope,
                        )
                    }
                    "get_file_outline" => {
                        let params: navigation::GetFileOutlineParams =
                            serde_json::from_value(arguments)?;
                        let res = navigation::handle_get_file_outline(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        let facts = self.index_facts(project_arg.as_deref()).await;
                        res.next.index_state = index_line(&call, facts.as_ref(), &res);
                        if is_partial(&call, &res) {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        navigation::fit_outline_detail(
                            &mut res,
                            max_tokens,
                            no_truncate,
                            format,
                            |s| self.state.telemetry.count_tokens(s),
                        );
                        self.fit_list(&mut res, max_tokens, no_truncate, format);
                        emit(res, format, &mut touched)
                    }
                    "get_type_contract" => {
                        let params: navigation::GetTypeContractParams =
                            serde_json::from_value(arguments)?;
                        let res = navigation::handle_get_type_contract(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        Ok(serde_json::to_value(res)?)
                    }

                    // Graph Traversal Router (2 tools)
                    "trace_call_hierarchy" => {
                        let params: graph::TraceCallHierarchyParams =
                            serde_json::from_value(arguments)?;
                        let res = graph::handle_trace_call_hierarchy(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        let facts = self.index_facts(project_arg.as_deref()).await;
                        res.next.index_state = index_line(&call, facts.as_ref(), &res);
                        if is_partial(&call, &res) {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        self.fit_list(&mut res, max_tokens, no_truncate, format);
                        emit(res, format, &mut touched)
                    }
                    "calculate_blast_radius" => {
                        let params: graph::CalculateBlastRadiusParams =
                            serde_json::from_value(arguments)?;
                        let res = graph::handle_calculate_blast_radius(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        if is_partial(&call, &res) {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        answer(
                            res,
                            format,
                            &call,
                            &mut touched,
                            crate::tools::render::blast_radius,
                        )
                    }

                    // Architectural Memory Router (3 tools)
                    "query_adrs" => {
                        let params: adr::QueryAdrsParams = serde_json::from_value(arguments)?;
                        let res =
                            adr::handle_query_adrs(&self.state.context, &self.state.engine, params)
                                .await?;
                        let mut res = res;
                        self.fit_list(&mut res, max_tokens, no_truncate, ResponseFormat::Json);
                        Ok(serde_json::to_value(res)?)
                    }
                    "record_adr" => {
                        let params: adr::RecordAdrParams = serde_json::from_value(arguments)?;
                        let res =
                            adr::handle_record_adr(&self.state.context, &self.state.engine, params)
                                .await?;
                        Ok(serde_json::to_value(res)?)
                    }
                    "delete_adr" => {
                        let params: adr::DeleteAdrParams = serde_json::from_value(arguments)?;
                        let res =
                            adr::handle_delete_adr(&self.state.context, &self.state.engine, params)
                                .await?;
                        Ok(serde_json::to_value(res)?)
                    }

                    // Dependency Discovery & Search (2 tools)
                    "get_crate_outline" => {
                        let params: dependency::GetCrateOutlineParams =
                            serde_json::from_value(arguments)?;
                        let mut res = dependency::handle_get_crate_outline(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        dependency::fit_crate_outline_to_budget(
                            &mut res,
                            max_tokens,
                            no_truncate,
                            |s| self.state.telemetry.count_tokens(s),
                        );
                        if format == ResponseFormat::Text {
                            return Ok(Value::String(crate::tools::render::crate_outline(&res)));
                        }
                        Ok(serde_json::to_value(res)?)
                    }
                    "search_symbols" => {
                        let params: search::SearchSymbolsParams =
                            serde_json::from_value(arguments)?;
                        let res = search::handle_search_symbols(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        let mut res = res;
                        let facts = self.index_facts(project_arg.as_deref()).await;
                        res.next.index_state = index_line(&call, facts.as_ref(), &res);
                        self.fit_list(&mut res, max_tokens, no_truncate, format);
                        emit(res, format, &mut touched)
                    }

                    // Symbol Inspection (1 tool)
                    "inspect_symbol" => {
                        let params: inspect::InspectSymbolParams =
                            serde_json::from_value(arguments)?;
                        if params.symbols.is_some() {
                            let res = inspect::handle_inspect_batch(
                                &self.state.context,
                                &self.state.engine,
                                params,
                                max_tokens,
                                no_truncate,
                                |s| self.state.telemetry.count_tokens(s),
                            )
                            .await?;
                            return Ok(serde_json::to_value(res)?);
                        }
                        let mut res = inspect::handle_inspect_symbol(
                            &self.state.context,
                            &self.state.engine,
                            params,
                        )
                        .await?;
                        inspect::fit_snippet_to_budget(&mut res, max_tokens, no_truncate, |s| {
                            self.state.telemetry.count_tokens(s)
                        });
                        if self.options.tools == ToolProfile::Core {
                            // The session doesn't list extended tools; say how to reach them.
                            for hint in &mut res.see_also {
                                *hint = cli_hint(hint);
                            }
                        }
                        if is_partial(&call, &res) {
                            CallIndex::scrub_notes(&mut res.notes);
                        }
                        answer(
                            res,
                            format,
                            &call,
                            &mut touched,
                            crate::tools::render::inspect_symbol,
                        )
                    }

                    unknown => {
                        anyhow::bail!("Unknown tool: '{unknown}'")
                    }
                }
            }
            .await;

            if answered_again || !index_gate::needs_index(name) || dispatch_result.is_err() {
                break;
            }
            if let Ok(value @ (Value::Object(_) | Value::Array(_))) = &dispatch_result {
                index_gate::collect_files(value, &mut touched);
            }
            if let Some(root) = call.root() {
                let rels: Vec<PathBuf> = touched
                    .iter()
                    .filter_map(|f| index_gate::relative_to_root(&root, f))
                    .collect();
                if index_gate::refresh(&self.state.engine, &mut call, &rels).await {
                    if let Ok(mut cache) = self.state.health.lock() {
                        cache.clear();
                    }
                    answered_again = true;
                    next_arguments = Some(kept_arguments);
                    continue;
                }
            }
            break;
        }

        if index_gate::needs_index(name)
            && let Ok(value) = &mut dispatch_result
        {
            call.annotate_json(value, &touched);
        }

        match dispatch_result {
            Ok(val) => {
                // List tools in text format return their text as a string value.
                let json_str = match &val {
                    Value::String(text) => text.clone(),
                    other => render_json(other),
                };
                let (limited_payload, payload_tokens, hard_cut) = self
                    .state
                    .telemetry
                    .enforce_limit(&json_str, max_tokens, no_truncate);
                // An answer is "truncated" when the agent was told there is more: cut at the hard
                // budget, or a page with a continuation (`next.next_offset`, or `TRUNCATED` in the
                // header line of the text format).
                let truncated = hard_cut
                    || match &val {
                        Value::String(text) => text
                            .lines()
                            .next()
                            .is_some_and(|header| header.contains("TRUNCATED")),
                        other => other.pointer("/next/next_offset").is_some(),
                    };

                let active_pid = self.state.context.get_active_project().await;

                // Record the call's size and outcome (never its content), asynchronously.
                self.state.telemetry.record_invocation(
                    self.state.session_id.clone(),
                    project_id.or(active_pid),
                    tool_name,
                    payload_tokens as u64,
                    truncated,
                    start_time,
                );

                Ok(CallToolResult::success(vec![ContentBlock::text(limited_payload)]).into())
            }
            Err(e) => {
                let err_msg = format!("Tool execution error for '{tool_name}': {e}");
                Ok(CallToolResult::error(vec![ContentBlock::text(err_msg)]).into())
            }
        }
    }
}

impl ServerHandler for ScryerMcpServer {
    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("scryer-mcp", env!("CARGO_PKG_VERSION")))
            .with_instructions(server_instructions(self.options.tools))
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, McpError> {
        context.peer.set_peer_info(request.clone());
        self.negotiate_initialize(&request)
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        Ok(ListToolsResult {
            tools: tool_definitions_for(self.options.tools, self.options.always_load),
            ..Default::default()
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, McpError> {
        let args_value = request
            .arguments
            .map(Value::Object)
            .unwrap_or(Value::Object(Default::default()));

        self.dispatch_tool(&request.name, args_value).await
    }

    async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
        self.refresh_session_roots(&context.peer).await;
    }

    async fn on_roots_list_changed(&self, context: NotificationContext<RoleServer>) {
        self.refresh_session_roots(&context.peer).await;
    }
}

/// Convert a `file://` URI into a local path, decoding percent escapes.
fn file_uri_to_path(uri: &str) -> Option<PathBuf> {
    let rest = uri.strip_prefix("file://")?;
    // Skip an optional authority ("file://localhost/path").
    let path = &rest[rest.find('/')?..];

    let bytes = path.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let Ok(byte) = u8::from_str_radix(&path[i + 1..i + 3], 16)
        {
            decoded.push(byte);
            i += 3;
        } else {
            decoded.push(bytes[i]);
            i += 1;
        }
    }
    let decoded = String::from_utf8(decoded).ok()?;

    // Windows drive paths arrive as "/C:/...".
    let trimmed = match decoded.as_bytes() {
        [b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => &decoded[1..],
        _ => decoded.as_str(),
    };
    Some(PathBuf::from(trimmed))
}

#[cfg(test)]
mod tests {
    use super::file_uri_to_path;
    use std::path::PathBuf;

    #[test]
    fn file_uris_decode_to_paths() {
        assert_eq!(
            file_uri_to_path("file:///home/me/my%20project"),
            Some(PathBuf::from("/home/me/my project"))
        );
        assert_eq!(
            file_uri_to_path("file://localhost/srv/repo"),
            Some(PathBuf::from("/srv/repo"))
        );
        assert_eq!(file_uri_to_path("https://example.com/x"), None);
    }
}

/// What a client reads at `initialize`: how to choose among the tools and the conventions
/// every tool shares. Keep in step with the decision tree in `scryer init`'s instructions.
pub const SERVER_INSTRUCTIONS_FULL: &str = r#"Use Scryer instead of grep for code questions: who calls X, where X is defined, what a file contains, what contains this line, what breaks if X changes. Parsed code (Rust, Python, TypeScript), exact lines.

Not for: a literal string, log or error message, comment, config or non-code file, one small file, a tiny repository. Use grep or Read.

Pick a tool by what you know:
- Callers, usages, impact of X: find_references(X) first. view callers: each caller once, with its line; files: the files to change.
- Know the name: inspect_symbol(symbol, or symbols: up to 5) gives definition, signature, snippet, callers, ADRs. Qualify it (Config::new) or pass file_path if ambiguous.
- Don't know the name: search_symbols(query: "retry backoff").
- Know a location (stack trace, diff, grep hits): get_enclosing_scope(file_path, line or lines; or at: ["path:line", ..]) names the containing function; resolve_definition(file_path, line, col) jumps to a definition.
- Outline, signatures, structure: get_file_outline(file_path) before reading a file; get_crate_outline(crate_name); get_type_contract(type_name).
- About to change code: calculate_blast_radius(symbol or file_path); query_adrs for governing decisions; trace_call_hierarchy for multi-hop.

Reading answers:
- Lines are 1-based, columns 0-based. file_path is project-relative or absolute.
- Tools use the working directory's project (list_projects, switch_active_project). The index follows your edits (index_workspace rebuilds it); a first call may wait while it is built.
- complete means exhaustive over indexed files: don't re-grep it unless a CAVEAT applies. INDEXING or STALE means partial: retry shortly. notes explain empty results.
- Not seen: build-script output, other languages. Trait-object and closure calls resolve by name."#;

/// Instructions for [`ToolProfile::Core`]: names only the listed tools and says where the
/// rest live.
pub const SERVER_INSTRUCTIONS_CORE: &str = r#"Use Scryer instead of grep for code questions: who calls X, where X is defined, what a file contains, what contains this line, what breaks if X changes. Parsed code (Rust, Python, TypeScript), exact lines.

Not for: a literal string, log or error message, comment, config or non-code file, one small file, a tiny repository. Use grep or Read.

Pick a tool by what you know:
- Callers, usages, impact of X: find_references(X) first. view callers: each caller once, with its line; files: the files to change.
- Know the name: inspect_symbol(symbol, or symbols: up to 5) gives definition, signature, snippet, callers, ADRs. Qualify it (Config::new) or pass file_path if ambiguous.
- Don't know the name: search_symbols(query: "retry backoff").
- Know a location (stack trace, diff, grep hits): get_enclosing_scope(file_path, line or lines; or at: ["path:line", ..]) names the containing function and its code.
- Outline, signatures: get_file_outline(file_path) before reading a file.
- About to change code: calculate_blast_radius(symbol or file_path) for what depends on it.

Call graphs, type contracts, ADRs and project admin are not listed here: run `scryer --help` for the CLI, or start the server with `--tools full`.

Reading answers:
- Lines are 1-based, columns 0-based. file_path is project-relative or absolute.
- Tools use the working directory's project. The index follows your edits; a first call may wait while it is built.
- complete means exhaustive over indexed files: don't re-grep it unless a CAVEAT applies. INDEXING or STALE means partial: retry shortly. notes explain empty results.
- Not seen: build-script output, other languages. Trait-object and closure calls resolve by name."#;

/// The instructions a session sends at `initialize`.
pub fn server_instructions(profile: ToolProfile) -> &'static str {
    match profile {
        ToolProfile::Core => SERVER_INSTRUCTIONS_CORE,
        ToolProfile::Full => SERVER_INSTRUCTIONS_FULL,
    }
}

/// The full-profile instructions (the default).
pub const SERVER_INSTRUCTIONS: &str = SERVER_INSTRUCTIONS_FULL;

#[cfg(test)]
mod instructions_tests {
    use super::server_instructions;
    use crate::session::{AlwaysLoad, ToolProfile};

    /// Every tool the instructions name must be listed in the profile, and every listed tool
    /// must be reachable from them.
    fn check_instructions_match_profile(profile: ToolProfile) {
        let text = server_instructions(profile);
        let tools: Vec<String> = crate::tools::tool_definitions_for(profile, AlwaysLoad::None)
            .iter()
            .map(|t| t.name.to_string())
            .collect();
        let all: Vec<String> = crate::all_tool_definitions()
            .iter()
            .map(|t| t.name.to_string())
            .collect();

        // Words that look like tool names (snake_case with an underscore) in the text.
        for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
            let looks_like_tool = word.contains('_')
                && word.chars().all(|c| c.is_ascii_lowercase() || c == '_')
                && [
                    "search_",
                    "inspect_",
                    "get_",
                    "resolve_",
                    "calculate_",
                    "trace_",
                    "find_",
                    "query_",
                    "list_",
                    "index_",
                ]
                .iter()
                .any(|p| word.starts_with(p));
            if looks_like_tool {
                assert!(
                    all.iter().any(|t| t == word),
                    "{profile} instructions mention unknown tool '{word}'"
                );
                assert!(
                    tools.iter().any(|t| t == word),
                    "{profile} instructions mention '{word}', which the profile does not list"
                );
            }
        }

        // The administration tools that agents rarely need are deliberately not listed.
        let optional = [
            "switch_active_project",
            "delete_project",
            "get_indexing_status",
            "get_token_savings_metrics",
            "record_adr",
            "delete_adr",
        ];
        for tool in &tools {
            assert!(
                text.contains(tool.as_str()) || optional.contains(&tool.as_str()),
                "{profile} tool '{tool}' is not reachable from the server instructions"
            );
        }
        // Claude Code truncates instructions at 2,048 characters, silently.
        assert!(
            text.len() <= 1_800,
            "{profile} instructions are {} chars",
            text.len()
        );
    }

    #[test]
    fn full_instructions_name_exactly_the_real_tools() {
        check_instructions_match_profile(ToolProfile::Full);
    }

    #[test]
    fn core_instructions_name_only_the_core_tools() {
        check_instructions_match_profile(ToolProfile::Core);
    }
}